Previous Page : JavaScript Data Types

In JavaScript, a function is a block of code that can be reused multiple times. Functions are declared using the function keyword, followed by the function name and a set of parentheses. The code that makes up the function is enclosed in curly braces.

For example:

function greet() {
  console.log("Hello, world!");
}

Functions can also be assigned to variables, which is known as a function expression. When a function is assigned to a variable, the variable is known as a function object or a function reference.

Functions can also be passed as arguments to other functions, or returned as values from other functions. This is known as higher-order functions.

JavaScript also has arrow functions, introduced in ECMAScript 6. An arrow function is a shorthand syntax for creating a function. They are useful when you have a simple one-line function.

let greet = (name) => console.log("Hello, " + name + "!");

JavaScript also provides several built-in functions, such as Math.random(), parseInt(), parseFloat(), Date(), and many others.

Functions are a fundamental building block in JavaScript and are used to organize and structure code. They allow you to create reusable code, which can be called multiple times and can help to make your code more readable and maintainable.