The scope of const variables

The const variables are block-scoped variables, that is, they follow the same scoping rules as the variables that are declared using the let keyword. The following example demonstrates the scope of the constant variables:

const a = 12; // accessible globallyfunction myFunction() {  console.log(a);  const b = 13; // accessible throughout function  if(true) {    const c = 14; // accessible throughout the "if" statement    console.log(b);  }console.log(c);}myFunction();

The output of the preceding code is:

1213ReferenceError Exception

Here, we can see that constant variables behave in the same way as block-scoped variables when it comes to scoping rules.

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.