Search⌘ K
AI Features

What Are Var, Let, and Const Keywords in JavaScript?

Explore the fundamental differences between var let and const keywords in JavaScript. Understand their distinct scopes hoisting behavior reassignment permissions and redeclaration rules to write cleaner and more effective code. This lesson clarifies how these keywords impact variable accessibility and modification within various code blocks.

Introduction

To define any variable in JavaScript, there are three keywords: var, let, and const. These keywords can be a bit confusing—let’s get to know them by going over their differences. We’ll start with their scope.

Scope

The scope of a variable defines the accessibility of that variable in the program. In other words, it specifies the area in the program/code where a particular variable can be accessed.

var let const
Variables declared with var are in the function scope. Variables declared as let are in the block scope. Variables declared as const are also in the block scope.

Look at the below code snippets to see this:

var
let
const
{
// Define a var variable
var variable_1 = "Hello";
// Access and print the value of variable_1
console.log(variable_1);
}
// Access and print the value of variable_1
console.log(variable_1);
How scoping works for var variables

Explanation:

  • When executing ...