Skip to content

Instantly share code, notes, and snippets.

@4sskick
Created September 4, 2016 20:36
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save 4sskick/5c4305201010bd8b82ca0fd382f79b07 to your computer and use it in GitHub Desktop.
'let' + 'const' equivalent in ES5
As we knew that 'let & const' are not coming in ES5, those are coming in ES6 since 2015.
So to make these work like in latest version ECMA Scripts 2015, we can define it by ourself.
'const' - ES6
const a = 1;
'const' - ES5
var a = (function(){
var a = 1;
return function(){
a;
};
});
'let' - ES6
actually 'let' in ES6 has function to make scope in javascript.
Like in other language, when we define variable as global it can accessed everywhere even inside of looping/method as long in same class.
But in javascript, using 'let' in ES6 will be limited scope of variables.
example - ES6.
let a = -1; //this can be accessed everywhere/global, even inside of 'if', 'for' & 'function()'
if(a === 1){
let b = 2;// b cannot be accessed outside the 'if'
}
for(let c = 0; c < 10; c++){
...//so do the 'c' cannot be acccessed outside of 'for'
}
function declareAnotherOne(){
let d = 5;//undefined outside of function
}
example - ES5
var a = 1; // global variable
if(a === 1){
var b = 3; // global variable
}
for(var c = 0; c < 10; c++){
...// var c is global variable
}
function declareAnotherOne(){
var d = 5;// non-global variable
}
In ES5 every var that were declared are going to 'global variable' and can be accessed everywhere,
but when it declare inside 'function()' the variable is not global anymore. The scope only iside the 'function()'.
For ES6, 'a' able to accessed everywhere (if & for). But no with 'b', 'c' even 'd',
they are going to be 'undefined' when you call it outside their scope.
Maybe the only solution to limiting access of variables in ES5 like 'let' ES6, put it inside 'function()'.
Here is simply explanation 'let' vs 'var'
'let' vs 'var'
function loop(arr) {
// i IS NOT known here
// j IS NOT known here
for( var i = 0; i < arr.length; i++ ) {
// i IS known here
}
// i IS known here
// j IS NOT known here
for( let j = 0; j < arr.length; j++ ) {
// j IS known here
}
// i IS known here
// j IS NOT known here
}
@nmvuong92
Copy link

good one

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment