loading...

ES6 Part 2 const

scdan0624 profile image SCDan0624 ・1 min read

Intro
let is not the only new way to declare variables in ES6. We are also introduced to another keyword called const.

How is const different from let
const has all the same features as let with one additional key difference, variables declared with const are a constant value and cannot be reassigned:

const myDog = "Penny"
myDog = "Butch" // will return an error
Enter fullscreen mode Exit fullscreen mode

When to use const
You should always name variables you don't want to reassign using const. This will prevent you from accidentally reassigning a variable when coding using larger code bases.

You can mutate an array or object using const
While variables cannot be reassigned using const you can still mutate objects (including arrays and functions):

const myTeam = ["Shaq","Fisher","Kobe"]

myTeam = ["Duncan","Parker","Manu"] // will throw an error

myTeam[1] = "Horry"

console.log(myTeam) // [ 'Shaq', 'Horry', 'Kobe' ]

console.log(myTeam)
Enter fullscreen mode Exit fullscreen mode

As you can see you cannot reassign the array using the const keyword but you can mutate the original const array.

Prevent object mutation

If you still need to prevent an object from being mutated ES6 provides Object.freeze

let obj = {
  name:"Pippen",
  defense:10
};
Object.freeze(obj);
obj.defense = "9"; // will be ignored. Mutation not allowed
obj.shooting = 7; // will be ignored. Mutation not allowed
console.log(obj); // let obj = {name:"Pippen",defense:10}


Enter fullscreen mode Exit fullscreen mode

Discussion

pic
Editor guide