As you have seen in the previous examples, JavaScript functions are defined with the function
keyword.
Functions can also be defined with a built-in JavaScript function constructor called Function()
.
Example
let x = myFunction(4, 3);
You actually don't have to use the function constructor. The example above is the same as writing:
Example
let x = myFunction(4, 3);
Most of the time, you can avoid using the new
keyword in JavaScript.
Function Hoisting
Earlier in this tutorial, you learned about "hoisting" (JavaScript Hoisting).
Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope.
Hoisting applies to variable declarations and to function declarations.
Because of this, JavaScript functions can be called before they are declared:
function myFunction(y) {
return y * y;
}
Functions defined using an expression are not hoisted.
Self-Invoking Functions
Function expressions can be made "self-invoking".
A self-invoking expression is invoked (started) automatically, without being called.
Function expressions will execute automatically if the expression is followed by ().
You cannot self-invoke a function declaration.
You have to add parentheses around the function to indicate that it is a function expression:
Example
let x = "Hello!!"; // I will invoke myself
})();
The function above is actually an anonymous self-invoking function (function without name).
Functions Can Be Used as Values
JavaScript functions can be used as values:
Example
return a * b;
}
let x = myFunction(4, 3);
JavaScript functions can be used in expressions:
Example
Practice Excercise Practice now