Skip to content

Latest commit

 

History

History
91 lines (70 loc) · 2.26 KB

functions.md

File metadata and controls

91 lines (70 loc) · 2.26 KB

⚑ Functions

Functions are reusable blocks of code that perform specific tasks. It helps to organize the code, make it more modular, and for code reusability.

☴ Overview:

  1. Defining functions
  2. Calling functions
  3. Function arguments and return values
  4. Function Scope and closures
  5. Arrow functions

✦ Defining Functions:

The functions are usable before defining it.

Syntax:

function functionName(parameter1, parameter2, ...) {
  // Function body (statements to be executed)
  return value; // Optional: Returns a value
}
function greet(name) {
  console.log("Hello, " + name + "!");
}

✦ Calling Functions:

To use function in the JavaScript code, that need to be called where it is required.

Syntax:

functionName(argument1, argument2, ...);
greet("Kumar"); // Output: Hello, Kumar!

✦ Function Arguments and Return Values:

Arguments: Values passed to a function that accepts as parameter of it when it's called. Return Values: Values that a function can return to the where it was called or invoked using the return statement in the function.

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

let sum = add(1, 2);
console.log(sum); // Output: 3

✦ Function Scope and Closures:

Scope: The region of code where a variable or function is accessible. Closures: Functions that have access to variables from the outer scope, even after the outer scope has finished executing.

function outerFunction() {
  let x = 10;

  function innerFunction() {
    console.log(x); // Accesses the outer variable x
  }

  return innerFunction;
}

let closure = outerFunction();
closure(); // Output: 10

✦ Arrow Functions:

It is defined in a concise way or in shorthand form.

Syntax:

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

⇪ To Top

❮ Previous TopicNext Topic ❯

⌂ Goto Home Page