...

/

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

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

Learn how to define variables, as well as the differences between the var, let, and const keywords used to declare variables.

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:

{
// 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 the code in the var tab, we will see that the variable_1 is accessible inside and outside of the block. ...