Advance JavaScript Course
About Lesson

In JavaScript, users can declare a variable using 3 keywords that are var, let, and const. In this article, we will see the differences between the var, let, and const keywords. We will discuss the scope and other required concepts about each keyword.

JavaScript var keyword: The var is the oldest keyword to declare a variable in JavaScript.

Scope: Global scoped or function scoped. The scope of the var keyword is the global or function scope. It means variables defined outside the function can be accessed globally, and variables defined inside a particular function can be accessed within the function.

JavaScript let keyword: The let keyword is an improved version of the var keyword.

Scope: block scoped: The scope of a let variable is only block scoped. It can’t be accessible outside the particular block ({block}).

const keyword in JavaScript: The const keyword has all the properties that are the same as the let keyword, except the user cannot update it.

Scope: block scoped: When users declare a const variable, they need to initialize it, otherwise, it returns an error. The user cannot update the const variable once it is declared.

Differences between var, let, and const:

var:

  • The scope of a var variable is functional scope.
  • It can be updated and re-declared into the scope.
  • It can be declared without initialization.
  • It can be accessed without initialization as its default value is “undefined”.
  • hoisting done, with initializing as ‘default’ value

let

  • The scope of a let variable is block scope.
  • It can be updated but cannot be re-declared into the scope.
  • It can be declared without initialization.
  • It cannot be accessed without initialization otherwise it will give ‘referenceError’.
  • Hoisting is done, but not initialized (this is the reason for the error when we access the let variable before declaration/initialization

const

  • The scope of a const variable is block scope.
  • It cannot be updated or re-declared into the scope.
  • It cannot be declared without initialization.
  • It cannot be accessed without initialization, as it cannot be declared without initialization.
  • Hoisting is done, but not initialized (this is the reason for the error when we access the const variable before declaration/initialization

Note: Sometimes, users face problems while working with the var variable as they change its value of it in a particular block. So, users should use the let and const keywords to declare a variable in JavaScript.

Exercise Files
No Attachment Found
No Attachment Found
Join the conversation

Introducing Official ApeStaking Protocol for ApeCoin.

New Blur NFT Marketplace Courting Professional.