🥜Functions

In JavaScript, a function is a block of code that performs a specific task. It can optionally take input in the form of parameters, and can optionally return output in the form of a return value.

Here is the basic syntax for defining a function in JavaScript:

function functionName(parameter1, parameter2, ...) {
  // code to be executed
}

Here is an example of a function that takes two parameters, adds them together, and returns the result:

function add(x, y) {
  return x + y;
}

let result = add(2, 3);  // result will be 5

Functions can be called or invoked by using their function name followed by parentheses, and passing in any required arguments.

It's also possible to define functions using the function expression syntax:

let functionName = function(parameter1, parameter2, ...) {
  // code to be executed
};

And in modern JavaScript (ES6+), you can use the arrow function syntax to define a function:

let functionName = (parameter1, parameter2, ...) => {
  // code to be executed
};

Last updated