0

Can someone explain to me the behaviour of this little javascript code...

"use strict";
var toto = [];
toto["This should break"] = "But it does not";
console.log(JSON.stringify(toto));

I understand that variables in javascript can change type halfway through a script.

So, on line 2, I "declare" my variable toto as an empty array.

On line 3, I attempt to assign a property to an object called toto

But line 4 shows me that toto is still an empty array!?

Should not I have had an error on line 3?

PS: you may have guessed I am not a javascript expert...

Eric Mamet
  • 2,681
  • 2
  • 13
  • 43
  • Arrays are objects, but the non-numeric properties are not normally shown. – Barmar Dec 17 '20 at 17:19
  • Also, you can change a variable's type by assigning a new value of different type to it. You can't change its type by changing the value's properties. – Guy Incognito Dec 17 '20 at 17:22

0 Answers0