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.

Tutorials dojo strip

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

Using var

JavaScript
  • 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

JavaScript

Using let

JavaScript
  • 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

JavaScript

Using const

JavaScript
  • 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

JavaScript

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.

Tutorials dojo strip