4

I was playing around in Node and accidentally mistyped the curly brackets ({}) and put square brackets ([]) instead, and started using the variable as a simple object. No error has been thrown, and the behaviour seems to be the same, but when I checked the type with Object.getPrototypeOf() they were different.

> var cake = [];
> cake["is_a"] = "lie";

> cake
[ is_a: 'lie' ]

> Object.getPrototypeOf(cake.is_a)
[String: '']

> Object.getPrototypeOf(cake)
[]

> Object.getPrototypeOf({})
{}

Then I thought that this is a syntactic sugar on top of arrays, but no:

> cake[0]
undefined

It reminds me of Elixir's keyword lists or Erlang's property lists. What are they called? (So that I can google further.) Are these specific to Node?

toraritte
  • 6,300
  • 3
  • 46
  • 67
  • 2
    Arrays are objects. No, it's not a Node thing; it's basic JavaScript. – Pointy Aug 01 '18 at 23:54
  • 2
    Other than "primitive values", everything else in Javascript is an object ... and you can add properties like you do in your code to any object you like ... `var d = new Date; d.is_a='lie'` works just the same as `var d = new Object; d.is_a = 'lie'` – Jaromanda X Aug 01 '18 at 23:58
  • Wow, I'm an idiot... Thanks @Pointy and Jaromanda X; it has been a while and completely forgot the basics... Should just delete this question or leave it here for the education of others? – toraritte Aug 02 '18 at 00:00

1 Answers1

0

As Pointy and Jaromanda X pointed out in the question comments, in JavaScript everything is an object (including arrays), except for primitives:

The latest ECMAScript standard defines seven data types:

  • Six data types that are primitives:

    • Boolean
    • Null
    • Undefined
    • Number
    • String
    • Symbol (new in ECMAScript 2015)
  • and Object

(See also the relevant question Primitive value vs Reference value).

My question's code samples were deceiving (at least to me) as it looked like something has been stored in the array itself, but that was only the representation of the Node REPL (it is the same on Chrome's console for that matter) and the array is in fact empty:

> var cake = [];
> cake["is_a"] = "lie";

> cake
[is_a: "lie"]

> cake.length
0
toraritte
  • 6,300
  • 3
  • 46
  • 67