JAVASCRIPT SCOPE
Links
// 73 - DIFFERENCES BETWEEN VAR AND LET
let catName = "Quincy";
var quote;
catName = "Beau";
function catTalk(){
"use strict";
catName = "Oliver";
quote = catName + " says Meow!";
}
console.log("Var vs Let");
console.log(catTalk());
// 74 - SCOPES OF VAR AND LET
// var are always accessible from anywhere
// let can be defined in multiple places block or outside
function checkScope(){
"use strict";
let i = "function scope";
if (true){
let i = "block scope";
console.log("Block scope i is: ", i);
}
console.log("Function scope i is: ", i);
return i;
}
console.log("Scope of Var and Let");
console.log(checkScope());
// 75 - CONST
function printManyTimes(str){
"use strict";
const SENTENCE = str + " is cool";
for (let i=0; i<str.length; i+=2){
console.log(SENTENCE);
}
}
console.log("Const");
console.log(printManyTimes("Tree"));
// 76 - MUTATE AN ARRAY DECLARED WITH CONST
const s = [5, 7, 2];
function editInPlace() {
"use strict";
s[0] = 2;[2,5,7];
s[0] = 5;
s[0] = 7;
}
editInPlace();
console.log("Mutate an array declared with const");
console.log(s);
// 77 - PREVENT OBJECT MUTATION
function freezeObj() {
"use strict";
const MATH_CONSTANTS = {
PI: 3.14
};
Object.freeze(MATH_CONSTANTS);
try {
MATH_CONSTANTS.PI = 99;
}catch( ex ) {
console.log(ex);
}
return MATH_CONSTANTS.PI;
}
console.log("PreventObjectMutation:");
const PI = freezeObj();