buley
buley

Reputation: 29208

What do people mean when they say "object literal" in JavaScript?

I know that most everything is an object in JavaScript. When people say "object literal," do they mean an object like this?

var thing = {
   'foo': 'bar'
   , 'baz': 'foo'
   , 'bar': 'baz'
};

Upvotes: 7

Views: 4841

Answers (6)

romainl
romainl

Reputation: 196556

An object literal is a way to declare an object.

You would write

var myObject = {}; // with or without members

instead of

var myOject = new Object();

You can also use array literals:

var myArray = [];

instead of

var myArray = new Array(); // with or without members

It's shorter, of course but it also bypasses the constructor so it's supposed to be more efficient.

Upvotes: 10

Ryan
Ryan

Reputation: 1557

It's supposed to represent a notational delineation. When they say 'object literal', they mean 'object literal notation'. There are various ways to make an object. This is the most straightforward approach.

Upvotes: 2

ruakh
ruakh

Reputation: 183301

Yes, more or less. The "literal" is the source-code representation of the object; so, just the part from { to }, not the rest of the declaration.

A good reference: https://developer.mozilla.org/en/JavaScript/Guide/Values,_Variables,_and_Literals#Object_Literals.

Upvotes: 1

Smamatti
Smamatti

Reputation: 3931

Yes.

In the object literal notation, an object description is a set of comma-separated name/value pairs inside curly braces. The names can be identifiers or strings followed by a colon.

Upvotes: 1

Mob
Mob

Reputation: 11098

Yes. Read more. http://www.dyn-web.com/tutorials/obj_lit.php

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038820

Yes, that's exactly what object literal means. A definition of a javascript object which may contain comma separated definition of properties, functions, ...

Object literals are formed using the following syntax rules:

  • A colon separates property name from value.
  • A comma separates each name/value pair from the next.
  • There should be no comma after the last name/value pair. Firefox won't object if you add it, but Internet Explorer will trigger an error: 'Expected identifier, string or number'.

Upvotes: 9

Related Questions