Variables vs. Let vs. Const
var
var x = "Joanne Tang";
var x = 21;
- can be used before it is declared
carName = "Benz";
var carName;
{
var x = 2;
}
// x CAN be used here
let
var x = "Joanne Tang";
var x = 21;
// SyntaxError: 'x' has already been declared
- must be declared before use
- can be reassigned
- have block scope
{
let x = 2;
}
// x can NOT be used here
const
- cannot be redeclared
- must be assigned a value when they are declared
// Incorrect
const PI;
PI = 3.141592653589793;
const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error
- can change the elements of constant array
// You can create a constant array:
const cars = ["Benz", "Volvo", "BMW"];
// You can change an element:
cars[0] = "LEXUS";
// You can add an element:
cars.push("Audi");
const cars = ["Benz", "Volvo", "BMW"];
cars = ["LEXUS", "Volvo", "Audi"]; // ERROR
- can change the properties of constant object
// You can create a const object:
const person = {name:"Joanne Tang", age:"21", email:"joannetang@gmail.com"};
// You can change a property:
person.email = "joannetang@yahoo.com";
// You can add a property:
person.gender = "female";
const person = {name:"Joanne Tang", age:"21", email:"joannetang@gmail.com"};
person = {name:"Ben Wu", age:"25", email:"benwu@gmail.com"}; // ERROR
const x = 10;
// Here x is 10
{
const x = 2;
// Here x is 2
}
// Here x is 10
Comparision Operators
Operator |
Description |
== |
equal value |
=== |
equal value and type |
!= |
not equal value |
!== |
not equal value or type |
Reference