Arun Ravilla
Arun Ravilla

Reputation: 93

If key is not defined then variable name is taken as key in javascript object

Let's consider the following example

a = [1,2]
c = {a, b: "Hello"}

Output in chrome dev tool

{
  "a": [
    1,
    2
  ],
  "b": "Hello"
}

How this is happening is it safe to create a object like this?

Upvotes: 1

Views: 236

Answers (1)

Barmar
Barmar

Reputation: 780744

In an object literal, there are two ways to enter elements.

The traditional way is key: value. In this case, key is not evaluated, it's taken as a literal, while value is evaluated. So in your b: "Hello" element, it doesn't matter whether b is defined, it always creates the key "b".

EcmaScript 6 added a shorthand notation, where you just put one variable, like your a element. This is short for a: a, so it uses the name of the variable as the key, and then uses its value as the value. In this case, the variable does need to be defined.

There are some other shorthands for creating properties with functions, see Enhanced Object Literals.

As for whether it's safe, see the compatibility table in MDN (which also goes into more detail about each of these shorthand notations).

Upvotes: 2

Related Questions