Var, let and const variable declarations in ES6

Until ES5 JavaScript only had ‘var’ to declare variables. If you tried out other languages you might find it a bit strange or even a relief not having to think hard about what type of ┬ávariable you are creating. In most other languages you have to decide up front what data type it is, where the most used are: boolean,string,float and integer.

In general these declared variables is also block scoped meaning that they are only accessible from within the same block they are written. However in JavaScript, var declarations are function scoped. Which means that they can be accessed globally unless you put the var declaration within the function, then its only accessible within that function.
It’s therefor best practice to always wrap a function scope around your blocks of code to avoid bugs with Immediately Invoked Function Expressions,”IFFY”:

(function () { 
//code goes here
}());  

With ES6 ‘var’ becomes redundant for 99.99% of all code and you should have very good reason to use it. It’s like global variables in other languages, something that next to never should be used in order to avoid conflicts, performance and unexpected behaviour.

Instead of var, we now got to work with ‘let’ and ‘const’.

Both const and let are block scoped, which means that as long as they are between {} they will only be accessible within those brackets.

const stands for constant and just what it sounds like it should be used for constant values.
Always try to use const when you are declaring variables that won’t change it’s value, this is an important concept that will make the code more stable and readable. In all other cases, use let!

You might find it annoying that now suddenly you need to return data from functions, send in data in parameters more than you used to before when you worked with global or function scoped variables but that is a GOOD THING. It makes you a better developer and writing better code.

PS
Make sure you are using Babel for your projects if you are using this in production code 2017 as ES6 support is still limited.

Add your comment