Suggest an editImprove this articleRefine the answer for “Ways to declare a variable”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**Variables in JavaScript** can be declared in three ways: `var`, `let`, and `const`. They differ in scope, whether they can be redeclared, and hoisting behavior. **Key point:** Use `const` by default, and `let` only if the variable actually needs to change; using `var` in modern code is not recommended.Shown above the full answer for quick recall.Answer (EN)ImageJavaScript has **three ways to declare a variable**: `var`, `let`, and `const`. They differ in **scope**, **whether they can be redeclared**, and **hoisting behavior**. Let's go through them in detail. --- ## **1.** `var` **- the old way (ES5 and earlier)** ```javascript var name = 'Tim'; ``` ### Features: - It can be **redeclared** and **reassigned**: ```javascript var x = 10; var x = 20; // does not cause an error ``` - **Function scope** (ignores `{}` blocks) ```javascript if (true) { var a = 5; } console.log(a); // 5 - the variable "escaped" outside the block ``` - **Hoists** - the variable is accessible before its declaration, but its value is `undefined`: ```javascript console.log(user); // undefined var user = 'Alex'; ``` > Using `var` in modern code **is not recommended**. --- ## **2.** `let` **- the modern way for mutable variables** ```javascript let age = 25; age = 26; // can be changed ``` ### Features: - The value **can be changed**, but it cannot be redeclared in the same block: ```javascript let a = 1; // let a = 2; Error ``` - **Block scope**: ```javascript if (true) { let x = 10; } console.log(x); // ReferenceError - the variable is not visible outside the block ``` - Not accessible before its declaration (unlike `var`): ```javascript console.log(a); // ReferenceError let a = 5; ``` > Use `let` when the variable's value will **change**. --- ## **3.** `const` **- a constant (immutable reference)** ```javascript const PI = 3.14; ``` ### Features: - It cannot be **reassigned** or **redeclared**: ```javascript const x = 10; x = 20; // TypeError ``` - But if it is an **object or array**, its internal data can be changed: ```javascript const user = { name: 'Tim' }; user.name = 'Alex'; // allowed // user = {} cannot reassign the reference itself ``` - **Block scope** - same as `let`. > Use `const` **by default**, and `let` only if the variable actually needs to change. --- ## Quick comparison: | Feature | `var` | `let` | `const` | |---|---|---|---| | Scope | Function | Block | Block | | Can be redeclared | Yes | No | No | | Can be reassigned | Yes | Yes | No | | Hoisting | Yes, with value `undefined` | Yes, but cannot be used before declaration | Yes, but cannot be used before declaration | | Modern standard | No, deprecated | Yes | Yes |For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.