DEV Community

vishwa v
vishwa v

Posted on

Function(expression,arrow)

What is a Function Expression?
A function expression is a function stored in a variable.

// Standard Function
function multiply(a, b) {
  return a * b;
}

// Function Expression
const multiply = function(a, b) {
  return a * b;
};
Enter fullscreen mode Exit fullscreen mode

Anonymous Functions
Function expressions are commonly used to create anonymous functions.

The function above is actually function without a name.

Functions stored in variables do not need names.

The variable name is used to call the function.

Functions vs. Function Expressions
JavaScript functions are defined with the function keyword.

JavaScript functions can be defined in different ways.

In JavaScript, function declarations and function expression refer to different ways of defining functions, their different syntax and how they are handled:

They both work the same when you call them.

The difference is when they become available in your code.

Hoisting
Function declarations can be called before they are defined.

Function expressions can not be called before they are defined.

Function declarations are "hoisted" to the top of their scope. This means you can call a function before it is defined in the code:

let sum = add(2, 3); // Will work

function add(a, b) {return a + b;}
Enter fullscreen mode Exit fullscreen mode

Function expressions are not hoisted in the same way as function declarations.

They are created when the execution reaches their definition, and cannot be called before that point:

let sum = add(2, 3); // ⛔ Will generate error

const add = function (a, b) {return a + b;};
Enter fullscreen mode Exit fullscreen mode

JavaScript Arrow Functions
Arrow Functions allow a shorter syntax for function expressions.

You can skip the function keyword, the return keyword, and the curly brackets:

const multiply = (a, b) => a * b;
Enter fullscreen mode Exit fullscreen mode

If the function body contains only one statement:

You can remove the word function, the curly brackets and the return keyword.

Arrow functions are not hoisted.

Top comments (0)