Functions

Functions in JavaScript

Functions are reusable blocks of code that perform specific tasks. They are fundamental building blocks in JavaScript programming.

Function Declaration

function greet(name) {
  return "Hello, " + name + "!";
}

const message = greet("Alice");
console.log(message); // Output: Hello, Alice!

Function Expression

You can also define functions as expressions:

const add = function(a, b) {
  return a + b;
};

console.log(add(5, 3)); // Output: 8

Arrow Functions

ES6 introduced arrow functions, a concise syntax for writing functions:

const multiply = (a, b) => a * b;

console.log(multiply(4, 5)); // Output: 20

Default Parameters

function greet(name = "Guest") {
  return "Hello, " + name + "!";
}

console.log(greet());        // Output: Hello, Guest!
console.log(greet("Bob"));   // Output: Hello, Bob!