JavaScriptBasics
JavaScript Variables (var, let, const)
Learn JavaScript variables, how to declare them using var, let, and const, understand scope, redeclaration rules, and best practices used in real-world development.
What are Variables in JavaScript?Link to this section
Variables are used to store data values in JavaScript. These values can be numbers, text, objects, or any other type of data that a program needs to work with.
A variable allows you to save a value in memory and reuse or modify it throughout your program.
Declaring Variables in JavaScriptLink to this section
JavaScript provides three ways to declare variables:
- var
- let
- const
Using var :Link to this section
The var keyword was the original way to declare variables in JavaScript.
Characteristics of var
- Function-scoped - Can be redeclared - Can be updated - Hoisted to the top of its scopewarning
Using var can lead to unexpected bugs due to its loose scoping behavior. It is not recommended in modern JavaScript development.
Using let :Link to this section
The let keyword was introduced in ES6 to solve problems associated with var.
Characteristics of let
- Block-scoped - Cannot be redeclared in the same scope - Can be updated - Safer and more predictable than vartip
Use let when you know the variable value will change later.
Using const :Link to this section
The const keyword is used to declare variables whose values should not be reassigned.
Characteristics of const
- Block-scoped - Cannot be redeclared - Cannot be reassigned - Must be initialized at declarationnote
<b>const</b> does not make objects immutable. It only prevents reassignment of the variable reference.
Difference Between var, let, and const :Link to this section
Scope
- var → Function scope - let → Block scope - const → Block scopeReassignment
- var → Allowed - let → Allowed - const → Not allowedRedeclaration
- var → Allowed - let → Not allowed - const → Not allowedVariable Naming RulesLink to this section
JavaScript variable names:
- Must start with a letter, underscore (_), or dollar sign ($)
- Cannot start with a number
- Cannot use JavaScript keywords
- Are case-sensitive
Best Practices for VariablesLink to this section
tip
Clean variable naming improves code readability and maintainability in large projects.
Check Your Understanding
Question 1 of 5Which keyword is block-scoped?
Variable Declaration
Declare a variable to store your name using const and another variable to store your age using let....
Fix the Error
Find and fix the issue in the following code:...
const score;
score = 100;
Scope Understanding
Write a small program where a variable declared using letis only accessible inside an if block....
Naming Practice
Create three variables with meaningful names to store:...
- User email
- Total price
- Login status