let, const and var
This lesson explains let, const and var in JavaScript with beginner-friendly examples, practical use cases, and clear best practices.
JavaScript let vs const vs var Overview
JavaScript provides three keywords for declaring variables:
let, const, and var. Although all
three are used to store data, they differ in scope, reassignment behavior,
hoisting, and best practices.
Modern JavaScript recommends using const by default,
let when values need to change, and avoiding
var except when maintaining legacy applications.
| Feature | const | let | var |
| Scope | Block | Block | Function |
| Can Reassign | No | Yes | Yes |
| Can Redeclare | No | No | Yes |
| Hoisted | Yes | Yes | Yes |
| Recommended | Yes | Yes | No |
JavaScript let, const and var Example
// const
const website = "PHPKingdom";
// let
let visitors = 1000;
visitors = 1200;
// var
var category = "JavaScript";
category = "Programming";
console.log(website);
console.log(visitors);
console.log(category);
Use const when the value should remain unchanged,
let when reassignment is expected, and avoid
var in new JavaScript projects.
When to Use let, const and var
| Keyword | Recommended Usage |
| const | Configuration values, constants, object references, arrays, imported modules, and values that should not be reassigned. |
| let | Loop counters, user input, calculations, counters, and variables whose values change. |
| var | Legacy applications written before ES6. Avoid using it in modern JavaScript. |
Best Practices
- Use
const by default for all variable declarations. - Switch to
let only when reassignment is necessary. - Avoid using
var in new projects. - Keep variable scope as small as possible.
- Use descriptive variable names that clearly explain their purpose.
- Declare variables close to where they are first used.
- Avoid creating unnecessary global variables.
- Follow consistent naming conventions such as camelCase.
Common Mistakes
- Using
var instead of let or const. - Trying to reassign a variable declared with
const. - Confusing block scope with function scope.
- Creating accidental global variables.
- Redeclaring variables unnecessarily.
- Using short or meaningless variable names.
- Assuming
const makes objects immutable.
Key Takeaways
const is the preferred choice for most variables. let should be used when values need to change. var is function-scoped and mainly used in legacy code. - Both
let and const are block-scoped. - Using modern variable declarations reduces bugs and improves code readability.
- Understanding variable scope is essential for writing reliable JavaScript.
Pro Tip
A simple rule followed by professional JavaScript developers is:
use const first, change it to let only if the
value must be reassigned, and avoid var unless maintaining
older JavaScript codebases.