JS vars
by azhwani
JavaScript
/*
var is the keyword that we can use to declare a variable in JS;
var can declare GLOBAL or FUNCTION scoped variables; (example 1);
var accept redeclaration (example 2);
*/
// EXAMPLE 1
/*
+++ A function can change the value of a global variable if it does not have a decalared variable with same name; (shadowing)
+++ We can't use a local function scoped variable outside the function!
*/
var nbr=0;
function foo(){
var nbr=1;
}
alert(nbr);
foo();
alert(nbr);
// EXAMPLE 2
/*
*/
/*var nbr2=0;
var nbr2=5;
alert(nbr2);
*/
// EXAMPLE 3
/*
ALL VARIABLE DECALARED BY var HAVE ONLY TWO SCOPES : GLOBAL OR FUNCTION !
THERE IS NO BLOCK SCOPE WITH var !
IN THIS EXAMPLE nbr4 IS A GLOBAL SCOPED VARIABLE NOT A LOCAL VARIABLE!
EVERY VARIABLE DECLARED INSIDE A FUNCTION WITHOUT USING var IS A GLOBAL VARIABLE
*/
/*var nbr3 = 15;
if(nbr3 > 10){
var nbr4 = 20;
}
else{
var nbr4 = 40;
}
alert(nbr4) // 20
function boo(){
var nbr5 = 10;
nbr6 = 33;
}
boo();
alert(nbr6); // 33
alert(nbr5); // referenceError: nbr5 is not defined
*/
/*
let is another the keyword that we can use to declare a variable in JS;
let can declare GLOBAL (nbr7) OR FUNCTION (nbr8) OR BLOCK (nbr9) scoped variables; (example 4);
let doesnt accept redeclaration (example 5);
let doesnot have any relation with hoisting like var means we can use
a variable which has not been declared!
*/
// EXAMPLE 4
let nbr7 = 10;
function letfoo(){
nbr7 = 52;
let nbr8=1;
if(nbr7 > 0){
let nbr9 = 10;
}
alert(nbr8); // 1
alert(nbr9); // ReferenceError: nbr8 is not defined
}
alert(nbr7);
letfoo();
alert(nbr7);
// EXAMPLE 5
let nbr10 = 20;
//let nbr10 = 2; //error