JavaScript functions
JavaScript functions are one of the building blocks of the language and are used to perform a specific task or calculation. Functions are reusable blocks of code that can be called multiple times with different inputs. Function will act as a reusable code block to use again as needed.
A function in JavaScript is defined using the function
keyword followed by a function name, a list of parameters enclosed in parentheses, and the function body enclosed in curly braces. Here's an example of a simple function that adds two numbers:
1function add(num1, num2) { 2 return num1 + num2; 3}
To call the function, we simply use its name followed by the arguments in parentheses:
1let result = add(3, 2); 2console.log(result); // 5
Functions in JavaScript can also have optional parameters, which can be specified using default values in the function definition. For example:
1function greet(name = "Max") { 2 console.log("Hello, " + name); 3} 4 5greet("Kim"); // Hello, Kim 6greet(); // Hello, Max
Another powerful feature of JavaScript functions is the ability to return a value. The return
statement is used to specify the value that the function should return. For example:
1function square(x) { 2 return x * x; 3} 4 5let result = square(5); 6console.log(result); // 25
In addition to named functions, JavaScript also supports anonymous functions, which are functions without a name. Anonymous functions are often used as arguments for other functions or as immediately-invoked function expressions (IIFEs).
1(function () { 2 console.log("Hello from an anonymous function!"); 3})();
Functions in JavaScript are a powerful tool that allow us to encapsulate and reuse logic, making our code more modular and maintainable. They are an essential aspect of the language and are used in a wide range of applications.