×
☰ See All Chapters

JavaScript ES6 Variables

A variable is a literal (value) assigned to an identifier, so you can reference and use it later in the program. A variable is used to store information like text, numbers, arrays, date etc…  When a variable is declared, it can be retrieved and manipulated over and over again in your script. The assignment operator (=) used to assign value to a variable. 

JavaScript is "untyped" language. JavaScript variables do not have any type attached to them; you can assign value with any type. Once you assign a specific type value.

In JavaScript ES5 variables are declared using var keyword, In JavaScript ES6, variable declarations can be done by using with let or const keywords also.

JavaScript ES6 syntax of declaring a variables

 

 

Syntax

Example

Variable declaration

var variableName;

let variableName;

var xyz;

let xyz;

Variable declaration and initialization

var variableName = variableValue;

let variableName = variableValue;

const variableName = variableValue;

var xyz = 3;

let xyz= 3;

const xyz = 3;

const variables declaration and initialization cannot be done in separate line. Only let and var variables can be declared and initialized in separate lines.

javascript-es6-variables-0
 

if a variable is declared with const, its value is expected to remain constant throughout the block. Any attempt to change the variable's value will result in a compiler error.

javascript-es6-variables-1
 

To test JavaScript ES6 code you can run it on Chrome DevTools Console window.  To start a new line in Chrome console window, after typing out the first line, instead of hitting enter, hit shift + enter. This will bring you the next line without executing the code. So, when you are done, hit enter, it will execute all the code you just wrote. Another option is to click on 'Sources', click the double arrow button next to 'Page', and click on 'Snippets'. There you can press the '+ New Snippet' button and write your code there. When you are done writing your code, press Ctrl + Enter and it will run your code and open the console below your code snippet. This is better for writing multiple lines of code because you can go back and edit your snippet and re-run more easily than re-typing the whole thing in the console.

javascript-es6-variables-2
 

If you don't initialize the variable when you declare it, it will have the undefined value until you assign a value to it.

 

javascript-es6-variables-3
 

You can redeclare the var many times, overriding it. But you cannot redeclare the let.

javascript-es6-variables-4
 

You can also declare multiple variables either var or let at once in the same statement:

javascript-es6-variables-5
 

All Chapters
Author