Variables in JavaScript, Scope and Hoisting

Image source : Unsplash
var x;            /Declare a variablex=10;             /Assign a value in itconsole.log(x);   /Use it

Scoping and Hoisting

Let’s first discuss about Scoping:

Scoping simply means that at what range a variable can be accessed.

Didn’t get it ?

var global = 'i am a global variable';
function doSomething() {
var local = 'i am a local variable';
console.log(local);
}
console.log(global);
console.log(local);
somethingReferenceError: local is not defined
at Object.<anonymous> (C:\Users\user\Desktop\demo\app.js:7:13)

What’s is the ReferenceError ?

function doSomething() {
if (1<2) {
var cow = 'cow';
let dog = 'dog';
const cat = 'cat';
console.log(cow); //cow
console.log(dog); //dog
console.log(cat); //cat
}
console.log(cow); //cow
console.log(dog); //ReferenceError: dog is not defined
console.log(cat); //ReferenceError: cat is not defined
}
doSomething();

Let’s first discuss about Hoisting:

The Heck ?

console.log(name);  //access name before it defined or initialized
var name='person'; //define and initialize after it been accessed
/* Output */
undefined
console.log(name);  //access name before it defined or initialized
name='person'; //initialize name without it defined
/* Output */
ReferenceError: name is not defined
//How we write it       |     //How JavaScirpt Manipulate it
console.log(name); | var name;
var name='person'; | console.log(name);
| name='person';
/* Output */
undefined
var statement = true;
function checkHoisting() {
//var statement; /* Javascript automatically declared it here */
if(1>2){
var statement = false;
}
console.log(statement);
}
checkHoisting();
//Output: undefined

But that simply not happen it case of let or const. Let’s see

let statement = true;
function checkHoisting() {
if(1>2){
let statement = false;
}
console.log(statement); //the global statement variable
}
checkHoisting();
//Output: true
var statement = true;
var statement = false;
console.log(statement); // Output:false
let done = true;
let done = false;
console.log(done); //Output:SyntaxError: Identifier 'done' has already been declared

Conclusion:

Making recipe with Programming :)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store