Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

JavaScript - Functions and Scope

Functions and Scope

Functions and scope are fundamental concepts in JavaScript that allow you to organize and manage your code. Functions are blocks of reusable code, while scope defines the visibility and accessibility of variables and functions in different parts of your code. Here's an overview of functions and scope in JavaScript:

Functions:

A function is a reusable block of code that performs a specific task or set of tasks. Functions help in organizing code, promoting reusability, and making the code more modular.

function greet(name) {
  console.log(`Hello, ${name}!`);
}

// Call the function
greet("John"); // Output: "Hello, John!"
 

Functions can take parameters (inputs) and return a value (output). In JavaScript, functions are first-class citizens, which means they can be assigned to variables, passed as arguments, and returned from other functions.

// Function expression
const multiply = function(x, y) {
  return x * y;
};

let result = multiply(3, 4); // result is 12
 

Function Scope:

Variables declared within a function are locally scoped, meaning they are only accessible within that function.

function myFunction() {
  let localVar = "I'm a local variable";
  console.log(localVar);
}

myFunction(); // Output: "I'm a local variable"
console.log(localVar); // Error: localVar is not defined
 

Global Scope:

Variables declared outside of any function, or without the let, const, or var keyword, are considered global and can be accessed from anywhere in the code.

let globalVar = "I'm a global variable";

function myFunction() {
  console.log(globalVar);
}

myFunction(); // Output: "I'm a global variable"
 

Lexical Scope (Closures):

Functions in JavaScript have access to variables defined in their outer scope. This is known as lexical scope or closure.

dfunction outerFunction() {
  let outerVar = "I'm from outer function";

  function innerFunction() {
    console.log(outerVar);
  }

  return innerFunction;
}

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

Arrow Functions:

Arrow functions provide a more concise way to write functions, especially for simple, one-line functions.

const add = (x, y) => x + y;

let result = add(2, 3); // result is 5
 

Arrow functions do not have their own this value, which can lead to differences in behavior compared to regular functions.