var, let & const in Javascript

Mariya Baig
2 min readMar 4, 2024

--

var

  • var can either be functional scoped or global scope but not block scoped. It means that if it is declared in a function, it won’t be accessible outside of it but if it’s written in a block of if-else, it can be accessed anywhere within the code.
  • var variables are hoisted to the top of the scope during the compilation phase, meaning that var can be used before being declared in the code.
function example() { if (true) { var x = 10 } console.log(x) // Outputs 10 (no block-scoping) }
console.log(x) // Outputs: undefined var x = 5 console.log(x) // Outputs: 5

even though console.log(x) appears before the declaration var x = 5 it doesn’t result in an error. During the compilation phase, the declaration var x is hoisted to the top, making the variable x accessible throughout its scope. However, only the declaration is hoisted, not the initialization, so the first console.log(x) outputs undefined. The second console.log(x) outputs 5 after the variable has been assigned the value 5.

  • var can be declared and reassigned.
  • use var if you want function-scoped variables that can be hoisted.

let

  • let has block-scope and can only be accessed inside that block ( i.e curly braces{})
  • let variables are hoisted to the top but are not initialised until an actual declaration is done. this is called the temporal dead zone.
function example() { if (true) { let blockScopedVar = "I am block-scoped" console.log(blockScopedVar) // Outputs: I am block-scoped } // Attempting to access blockScopedVar here would result in an error. // console.log(blockScopedVar) // Error: blockScopedVar is not defined } example()
console.log(variableBeforeDeclaration) // Error: Cannot access 'variableBeforeDeclaration' before initialization let variableBeforeDeclaration = 42 console.log(variableBeforeDeclaration) // Outputs: 42
  • let variables can be reassigned but we can not redeclare them within the same scope.
  • use let if you want block-scoped variables that can be reassigned.

const

  • const also has block scope meaning that isn’t accessible outside the block( i.e curly braces { })
  • const variables must be initialised during the declaration
  • const variables can neither be redeclared nor reassigned and hence are known as immutable
  • use const if you want block-scoped variables that are constant and cannot be reassigned.

Originally published at https://mariyabaig.com.

--

--

No responses yet