Jake said:
I was just reading this article on Ajaxian:
http://ajaxian.com/archives/show-love-to-the-object-literal
This is a newbie question, but what is the object literal? I thought it
was like an array notation, but is it really its own thing? You can
declare arrays this way, can't you? An object in Javascript is like a
hash array that stores pointers to properties and methods?
Or is object literal notation a convenience form, wholly arbitrary,
unrelated to anything else in the language, existing for the ease of
the programmer?
I guess when you ask such a question you are going to get lots of
different opinions in reply, so here's mine. Thomas has given you most
of it, I think there are two may issues: attempting to 'type' variables
is pointless, and literals are convenient.
Attempting to 'type' a variable by initialising it with a dummy value
generally doesn't make sense[1] because JavaScript variables don't have
a type, it is their value that has a type, e.g.
var x = new Object();
Leads to the idea that 'x is an Object', but strictly x is a reference
to an Object (in this case, an empty object). The above statement does
not 'type' x as an Object; it doesn't force the value referenced by x to
always be an object.
e.g.
var x = new Object();
x = 5;
The value of x is changed from an object to a number.
A literal is a convenient way to initialise the value of a variable and
can be used with any type, Thomas' examples cover that.
Some confusion might arise from:
var x = 'hello';
not being the same as:
var y = new String('Hello');
'x' is a string primitive, whereas 'y' is a string object. But 'x' will
be converted to a string object if required and possible[2], e.g. I can
still do:
alert( x.length ); // Shows 5
alert( x.split('') ); // Shows h,e,l,l,o
The value of x is still a primitive, it is converted only for the sake
of evaluating the expression.
Extensive use of literals leads to JavaScript Object Notation (JSON):
<URL:
http://www.json.org/>
1. Typing of variables has been proposed as part of Netscape's
JavaScript 2.0 and the Netscape proposal for ECMAScript Ed 4.
<URL:
http://www.mozilla.org/js/language/js20/index.html>
JScript .NET (JScript 7) implements typing of variables:
<URL:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/jscript7/html/jsoridatatypes.asp
2. The ECMAScript Language Specification Ed 3, Section 9:
"The ECMAScript runtime system performs automatic type
conversion as needed."
Read the rest of the section to get an idea of how it works.