0
0
Javascriptprogramming~5 mins

Function expression in Javascript

Choose your learning style9 modes available
Introduction

A function expression lets you create a function and save it in a variable. This helps you use the function later or pass it around like any other value.

When you want to store a function in a variable to use later.
When you want to pass a function as an argument to another function.
When you want to create a function without giving it a name (anonymous function).
When you want to write shorter code inside another function or event handler.
When you want to create functions dynamically during program execution.
Syntax
Javascript
const variableName = function(parameters) {
  // code to run
};

The function can be anonymous (no name) or named.

The function expression ends with a semicolon because it is an assignment.

Examples
This creates a function that prints 'Hello!' and stores it in the variable greet.
Javascript
const greet = function() {
  console.log('Hello!');
};
This function takes two numbers and returns their sum.
Javascript
const add = function(a, b) {
  return a + b;
};
This is a named function expression. The name name is local to the function itself.
Javascript
const sayName = function name() {
  console.log('My name is JavaScript');
};
Sample Program

This program creates a function expression that multiplies two numbers and then prints the result.

Javascript
const multiply = function(x, y) {
  return x * y;
};

console.log(multiply(4, 5));
OutputSuccess
Important Notes

Function expressions are not hoisted like function declarations, so you must define them before using.

You can use function expressions to create closures and keep data private.

Summary

Function expressions store functions in variables for flexible use.

They can be anonymous or named.

Use them when you want to pass functions around or create functions dynamically.