Var, Let, and Const in JavaScript.

JavaScript Variables Explained: var, let, and const (Beginner Guide)

Introduction

Variables are one of the most important concepts in JavaScript. A variable is used to store data that can be used later in your program.

In JavaScript, there are three ways to declare variables:

  • var

  • let

  • const

Understanding the differences between these three is important for writing clean and modern JavaScript code.

What is a Variable?

A variable is a container used to store data.

Example:

Here:

  • let → keyword used to declare a variable

  • name → variable name

  • "John" → stored value

You can later use the variable in your program.

Output:

1. var in JavaScript

var is the old way to declare variables in JavaScript.

Example:

Output:

Characteristics of var

  • Function scoped

  • Can be redeclared

  • Can be updated

Example:

Output:

Because of these behaviors, var can sometimes cause unexpected bugs.

2. let in JavaScript

let was introduced in ES6 (2015) and is now widely used.

Example:

Output:

Characteristics of let

  • Block scoped

  • Can be updated

  • Cannot be redeclared in the same block

Example:

This makes let safer than var.

3. const in JavaScript

const is used to declare constant variables.

Example:

Output:

Characteristics of const

  • Block scoped

  • Cannot be updated

  • Cannot be redeclared

Example:

Block Scope Example

Block scope means the variable only exists inside the block {}.

Example:

The variable cannot be accessed outside the block.

Comparison Table

When to Use var, let, and const

Use const

When the value should not change.

Use let

When the value may change later.

Avoid var

In modern JavaScript, developers usually avoid using var.

Example Program

Output:

Common Beginner Mistake

Trying to change a const variable.

Always remember:

const variables cannot be reassigned.

Summary

In this tutorial, you learned:

  • What variables are in JavaScript

  • How to use var, let, and const

  • Differences between them

  • When to use each one

Key takeaway:

  • Use const by default

  • Use let when values change

  • Avoid var

What’s Next?

In the next tutorial, you will learn:

JavaScript Data Types Explained with Examples.

Leave a Reply