DevAcademy
LearnJavaScriptJavaScript Variables
BeginnerJavaScript

JavaScript Variables

Learn how variables work in JavaScript, understand var, let, and const, and know when to use each with practical examples.

Reading Time

12 min

Lesson

Lesson 4 of 48

What is a Variable?

A variable is a named container used to store data. Instead of writing the same value multiple times, you store it inside a variable and reuse it whenever required.

Declaring Variables

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

var, let and const

Modern JavaScript recommends using let and const. Avoid using var in new projects because it behaves differently due to function scope and hoisting.

Comparison

Featurevarletconst
ScopeFunctionBlockBlock
RedeclareYesNoNo
ReassignYesYesNo
HoistedYesYesYes

Example of let

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

Example of const

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

Best Practice

Use const by default. Only use let when the value needs to change. Avoid var in modern JavaScript development.

Common Mistake

Many beginners think const makes objects immutable. It only prevents reassignment of the variable reference. Object properties can still be modified.

Remember

Variable names are case-sensitive. userName and username are considered different variables.

Interview Questions

Quick Quiz

1. Which keyword should be preferred by default?

2. Which keyword is block scoped?