Last active
March 2, 2021 10:28
-
-
Save junaidtk/861c6df4919cbf525c520e796f26e7c6 to your computer and use it in GitHub Desktop.
Javascript variable and its declaration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
These are three type of javascript variabe declaration. | |
var | |
==== | |
Function scoped or globally Scoped. | |
Reassignable and Redeclarable | |
Not subject to temporal dead zone. | |
var language = "JavaScript"; | |
function foo() { | |
var language = "Python"; | |
framework = "React"; | |
console.log(language); | |
} | |
foo(); // "Python" | |
console.log(language); // "JavaScript" | |
console.log(window.language); // "JavaScript" | |
console.log(window.framework); // "React" | |
let | |
==== | |
Block scoped. | |
Re-assignable, not re-declarable. | |
Subjected to temporal dead zone. | |
let language = "JavaScript"; | |
{ | |
let language = "React"; // Block scope | |
console.log(language); // "React" | |
} | |
function foo() { | |
let language = "Python"; | |
console.log(language); | |
} | |
foo(); // "Python" | |
console.log(language); // "JavaScript" | |
console.log(window.language); // undefined | |
Const | |
==== | |
Block scoped. | |
Not re-assignable, not re-declarable. | |
Subjected to temporal dead zone. | |
const language = "JavaScript"; | |
{ | |
const language = "React"; // Block scope | |
console.log(language); // "React" | |
} | |
function foo() { | |
const language = "Python"; | |
console.log(language); | |
} | |
foo(); // "Python" | |
console.log(language); // "JavaScript" | |
console.log(window.language); // undefined | |
All javascript variable are hoisted (Means all the variable declarations are moved to top of the scope). | |
The var variable will intialise with a vlaue of undefined. But let and const type will throw ReferenceError. | |
eg: for let | |
console.log(language); // TDZ | |
let language = "JavaScript"; // No hoisting | |
// ReferenceError: language is not defined | |
Block scope is within curly brackets. |
More understanding on const type.
const myArray = [];
myArray.push(1); // Works fine.
myArray[1] = 2; // Also works fine.
console.log(myArray); // [1, 2]
myArray = [1, 2, 3] // This will throw.
const foo; // ERROR: const declarations must be initialized
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
const something = {};
something = 10; // Error.
let somethingElse = {};
somethingElse = 1000; // This is fine.