Function level scoping vs block level scoping in ES6

I’m learning the updated ES6 for javascript. Testing to make sure I understand the difference between the two. ECMA Script 5 has Function level scoping where variables that are specific to the function block and or parent function, along with block level scoping that applies more globally.

What makes ES6 daper is because using let and const you declar to the browser more easily what variables will be dynamic and which ones are static for the better organization of the code? Tell me if I’m wrong or right, please? ::wince::

Prior to ES6, JavaScript only had function level scoping:

var foo = "Foo";

function childScope() {
  var bar = "Bar";

  console.log(foo);
  // "Foo"
}

console.log(bar);
// Uncaught ReferenceError: bar is not defined

Variables defined in a parent scope are available to functions defined within that scope, but variables defined in nested (i.e. child) scopes aren’t available to the parent.

With ES6, we have let and const, which allow block level scoping:

// The curly braces on the IF statement create a new block scope
if (true) {
  var foo = 'Foo';
  let bar = 'Bar';
}

console.log(foo);
// "Foo"

console.log(bar);
// Uncaught ReferenceError: bar is not defined

This is useful in situations such as when you define temporary variables within loops, as they won’t be available outside of the loop. This cuts down on potential sources of bugs.

The difference between let and const is that once you’ve declared a variable with const you can’t change that variable to point at a different value:

const answer = 42;

answer = 69;
// Uncaught TypeError: Assignment to constant variable.

Again, this helps prevent subtle bugs introduced by accidentally altering the value of variables. This article goes into more depth about the differences between var, let, and const.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.