JAVASCRIPT FUNCTION
A JavaScript function is a block of code designed to perform a particular task.
Function Syntax
A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().
A JavaScript function is executed when "something" invokes it (calls it).
Tip : Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...)
1function name(parameter1, parameter2, parameter3) {
2 // code to be executed
3}
Function Return
Functions often compute a return value. The return value is "returned" back to the "caller":
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.
1// Function is called, the return value will end up in x
2let x = myFunction(4, 3);
3
4function myFunction(a, b) {
5// Function returns the product of a and b
6 return a * b;
7}
Functions Used as Variable Values
Functions can be used the same way as you use variables, in all types of formulas, assignments, and calculations.
1let x = toCelsius(77);
2let text = "The temperature is " + x + " Celsius";
Nested Functions
1function outerFunction(x) {
2 function innerFunction() {
3 // code to be executed
4 }
5 // more code
6}
In this example, the innerFunction is defined inside the outerFunction and can only be called from within that function.
In addition to these basic concepts, there are many other things you can do with functions in JavaScript, such as passing functions as arguments, creating anonymous functions, and using higher-order functions. These advanced techniques can make your code more efficient and flexible, and are essential tools for any JavaScript developer.
Arrow Functions
Arrow functions are often used when you want to create a small, one-line function that doesn't require a separate function keyword.
Functions can be defined inside other functions, which is known as "nesting." This is useful for creating smaller, reusable blocks of code that can be called from within the larger function.
1const square = (x) => {
2 return x * x;
3};