0

This is what object literal syntax looks like:

var x = {property:value};

Now, please correct me if I am wrong but what I'm looking at is the word "var" here, and that seems to imply "variable". Does this mean that fundamentally "objects" are variables (with the caveat that they behave similar to arrays)? I recently asked a question about whether variables were objects and everyone said no.

But it's strange that the keyword "var" is used when creating an object literal, and if they aren't variables (which I'm assuming for now) why would ecmascript incorporate this use if object literals are not in some way or another variables? It seems syntactically confusing.

1
  • An object is an object, which is a value. A variable is a location, and you're assigning the value to it. You can use object literals without variables as well - they're basic expressions, and can be used e.g. as a function argument. Commented Jun 10, 2014 at 22:24

2 Answers 2

2

The object { property: value } is not a variable, but x is, and that’s what the var refers to. var creates a variable, and optionally gives it a value; x is the variable, and { property: value } is the object you’re assigning to it. The object has nothing to do with a variable. Consider

var x = 5;

5 isn’t a variable.

var x = null;

null isn’t a variable.

console.log({ foo: 70 }.foo + " boxes");

No variables involved here, but there is an object literal, just like 70 is a numeric literal and " boxes" is a string literal.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, I think I get it now. (I pressed return too soon btw, and it send my message, I wasn't ready to respond yet)
@AllanSocks, if you created and array, the array wouldn't be the variable, it would be whatever you're assigning the array to. var x = ["test", "test2", "test3"]... The array would just be the variables value.
0

The variable here is x. You are declaring x and then assigning it to point to an object literal.

Remember that with hoisting, your code ends up being processed like this:

var x;
x = {property:value};

As you can see, it really doesn't matter what you set x to, or even if you don't set it at all. var x declares a variable in the current scope named x.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.