Function in javaScript

Function in javaScript

Functions in JavaScript are blocks of code that can be called and executed multiple times. Functions are used to perform specific tasks or calculations, and they can take arguments (inputs) and return values (outputs). In JavaScript, functions are first-class citizens, which means they can be assigned to variables, passed as arguments to other functions, and returned from functions.

There are several ways to define functions in JavaScript:

1.Function Declaration :

A function declaration starts with the keyword function, followed by the name of the function, a list of parameters enclosed in parentheses, and the function body enclosed in curly braces. Here is an example:

function add(a, b) {

return a + b;

}

2.Function Expression :

A function expression is a function that is assigned to a variable. It starts with the keyword function, followed by an optional name, a list of parameters enclosed in parentheses, and the function body enclosed in curly braces. Here is an example:

const add = function(a, b) {

return a + b;

};

3.Arrow Function:

An arrow function is a shorthand syntax for defining a function expression. It starts with a list of parameters enclosed in parentheses (optional if there's only one parameter), followed by the arrow =>, and then the function body enclosed in curly braces (optional if there's only one expression to return). Here is an example:

const add = (a, b) => a + b;

4.Function Constructor :

A function constructor is a built-in function that creates a new function object. It takes a list of parameter names and a string representing the function body as arguments. Here is an example:

const add = new Function(‘a’, ‘b’,

‘return a + b’);

Once a function is defined, it can be called by its name followed by a list of arguments enclosed in parentheses. Here is an example of calling a function:

const result = add(2, 3);

console.log(result); // Output: 5

Functions can also be nested inside other functions, and they have their own scope, which means they can access variables defined in their parent functions. Functions can also be used as callbacks, which are functions that are passed as arguments to other functions and are called when certain events occur or when certain conditions are met.

click here to learn more