Skip to main content

Command Palette

Search for a command to run...

Function in JS

Published
Function in JS

A function is a reusable set of instructions.
It is a block of code designed to perform a specific action.

In JavaScript, functions are first-class citizens, which means they can be:

  • stored in variables

  • passed as arguments

  • returned from other functions


Function Declaration

When we write a function with a function name, it is called a function declaration.

Function declarations are fully hoisted in memory, so they can be used before their declaration in the code.

Example:

function greet(name) {
    return `Hello, ${name}!`;
}

Anonymous functions cannot be used directly in function declarations.

Example of an anonymous function:

function() {}

This will not work as a function declaration because it has no name.


Function Expression

When we assign a function to a variable, it is called a function expression.

Function expressions are not fully hoisted, so they cannot be used before they are defined.

Example:

const greet = function(name) {
    return `Hello, ${name}!`;
};

A function expression can be an anonymous function.

Example:

const anonymous = function() {};

It can also be a named function expression.

Example:

const named = function func() {};

Hoisting Difference

We can see the difference using the following examples.

Function Declaration (Works)

sayHello("John"); // "Hello, John!"

function sayHello(name) {
    return `Hello, ${name}!`;
}

Function Expression (Error)

sayHi("John"); // ReferenceError: Cannot access before initialization

const sayHi = function(name) {
    return `Hi, ${name}!`;
};