Andre DiCioccio

Law, Technology and Finance

ECMA Script Block Scoped Declarations

ECMA Script 6 has introduced the ability to use const and let instead of var to declare local variables.

The main benefit of this is that const and let are scoped to the block level (meaning their scope is confined to a blocked deliminated with curly brackets).

A further benefit of this new syntax is that any variables which are declared using the const keyword can only be assigned a value once and are effectively constants therefore.  If you attempt to assign a new value to one of these constants, the compiler will throw an error.  You should note of course that if you assign an object to a const, then the usual reference rules apply – meaning you can modify the contents of the object – just not the actual reference to the object itself.

USING const and let: 
const a = 1
let b = 'foo'

// Not allowed!
// a = 2

// Ok!
b = 'bar'

if (true) {
 const a = 3
}
How the output is compiled using Babel:
var a = 1;
var b = 'foo';

// Not allowed!
// a = 2

// Ok!
b = 'bar';

if (true) {
 var _a = 3;
}

This demonstrates how the Babel compiler tranforms the const declaration to a standard var declaration.  It is actually the Babel compiler which enforces the correct usage and block scoping, rather than the actual browser JavaScript engine.

 

Related articles

JavaScript ES7 Static Class Properties

In ES6 you can declare static functions which apply to ES6 classes but ES7 adds the ability to declare static properties also. A static property can be useful in a large number of situations, such as the following (contrived example): class Cat { static legCount = 4 } console.log(Cat.legCount) // 4  

Learn More

Apple Mac Keyboard Shortcuts and Symbols

Hi there, How many times have you looked at the Apple menu or some instructions and wondered what the keyboard symbols mean? I have been using Apple products for about 20 years now and still wonder what the little option symbol relates to on the keyboard. Here is a quick-reference that hopefully will assist some […]

Learn More

How to create a react-navigation StackNavigator

In a web browser, you can link to different pages using an anchor (<a>) tag. When the user clicks on a link, the URL is pushed to the browser history stack. When the user presses the back button, the browser pops the item from the top of the history stack, so the active page is […]

Learn More

Leave a Reply

Your email address will not be published. Required fields are marked *