An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces (
{}
). You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block.The following is an example of an object literal. The first element of the
car
object defines a property, myCar
, and assigns to it a new string, "Saturn
"; the second element, the getCar
property, is immediately assigned the result of invoking the function (CarTypes("Honda"));
the third element, the special
property, uses an existing variable (Sales
).var Sales = "Toyota";
function CarTypes(name){
if(name == "Honda"){
return name;
}else{
return "Sorry, we don't sell "+name+".";
}
}
var car = {myCar:"Saturn",getCar:CarTypes("Hondas"),special:Sales};
console.log(car.myCar);
console.log(car.getCar);
console.log(car.special);
Result:
Saturn
Sorry, we don't sell Hondas.
Toyota
---------------------------
var car = {manyCars:{a:"Saab","b":"Jeep"},7:"Mazda"};
console.log(car.manyCars.b);
console.log(car[7]);
Result:
Jeep
Mazda
---------------------------
Invalid JavaScript identifier
var unusualPropertyNames = {
"": "An empty string",
"!":"Bang!"
}
console.log(unusualPropertyNames[""]);
console.log(unusualPropertyNames["!"]);
console.log(unusualPropertyNames.""); // Error
console.log(unusualPropertyNames.!); // Error
Result:
An empty string
Bang!
Object property names can be any string, including the empty string. If the property name would not be a valid JavaScript identifier, it must be enclosed in quotes. Property names that would not be valid identifiers also cannot be accessed as a dot (
.
) property, but can be accessed and set with the array-like notation("[]
").------------------------------
NOTE!
var foo = {a:"alpha",2:"two"};console.log(foo.a);
console.log(foo[2]);
console.log(foo["a"]);
console.log(foo["2"]);
console.log(foo.2); // Error
console.log(foo[a]); // undefined
Result:
Result:
alpha
two
alpha
two
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types