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


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.