DEV Community

Ruxin Qu
Ruxin Qu

Posted on

JavaScript: global scope & block scope

  • A global scope content exists throughout the file.
  • A block scope content only exists inside the block.

example 1: In this example, dogName is a local variable inside the function block.

const nameYourDog = () =>{
  let dogName = 'dog';        //dogName is inside the function block
  let ownerName = 'Ruxin';    //ownerName is inside the function block
  if (ownerName === 'Ruxin'){
    let dogName = 'Dahuang';    //declare a new dogName variable inside if block, only change the value of dogName inside the if block
    console.log(dogName);   
  }
  console.log(dogName);  //the dogName variable outside of if block still remain unchanged.
}
nameYourDog();
console.log(dogName);   // the variable is undefined outside the function
Enter fullscreen mode Exit fullscreen mode

output: Dahuang dog undefined


example 2: In this example, we don't declare a new dogName variable inside the if block

const nameYourDog = () =>{
  let dogName = 'dog';
  let ownerName = 'Ruxin';
  if (ownerName === 'Ruxin'){
    dogName = 'Dahuang';     //change the dogName value to Dahuang.
    console.log(dogName);
  }
  console.log(dogName);    // the value of dogName is changed outside of if block.
}
nameYourDog();
console.log(dogName);
Enter fullscreen mode Exit fullscreen mode

Output: Dahuang Dahuang undefined


example 3: declare a global variable.

let dogName = 'dog';      //global variable 
let ownerName = 'Ruxin';
const nameYourDog = () =>{
  if (ownerName === 'Ruxin'){
    let dogName = 'Dahuang';    //declare a new local variable and give a value
    console.log(dogName);
  }
  console.log(dogName);   //the global value can be accessed throughout the file
}
nameYourDog();
console.log(dogName);    
Enter fullscreen mode Exit fullscreen mode

Output: Dahuang dog dog

Top comments (0)