1. Use the
var Keyword (ES5 and Earlier):
var name = "John";
2. Use the
let Keyword (ES6/ES2015 and Later):
- Part of the ECMAScript 6 standard (also known as ES6 and ES2015).
- Allows you to declare block-scoped variables.
let age = 25;
3. Use the
const Keyword (ES6/ES2015 and Later):
- For declaring variables whose values shouldn’t change (constants).
- Block-scoped like
const PI = 3.14159;
4. Initialize Without a Keyword (Not Recommended):
- It’s possible but not advisable due to potential issues and unintended global scope.
mistake = "This is not recommended";
Can I re-declare a variable using
let in the same scope?
No. If you’ve already declared a variable using
let in a specific scope, re-declaring it in the same scope will result in an error.
What’s the main difference between
The main difference is scope. Variables declared with
var are function-scoped, whereas variables declared with
let are block-scoped. This means
let variables have a narrower scope, making them preferable in many coding situations for better readability and avoiding potential variable reassignment bugs.
When should I use
const when you have a variable whose value you don’t want to change or reassign throughout the code. It ensures immutability for the binding, but remember, if you assign an object to a
const variable, the object’s properties can still be changed.