Intro to JS question – JavaScript – SitePoint - Freelance Bargain

Breaking



Wednesday 3 August 2022

Intro to JS question – JavaScript – SitePoint

from Novice to Ninja

If the variable references a non-primitive data type, such as an array, function or object, then using const will not make it immutable . This means the underlying data inside the object can change (known as mutating the object).

please clairfy :slight_smile:

When you declare an object as a ‘const’ you are reserving memory for that const.
The assigned object is in a different memory location and the const is a reference to the memory location od the object
The system knows that it is an object and when you change the object you are changing the object not the const.
When you change the object it can either overwrite the existing object or create a new object and deleting the existing object and changing the reference.
Think of const as a container for an object and you can change what goes into the container but not the container.
That is the simple aprox. answer.

Constants cannot be reassigned.

const obj = { c: 2 } const obj = { d: 3 }
// Uncaught SyntaxError: Identifier 'obj' has already been declared obj = { d: 3 }
// Uncaught TypeError: Assignment to constant variable.

The contents of reference types can be changed though. They are mutable.

Objects

// adding a property to the object
obj.d = 3
console.log(obj)
// { c: 2, d: 3 } // deleting a property from the object
delete (obj.c)
console.log(obj)
// { d: 3 }

The same for Arrays, another reference type.

Arrays

const arr = [1, 2, 3, 4] arr = [6, 7, 8]
// Uncaught TypeError: Assignment to constant variable. // add an item to the array
arr.push(5)
console.log(arr)
// [1, 2, 3, 4, 5] // remove the last item
arr.pop()
console.log(arr)
// [1, 2, 3, 4]

In short if a reference type is assigned to a const you can still change it’s contents. It is mutable.

As this relates to the Novice to Ninja course/book I have moved it to the appropriate category :slight_smile:



from Web Development – My Blog https://ift.tt/jUxy8Na
via IFTTT

No comments:

Post a Comment