DEV Community

loading...

Compare Scopes of the var and let Keywords

rthefounding profile image Randy Rivera ・1 min read
  • Let's give you an example:
function checkScope() {
  var i = 'function scope';
  if (true) {
    i = 'block scope';
    console.log('Block scope i is: ', i);
  }
  console.log('Function scope i is: ', i);
  return i;
}
Enter fullscreen mode Exit fullscreen mode
console.log(checkScope()); will display 
Block scope i is:  block scope
Function scope i is:  block scope
block scope
Enter fullscreen mode Exit fullscreen mode
  • Let's Fix the code so that i declared in the if statement is a separate variable than i declared in the first line of the function. Just be certain not to use the var keyword anywhere in your code.
function checkScope() {
  let i = 'function scope';
  if (true) {
    let i = 'block scope';
    console.log('Block scope i is: ', i);
  }
  console.log('Function scope i is: ', i);
  return i;
}
Enter fullscreen mode Exit fullscreen mode
console.log(checkScope()); will display 
Block scope i is:  block scope
Function scope i is:  function scope
function scope
Enter fullscreen mode Exit fullscreen mode

This challenge is designed to show the difference between how var and let keywords assign scope to the declared variable. When programming a function similar to the one used in this exercise, it is often better to use different variable names to avoid confusion.

Discussion (1)

Collapse
cariehl profile image
Cooper Riehl

Short, sweet, and to the point. Thanks for sharing!

Forem Open with the Forem app