Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 4 - Functions

4.4 Scope Of Variables

Variable scope determines from where the variable is accessible. You have two types of variable scope available in JavaScript:

  1. Local variable: Defined within a function, only accessible from its parent function.
  2. Global variable: Defined outside of a function, can be accessible throughout the entire code.

Let's understand them through a practical example:

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

function example() {
    let localVar = "I'm a local variable";
    console.log(globalVar);  // Accessing global variable
    console.log(localVar);   // Accessing local variable

console.log(globalVar);  // Accessing global variable outside the function
console.log(localVar);  // This will cause an error because localVar is not accessible here

Here, the global variable globalVar can be accessed from the function example(), whereas the local variable localVar is only accessible inside the function example().