React ES6 Variables

Before ES6, there was only one way of defining your variables: with the var keyword. If you did not define them, they would be assigned to the global object. Unless you were in strict mode, then you would get an error if your variables were undefined.

Now, with ES6, there are three ways of defining your variables: var, let, and const.



Using var

var score = 100;
  • Global Scope: If you use var outside of a function, it belongs to the global scope.
  • Function Scope: If you use var inside of a function, it belongs to that function.
  • Block Scope: If you use var inside of a block, i.e., a for loop, the variable is still available outside of that block.
  • Scope Limitation: var has a function scope, not a block scope.

Example

var age = 25;

if (true) {
    var name = "John";
}
console.log(name); // Outputs: John




Using let

let score = 100;
  • Block Scope: let is the block-scoped version of var, and is limited to the block (or expression) where it is defined.
  • Limited Scope: If you use let inside of a block, i.e., a for loop, the variable is only available inside of that loop.
  • Block Scope Limitation: let has a block scope.

Example

let age = 25;

if (true) {
    let name = "Alice";
    console.log(name); // Outputs: Alice
}
console.log(name); // Error: name is not defined




Using const

const score = 100;
  • Block Scope: const is a variable that, once it has been created, its value can never change.
  • Constant Reference: const has a block scope, and means you cannot reassign the variable. However, the contents of a constant array or object can still be changed.

Important Notes:

  • Allowed: You can change the elements of a constant array or the properties of a constant object.
  • Prohibited: Reassigning a constant value, array, or object is not allowed.

Example

const birthYear = 1990;
const colors = ["red", "blue"];
const person = {name: "Bob", age: 30};

colors.push("green"); // Allowed
person.age = 31; // Allowed

birthYear = 2000; // Error: Assignment to constant variable.
colors = ["yellow", "purple"]; // Error: Assignment to constant variable.
person = {name: "Eve", age: 25}; // Error: Assignment to constant variable.




Summary

  • var: Function-scoped, not block-scoped.
  • let: Block-scoped, limited to the block where it is defined.
  • const: Block-scoped with immutable reference.

Using let and const helps ensure better control over variable scope and reduces the risk of errors associated with var.

Scroll to Top