Functions In JavaScript

 In JavaScript, functions are reusable blocks of code that perform a specific task or calculate a value. They are fundamental to JavaScript programming and are used to organize code, improve code reusability, and implement modular design patterns. Here's an overview of functions in JavaScript along with examples:

1. Function Declaration:

// Syntax: function functionName(parameters) { code to be executed }
function greet(name) {
  console.log("Hello, " + name + "!");
}

// Calling the function
greet("Alice"); // Output: Hello, Alice!

2. Function Expression:

// Anonymous function expression
let greet = function(name) {
  console.log("Hello, " + name + "!");
};

// Named function expression
let greet = function greet(name) {
  console.log("Hello, " + name + "!");
};

// Calling the function
greet("Bob"); // Output: Hello, Bob!

3. Arrow Functions (Introduced in ES6):

// Syntax: const functionName = (parameters) => { code to be executed }
const greet = (name) => {
  console.log("Hello, " + name + "!");
};

// Calling the function
greet("Charlie"); // Output: Hello, Charlie!

4. Returning Values:

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

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

5. Default Parameters:

function greet(name = "Guest") {
  console.log("Hello, " + name + "!");
}

greet(); // Output: Hello, Guest!
greet("David"); // Output: Hello, David!

6. Rest Parameters:

function sum(...numbers) {
  let total = 0;
  for (let num of numbers) {
    total += num;
  }
  return total;
}

console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(10, 20, 30, 40)); // Output: 100

7. Function Scope and Closures:

function outerFunction() {
  let outerVar = "I'm from outer function";
  
  function innerFunction() {
    console.log(outerVar);
  }
  
  return innerFunction;
}

let innerFunc = outerFunction();
innerFunc(); // Output: I'm from outer function

These examples cover the basic concepts of functions in JavaScript. Functions are versatile and powerful in JavaScript, allowing developers to create complex applications with ease.

Post a Comment

0 Comments