Pratik
Pratik

Reputation: 978

Why Curly Brackets behave differently in JavaScript?

As far as I know, Javascript follows ECMA specification and according to that,

var x=[2,3,4] // represents array

and

var y= {"a":1,"b":2,"c":3} // represents object with key/value pair

But I am confused because of below 2 examples:

Example 1:

{"a","b","c"} // Is valid with return type --> "c"

whereas

Example 2:

var x={"a","b","c"} // Is Invalid

Can someone please explain reason of outcomes for last 2 examples ?

Upvotes: 1

Views: 72

Answers (2)

Dblaze47
Dblaze47

Reputation: 868

When using {} only without assigning in a variable is just evaluating expressions, as others have stated in the comments above. That is why it will log the last expression evaluated. In the second case, it is an incorrect object initialization. The possiblle scenarios are:

var x = {"a","b","c"}; //Invalid as object properties incorrectly defined.
var y = ["a","b","c"]; // Correct if you want an array with these elements.
var z = {
   a: "some value",
   b: "some value",
   c: "some value"
};  // Also correct if you want a,b,c as properties of an object.

Upvotes: 0

Barmar
Barmar

Reputation: 780843

Curly braces are used for two things in JavaScript.

  1. Delimiters around object literals, as in var y= {"a":1,"b":2,"c":3}
  2. Delimiters around statement blocks, as in if (y) { x = 1; z = 2; }

If the { is at the beginning of a statement, then it's treated as the second type, so it's parsed as a statement block. That's what your Example 2 is. The statement is the expression "a","b","c". This statement uses the comma operator, so its value is the last expression, which is "c". In a function you'd need to use return to return that value, but when you type a statement in the JavaScript console, it's automatically evaluated and the value is printed.

Example 2 is type 1, but the syntax of the object contents is invalid, so you get an error.

Upvotes: 2

Related Questions