How to declare variables in JavaScript?

Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.

Before you use a variable in a JavaScript program, you must declare it. JavaScript provides three ways to declare variables: var, let, and const.

Using var Keyword

Variables are declared with the var keyword as follows:

<script>
   var money;
   var name;
</script>

You can also declare multiple variables with the same var keyword:

<script>
   var money, name;
</script>

Using let Keyword (ES6)

The let keyword provides block-level scoping and is the modern way to declare variables:

<script>
   let age = 25;
   let city = "New York";
   
   console.log(age);  // 25
   console.log(city); // New York
</script>

Using const Keyword (ES6)

The const keyword declares constants that cannot be reassigned after initialization:

<script>
   const PI = 3.14159;
   const COMPANY_NAME = "TutorialsPoint";
   
   console.log(PI);           // 3.14159
   console.log(COMPANY_NAME); // TutorialsPoint
</script>

Variable Initialization

Storing a value in a variable is called variable initialization. You can do variable initialization at the time of variable creation or at a later point in time when you need that variable.

<script>
   // Declaration and initialization together
   var score = 100;
   let playerName = "John";
   const MAX_LIVES = 3;
   
   // Declaration first, initialization later
   var level;
   level = 1;
   
   console.log(score);      // 100
   console.log(playerName); // John
   console.log(MAX_LIVES);  // 3
   console.log(level);      // 1
</script>

Comparison

Keyword Scope Reassignable Hoisted
var Function Yes Yes
let Block Yes No
const Block No No

Conclusion

Use let for variables that may change and const for constants. Avoid var in modern JavaScript due to its function-scoped behavior and potential hoisting issues.

Updated on: 2026-03-15T21:22:55+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements