ES6 JavaScript & TypeScript
Specialist training and resources for Angular & JavaScript. https://codecraft.tv/courses/angular/es6-typescript/classinterface/
by Rafa Ola
JavaScript
/********************************************* Let **************************************************/
function hello() {
var a = "function";
for (var i = 0; i < 5; i++) {
let a = "block";
}
console.log('Section[LET]: '+ a);
}
hello();
//You might expect
// 0
// 1
// 2
// 3
// 4 ---> Prints 4,4,4,4,4
/* The reason for this is that the variable y is not block level, it doesn’t only exist inside its enclosing {} In fact it’s a global variable and by the time any of the functions are called it’s already been set to 4.*/
var funcs = [];
for (var i = 0; i < 5; i += 1) {
var y = i;
funcs.push(function () {
console.log('Section[LET]: '+ y);
})
}
funcs.forEach(function (func) {
func()
});
// Replacing using "LET"
var funcs = [];
for (var i = 0; i < 5; i += 1) {
let y = i;
funcs.push(function () {
console.log('Section[LET]: '+ y);
})
}
funcs.forEach(function (func) {
func()
});
//The for loop short-cut
/* let */
var funcs = [];
for (let i = 0; i < 5; i += 1) {
funcs.push(function () {
console.log('Section[LET] : '+ i);
})
}
funcs.forEach(function (func) {
func()
});
//////////////////////////////////* Const */??????????????????????????????????
//////////////////////////////////**Immutable variable**////////////////////////////////
// But we can however mutate, make changes to, the object foo points to, like so:
const foo = {};
foo['prop'] = "Moo"; // This works!
console.log('Section[OBJ PRO] : '+foo);
/* To force Object.freeze(…) to throw an error we must remember to be in "use strict" mode, like so:*/
// If we want the value of foo to be immutable we have to freeze it using Object.freeze(…).
// When we freeze an object we can’t change it, we can’t add properties or change the values of properties, like so:
//'use strict';
//const foo = Object.freeze({});
//foo.prop = 123; // SyntaxError: Identifier 'foo' has already been declared
/** Main ***/
const foo1 =...