Skip to content

Instantly share code, notes, and snippets.

@junaidtk
Last active March 2, 2021 10:28
Show Gist options
  • Save junaidtk/861c6df4919cbf525c520e796f26e7c6 to your computer and use it in GitHub Desktop.
Save junaidtk/861c6df4919cbf525c520e796f26e7c6 to your computer and use it in GitHub Desktop.
Javascript variable and its declaration
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.
@junaidtk
Copy link
Author

junaidtk commented Mar 2, 2021

const something = {};
something = 10; // Error.

let somethingElse = {};
somethingElse = 1000; // This is fine.

@junaidtk
Copy link
Author

junaidtk commented Mar 2, 2021

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.

@junaidtk
Copy link
Author

junaidtk commented Mar 2, 2021

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