The function keyword can be used to define a function inside an expression.
Syntax:
let myFunction = function [function name]([parameter 1 [, parameter 2[, ..., parameter N]]]) { statements};
The name of the function in the syntax above is optional. A function without a name will be called anonymous function.
//anonymous function
var myFunction = function() {
return "statements"
}
console.log(myFunction()); //statements
If we include the name then the function will be called named function.
//named function
function hello(name) {
return `Hello ${name}!`;
}
console.log(hello('YogeshChauhan.com')); // YogeshChauhan.com
Function Expression
A JavaScript function can also be defined using an expression.
For example,
function calculateRectangleArea(width, height) {
return width * height;
}
console.log(calculateRectangleArea(5, 6)); // 30
Named Function Expression
Whenever we need to refer to the current function inside the function body, we need to create a named function expression. This name is then local only to the function body (scope).
For example,
var foo = function() {}
foo.name // "foo"
var foo2 = foo
foo2.name // "foo"
var bar = function baz() {}
bar.name // "baz"
In the example above, The variable the function expression is assigned to will have a name property.
The name doesn’t change if it’s assigned to a different variable. If function name is omitted, it will be the variable name. If function name is present, it will be the function name.
Difference between Function Expression and Function Declaration
The main difference between a function expression and a function declaration is the function name.
A function expression is very similar to function declaration and it has almost the same syntax as a function declaration.
//Function Expression
alert(foo());
var foo = function() { return 5; }
//ERROR! foo wasn't loaded yet
//Function Declaration example
alert(foo());
function foo() { return 5; }
//Alerts 5.
So, as we can see in the examples above, Function declarations load before any code is executed while Function expressions load only when the interpreter reaches that line of code.
Arrow Function
Arrow functions allow us to write shorter function syntax.
For example,
fruit = () => {
return "banana";
}
fruit(); // banana
It gets even shorter! If the function has only one statement, and the statement returns a value, we can remove the brackets and the return keyword. For example,
hello = () => "Hello World!";
If we want to pass parameters, we can pass them inside the parentheses or we can skip the parentheses if we have only one parameter. For example,
hello = (val) => "Hello " + val; OR hello = val => "Hello " + val;
What About this keyword?
Handling of this is also different in arrow functions compared to regular functions. With arrow functions there are no binding of this and this keyword always represents the object that defined the arrow function.
Let’s take a look at examples of both functions.
Example 1 demonstrates that in a regular function, the “this” keyword represents different objects depending on how the function was called.
Example 2 demonstrates that in Arrow Functions, the “this” keyword represents the object that owns the function, no matter who calls the function.
//Example 1
<button id="btn1">Click Me!</button>
<p id="example1"></p>
<script>
var hello;
hello = function() {
document.getElementById("example1").innerHTML += this;
}
//The window object calls the function:
window.addEventListener("load", hello);
//A button object calls the function:
document.getElementById("btn1").addEventListener("click", hello);
</script>
//output
[object HTMLButtonElement]
//Example 2
<button id="btn2">Click Me!</button>
<p id="example2"></p>
<script>
var hello;
hello = () => {
document.getElementById("example2").innerHTML += this;
}
//The window object calls the function:
window.addEventListener("load", hello);
//A button object calls the function:
document.getElementById("btn2").addEventListener("click", hello);
</script>
//output
[object Window]
Nested Functions
Prior to JavaScript 1.2, function definition was allowed only in top level global code, but JavaScript 1.2 allows function definitions to be nested within other functions as well.
All functions have access to the global scope. In other words, all functions have access to the scope “above” (outside) them. So, Nested functions have access to the scope “above” (outside) them.
In this example 1, the inner function plus() has access to the counter variable in the parent function.
<p id="demo">0</p>
<script>
document.getElementById("demo").innerHTML = add();
function add() {
var counter = 0;
function plus() {counter += 1;}
plus();
return counter;
}
</script>
//Output
1
anonymous arrow declaration Expression functions nested