Skip to content

Instantly share code, notes, and snippets.

@BigaDev
Last active January 6, 2017 10:13
Show Gist options
  • Save BigaDev/09d030ca1c350655eb7cac10a6cb9ee0 to your computer and use it in GitHub Desktop.
Save BigaDev/09d030ca1c350655eb7cac10a6cb9ee0 to your computer and use it in GitHub Desktop.
ES6
// how come that return v in the else block will not raise error
function getx(c) {
if (c) {
var v = "dada"
return v;
} else {
return v;
}
}
// JS engine will will hosit var v into top of the function
function getx(c) {
var v;
if (c) {
v = "dada"
return v;
} else {
return v;
}
}
// try getx(true) , getx(false)
// the problem here is v scope will be for function not only in the if block
// by using ECMAScript 6 version we can force varible into specific scope
// here it will raise error because v is only defined in if statement scope
function getx(c) {
if (c) {
let v = "dada"
return v;
} else {
return v;
}
}
// correct ECMAScript 6 version
function getx(c) {
if (c) {
let v = "dada"
return v;
} else {
return null;
}
}
// example 1
var x = 3;
if (condition) {
let x = 2;
console.log(x); // print 2
}
console.log(x); // print 3
// example 2
for (var i = 0; i < 10; i++) {
console.log(i);
}
console.log(i); // i is still accessible here
for (let i = 0; i < 10; i++) {
console.log(i);
}
console.log(i); // throw error
// constants
// constants their values cannot be changed once initialized
// also constants like let accessible only in it's block
const x = 2;
// note const protect object from changing it's reference not value ex:
const user = {
name: "",
age: 0
}
// works
user.name = "Biga";
user.age = 25;
// throw error
user = {
name: "Biga",
age: 25
}
// so the final rule : const prevents modification of the binding, not modification of the bound value.
// let and const with GLOBAL/window scope
// GLOBAL in Node.js
// window in browser
// let and const are more safer than var by protecting your object from global/window scope
let x = 5;
const y = 10;
var z = 15;
console.log(GLOBAL.x); // print undefined
console.log(GLOBAL.y); // print undefined
console.log(GLOBAL.z); // print 15
// also let and const protect your variable from using before defination
// here remember hositing !
console.log(p); // it will print undefined
var p = 4;
// but using let or const this will raise an error
console.log(p); // raise error
let p = 5;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment