ES6 - const, let and var

/* const - if you’re setting a variable that you don’t plan on changing. - Protects and prevents your variables from reassignment. - In compiled languages, there is an increase in runtime efficiency of your code and thus an overall performance boost vs using plain ‘ol var. */ // Examples: // sometimes used as lowercase as when setting up your server. const express = require(‘express’); const app = express(); // sometimes uppercase. const DONT_CHANGE_ME_MAN = 'I ain’t changing for no one, man.'; // change attempt #1 const DONT_CHANGE_ME_MAN = 'I told I ain’t changing for no one.'; // change attempt #2 var DONT_CHANGE_ME_MAN = 'Still not changing, bro.'; // change attempt #3 DONT_CHANGE_ME_MAN = 'Haha, nice try, still not happening.'; // same error for all 3 attempts, const value stays the same: // Uncaught TypeError: Identifier ‘const DONT_CHANGE_ME_MAN’ has already been declared. // DONT_CHANGE_ME_MAN still results in “I ain’t changing for no one, man.” /* let - Scoping, your variable’s values are exactly as they should be in that current scope and they are not hoisted as with var. - Super useful if you don’t want your values to be overwritten, like in a for loop. - Beware: You may not always want to use let. For example in situation where variables aren’t as easily block scoped, var may be more convenient. */ // Example 1: // When using var what do we get? var bunny = "eat carrot"; if(bunny) { var bunny = "eat twig"; console.log(bunny); // "eat twig" } console.log(bunny); // "eat twig" // When using let what do we get? let bunny = "eat carrot"; if(bunny) { let bunny = "eat twig"; console.log(bunny); // "eat twig" } console.log(bunny); // "eat carrot" // Example 2: // with var. See example live: https://jsfiddle.net/maasha/gsewf5av/ for(var i = 0; i < 30; i++){ var div = document.createElement('div'); div.onclick = function() { alert("you clicked on a box " + i); }; document.getElementsByTagName('section')[0].appendChild(div); } // with let. See example live: https://jsfiddle.net/maasha/xwrq8d5j/ for(let i=0; i<30; i++) { var div=document.createElement(‘div’); div.onclick = function() { alert("you clicked on a box " + i); }; document.getElementsByTagName('section')[0].appendChild(div); }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.