JavaScript

Const Function Expression in JavaScript

A function is a sequence of commands that perform an operation or calculate a value. A function statement declares a function that will be executed only when called. A function expression is extremely like a function declaration except that a function expression is a function of a variable and executes the function using the variable’s name.

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:

const varName = function (parameters){

// 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:

const func = function (x,y,z){

return x * (y * z);

}

Execute the function with a variable name by passing numbers “2”, “8”, and “4” as arguments:

console.log(func(2, 8, 4));

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”:

func = function (x,y,z){

return x + (y + z);

}

While calling the function with the variable name, it will display an error:

console.log(func(12, 6, 24));

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.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.