In this first article of the series 'I Don't Know JS Yet' ', we will be looking at the various types of variable declaration along with their scope inside a particular program.
Declaration and Scope
Pre ES6 we only had the 'var' keyword available to us for declaration of variables inside a javascript program, which was said to be function-scoped. But after the release of ES6, we got two new keywords 'let' and 'const' for variables declaration which is said to be block-scoped.
To understand the difference between function scoped and block-scoped, let's look at the below two snippets of code.
πFunction scoped behaviour of var
var fname = "Captain"; //Global Scope
function displayN() {
var lname = "America";
console.log(`${fname} ${lname}`);
}
displayN();
console.log(`${fname} ${lname}`); //ReferenceError: lname is not defined
/*
Output:
Captain America
*/
Explanation π*When the program executes the first variable 'fname' is defined in the global scope (i.e, it is accessible throughout the program) and then the function displayN() is declared and called. Inside this function, the 'lname' variable is declared and accessible only inside the function and any attempt to call it outside the function will result in *'ReferenceError'.
πNote: Variable defined with 'var' in the global scope as well as inside a function scope can be updated at any point of the program.
πBlock scoped behaviour of let &const
let fname = "Captain"; //Global Scope
const color = "Red and Blue"; //Global Scope
function superHero() {
let lname = "Marvel";
console.log(`${fname} ${lname}`);
if(true) {
let age = 58;
console.log(`${fname} ${lname} was ${age} years old.`);
age = 59;
console.log(`${fname} ${lname} is ${age} years old.`);
}
console.log(`${fname} ${lname} is ${age} years old.`); //ReferenceError: age is not defined
}
superHero();
console.log(`${fname} loves ${color}.`);
color = 'Green'; //TypeError: Assignment to constant variable.
console.log(`${fname} ${lname} `); //ReferenceError: lname is not defined
/*
Output:
Captain Marvel
Captain Marvel was 58 years old.
Captain Marvel is 58 years old.
Captain loves Red and Blue.
*/
*Explanation π*When the above snippet runs, the first two variables are declared using 'let' and 'const' respectively. The only difference is that once youβve assigned a value to a variable using const, you canβt reassign it to a new value.
Continuing further, we declare a function superHero() and call it, which has the variable 'lname' defined inside it making it block-scoped along with 'age' inside another block. Both these variables are only accessible inside their particular block and any attempt to call them outside the defined block will result in 'ReferenceError'.*
Top comments (0)