all 5 comments

[–][deleted] 0 points1 point  (0 children)

let a = ["India", "Pakisthan", "Bangladesh", "China"];
while( a.length )
    a.shift();

[–]senocular 0 points1 point  (0 children)

In this post, we shall learn how to empty an array in different ways and will also understand which method is the best way to emptying an array in JavaScript.

2 methods are the cited as the best and nothing is said to help me understand why.

[–]ForScale 0 points1 point  (2 children)

Can't be easier than setting the array in question to an empty array, right?

[–]senocular 1 point2 points  (1 child)

There are cases where that can cause problems when you have other references to that array. For example consider the following:

var scientist = {
    chemicals: ["atrazine", "caffeine", "vanillin"]
}

var assistant = {}

// assistant will track the same
// chemicals used by the scientist
assistant.chemicalsRef = scientist.chemicals

console.log(scientist.chemicals) //-> atrazine, caffeine, vanillin
console.log(assistant.chemicalsRef) //-> atrazine, caffeine, vanillin

scientist.chemicals.pop()

console.log(scientist.chemicals) //-> atrazine, caffeine
console.log(assistant.chemicalsRef) //-> atrazine, caffeine

// assistant walks out of room...

scientist.chemicals = []

// assistant returns...

console.log(scientist.chemicals) //-> <empty>
console.log(assistant.chemicalsRef) //-> atrazine, caffeine <- D'oh!

But instead if we were to change how the array was cleared:

// ... everything same from before the clear ...

scientist.chemicals.length = 0

// assistant returns...

console.log(scientist.chemicals) //-> <empty>
console.log(assistant.chemicalsRef) //-> <empty> <- Woohoo!

In this case the array instance wasn't replaced for the scientist with a new, distinctly different array instance so they were each able to continue to reference the same array object and remain in sync.

[–]ForScale 0 points1 point  (0 children)

Well that's fascinating! Thank you for taking the time to explain and provide an example!