Variables and Constants in ES6 | Develandoo | Blog

Variables and Constants in ES6

I decided to turn to the theme of how  can we declare variables in .

Almost everyone knows that  {var} keyword has been with us since the very beginning of JavaScript. In ES6 we have new ways to declare variables and even constants. If you have any experience with JavaScript, you probably know at least something about variables and scope. We define variable using {var} keyword.

var variable = null;

You’ll probably also know that a variable is in the global scope if declared outside of a function, and the local scope if declared inside a function.

That means, we cannot access to local variables outside of the function scope, but we can access to global variables into the function scope, with the help of closures. But the confusing part here is that, only the way to define a local variable is to use function scope. Variables defined in a block, such as the body of an if statement, can be accessed from the enclosing function. They can even be accessed before the variable is declared.

.Block level scope with let

Variables declared with the let keyword work in a similar way with those declared with var, in addition they use block level scoping instead of function level. If we adapt the previous example to declare global Var with let, and run it in browser that supports the keyword the output will be ‘global’;

That means let has block level scope, all variables declared in blocks using let keyword can be modified only in that blocks where they were declared.

.Declaring constants with const

As well as variables, many languages have the concept of constants. That is, variables where you can not change the value once it has been initialized. JavaScript lacks this ability, although if you have an object, you can freeze it using Object.freeze in ES5.

The Object.freeze() method freezes an object, it means it prevents new properties from being added to it, prevents existing properties from being removed, and prevents existing properties, or their enumerability, configurability, or writability, from being changed. In essence the object is made effectively immutable. The method returns the object being frozen.

With ES6, we will get this ability directly with the new const keyword. As you  expect, once you have declared a const, the value can’t be changed.

If you this code, at first it will print the value of CONSTANT_VAR into the console, then you will land up with an error, something like this (Uncaught TypeError: Assignment to constant variable.)

This much concerning Variables and Constants in ES6.

  • Topics:
  • JavaScript

Top Stories

High Five! You just read 2 awesome articles, in row. You may want to subscribe to our blog newsletter for new blog posts.