How to Declare Variables in JavaScript: Syntax and Examples
In JavaScript, you declare variables using
let, const, or var keywords followed by the variable name. let and const are modern ways to declare variables, where const creates a constant value and let allows reassignment.Syntax
JavaScript variables can be declared using three keywords:
- let: Declares a block-scoped variable that can be reassigned.
- const: Declares a block-scoped constant that cannot be reassigned.
- var: Declares a function-scoped variable (older style, less recommended).
The general syntax is: keyword variableName = value; where keyword is one of let, const, or var.
javascript
let name = 'Alice'; const age = 30; var city = 'New York';
Example
This example shows how to declare variables with let, const, and var, and how their values can be used or changed.
javascript
let score = 10; score = 15; // Reassigned const maxScore = 20; // maxScore = 25; // This would cause an error var level = 1; level = 2; console.log('Score:', score); console.log('Max Score:', maxScore); console.log('Level:', level);
Output
Score: 15
Max Score: 20
Level: 2
Common Pitfalls
Common mistakes when declaring variables include:
- Using
constbut trying to reassign the variable, which causes an error. - Using
varcan lead to unexpected behavior due to its function scope and hoisting. - Forgetting to declare a variable (missing keyword) creates a global variable unintentionally.
javascript
/* Wrong: Reassigning const */ const pi = 3.14; // pi = 3.1415; // Error: Assignment to constant variable /* Wrong: Missing declaration keyword */ function test() { x = 5; // Creates global variable unintentionally } test(); console.log(x); // 5 /* Right: Use let or const */ let x = 5; x = 10; // Allowed console.log(x); // 10
Output
5
10
Quick Reference
| Keyword | Scope | Reassignable | Use Case |
|---|---|---|---|
| let | Block | Yes | General variable declaration |
| const | Block | No | Constants that do not change |
| var | Function | Yes | Legacy code, avoid in new code |
Key Takeaways
Use
let for variables that will change and const for constants.Avoid
var because it has confusing scope and hoisting behavior.Always declare variables with
let, const, or var to avoid creating global variables.const variables cannot be reassigned after declaration.Block scope means variables declared with
let or const exist only inside the nearest curly braces.