const

const

  • Stands for constant

  • The values of these variables can not be changed through reassignment (i.e. have it’s value changed using =)

  • This help make your code easier to debug and protects certain values from accidentally being overridden in your codebase


Declaring a variable using const

const are the same as let but with one key difference, values can only be assigned once to a const variable

// declare a constant named 'school'

const school = "General Assembly"

An error will occur if you try to update the value of a const

// correctly declare a constant using "const" keyword
const greeting = "Hello"


// const values cannot be updated, if you attempt to do so
// an error will occur

greeting = "Good Morning" // this will throw an error

inline


Variables declared with const can still be mutated

When dealing with arrays and objects you will find that you are still able to mutate their respective values because updating their values does not require reassignment

Here’s an example of working with arrays declared with const:

// declare an array using const
const myNumbers = [1, 2, 3]

/*
add a new number to the array
and no error will occur, because we did not
"reassign" new values directly to the
myNumbers variables using `=`
*/
myNnumbers.push(4)

console.log(myNumbers) // [1, 2, 3, 4]

/*
However, uncomment the line below and observe
the error when we attempt to "reassign" myNumbers
*/
// myNumbers = [4, 5] // an error will occur

JS Bin on jsbin.com

Objects declared with const can have their properties changes without any issues:

// declare an object using const
const myObject = {a: 1, b: 2, c: 3}

/*
add update an existing property
and add a new property to myObject
and no error will occur, because
we did not "reassign" new values
directly to the myObject variable using `=`
*/
myObject.c = 30
myObject.d = 4

console.log(myObject) // { a: 1, b: 2, c: 30, d: 4}

/*
However, uncomment the line below and observe
the error when we attempt to "reassign" values
directly to myObject
*/
// myObject = {e: 5, g: 6} // an error will occur

JS Bin on jsbin.com