Advertisement

Google Ad Slot: content-top

JS Functions


A function in JavaScript is a reusable block of code designed to perform a specific task. Functions make code modular, readable, and reusable.


Syntax:

function functionName(parameters) {
  // Function body
  return value;
}

Function Declaration:

A function declaration defines a named function using the function keyword.

Example
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // Output: Hello, Alice!

Try it yourself

Function Expression:

A function expression assigns a function to a variable.


Syntax:

const functionName = function(parameters) {
  // Function body
  return value;
}
Example
let greet = function(name) {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // Output: Hello, Alice!
Try it yourself

Arrow Functions (ES6):

Arrow functions provide a shorter syntax and automatically bind this.


Syntax:

const functionName = (parameters) => {
  // Function body
};
Example
const add = (a, b) => {
return a + b;
};
console.log(add(5, 3)); // Output: 8

// Single Parameter: Parentheses can be omitted
const greet = name => `Hello, ${name}`;
console.log(greet('Alice')); // Output: Hello, Alice!

// No Parameters: Use empty parentheses
const sayHi = () => console.log("Hi!");
sayHi();
Try it yourself

Immediately Invoked Function Expressions (IIFE):

An IIFE runs immediately after being defined.

Example
(function() {
console.log("I am an IIFE!"); // Output: I am an IIFE!
})();

// Arrow Function IIFE:
(() => {
console.log("IIFE with Arrow Function!"); // Output: IIFE with Arrow Function!
})();

Try it yourself