This tutorial will describe the JavaScript const function expression.
What is Const Function Expression in JavaScript?
The const function expression is the function assigned to a “const” variable. The “const” keyword was introduced in ES6. Variables or functions defined with “const” cannot be “redeclared”, or “reassigned” and are “block-scoped”. A value is created as a read-only reference by the “const” declaration.
Syntax
For using a “const” function expression in JavaScript, use the below-given syntax:
// return statement
}
In const function expression syntax:
“varName” is the name of a constant variable for the const function expression.
Let’s try an example to see what is the const function expression and how it works.
Example
Create a variable “func” with the keyword “const”, and assign a function with three parameters to it, that will return the product of three numbers:
return x * (y * z);
}
Execute the function with a variable name by passing numbers “2”, “8”, and “4” as arguments:
Output
The output displays the product of numbers passed in a const function expression on the console.
As discussed above, the keyword “const” doesn’t allow “redeclared” and “reassigned”. Here, in below code snippet, define a new function expression that will return the sum of the three numbers and store it in an already created constant variable “func”:
return x + (y + z);
}
While calling the function with the variable name, it will display an error:
Output
The output shows an error because of assigning a new function expression to the “func” variable.
Conclusion
The const function expression is the function assigned to a “const” variable. A function expression is extremely like a function declaration except that a function expression is a function of a variable and executes using the variable’s name. When a function expression is assigned to a const variable, the function definition is unchanged because the const variable cannot be changed.