Objects in JavaScript are very similar to arrays, but
objects use strings instead of numbers to access the
different elements. The strings are called keys or
properties, and the elements they point to are called
values. Together these pieces of information are called
key-value pairs. While arrays are mostly used to
represent lists of multiple things, objects are often used to represent single things with multiple characteristics, or
attributes.
Basic syntax for creating an object:
var cat = {
"legs": 3,
"name": "Harmony",
"color": "Tortoiseshell"
};
When you create an object, the
key goes before the colon (:), and
the value goes after. The colon acts
a bit like an equal sign—the values
on the right get assigned to the
names on the left, just like when
you create variables. In between
each key-value pair, you have to
put a comma. In our example, the commas are at the ends of the
lines—but notice that you don’t need a comma after the last keyvalue
pair (color: "Tortoiseshell"). Because it’s the last key-value
pair, the closing curly bracket comes next, instead of a comma.
Keys Without Quotes
var cat = {
legs: 3,
name: "Harmony",
color: "Tortoiseshell"
};
JavaScript knows that the keys will always be strings, which
is why you can leave out the quotes. If you don’t put quotes around
the keys, the unquoted keys have to follow the same rules as variable
names: spaces aren’t allowed in an unquoted key, for example.
If you put the key in quotes, then spaces are allowed:
var cat = {
legs: 3,
"full name": "Harmony Philomena Snuggly-Pants Morgan",
color: "Tortoiseshell"
};
Accessing Values in Objects
Square brackets
You can access values in objects using square brackets, just like
with arrays. The only difference is that instead of the index (a
number), you use the key (a string).
cat["name"];
"Harmony"
Dot notation
Instead of typing the key
name in quotes inside square brackets after the object name, we
just use a period, followed by the key, without any quotes. As with
unquoted keys in object literals, this will work only if the key
doesn’t contain any special characters, such as spaces.
cat.name;
"Harmony"
Objects keys
Instead of looking up a value by typing its key, say you wanted
to get a list of all the keys in an object. JavaScript gives you an
easy way to do that, using Object.keys():
var dog = { name: "Pancake", age: 6, color: "white", bark: "Yip yap
yip!" };
var cat = { name: "Harmony", age: 8, color: "tortoiseshell" };
Object.keys(dog);
["name", "age", "color", "bark"]
Object.keys(cat);
["name", "age", "color"]
Adding Values to Objects
An empty object is just like an empty array, but it uses curly
brackets, { }, instead of square brackets:
var object = {};
You can add items to an object just as you’d add items to an
array, but you use strings instead of numbers:
var cat = {};
cat["legs"] = 3;
cat["name"] = "Harmony";
cat["color"] = "Tortoiseshell";
cat;
{ color: "Tortoiseshell", legs: 3, name: "Harmony" }
Combining Arrays and Objects
var dinosaurs = [
{ name: "Tyrannosaurus Rex", period: "Late Cretaceous" },
{ name: "Stegosaurus", period: "Late Jurassic" },
{ name: "Plateosaurus", period: "Triassic" }
];
To get all the information about the first dinosaur, you can use
the same technique we used before, entering the index in square
brackets:
dinosaurs[0];
{ name: "Tyrannosaurus Rex", period: "Late Cretaceous" }
If you want to get only the name of the first dinosaur, you can
just add the object key in square brackets after the array index:
dinosaurs[0]["name"];
"Tyrannosaurus Rex"
Or, you can use dot notation, like this:
dinosaurs[1].period;
"Late Jurassic"
***You can use dot notation only with objects, not with arrays.
The delete operator
The delete operator cuts off a tentacle from such an octopus. It is a unary
operator that, when applied to an object property, will remove the named
property from the object. This is not a common thing to do, but it is possible.
let anObject = {left: 1, right: 2};
console.log(anObject.left);
// → 1
delete anObject.left;
console.log(anObject.left);
// → undefined
console.log("left" in anObject);
// → false
console.log("right" in anObject);
// → true
Object.assign
let objectA = {a: 1, b: 2};
Object.assign(objectA, {b: 3, c: 4});
console.log(objectA);
// → {a: 1, b: 3, c: 4}
The Math object
Math is a grab bag of number-related utility functions, such as
Math.max (maximum), Math.min (minimum), and Math.sqrt (square root).
Math.random
This is a function that returns a
new pseudorandom number between zero (inclusive) and one (exclusive) every
time you call it.
// → 0.36993729369714856
75
console.log(Math.random());
// → 0.727367032552138
console.log(Math.random());
// → 0.40180766698904335
If we want a whole random number instead of a fractional one, we can use
Math.floor (which rounds down to the nearest whole number) on the result of
Math.random.
console.log(Math.floor(Math.random() * 10));
// → 2
Multiplying the random number by 10 gives us a number greater than or
equal to 0 and below 10. Since Math.floor rounds down, this expression will
produce, with equal chance, any number from 0 through 9.
There are also the functions Math.ceil (for “ceiling”, which rounds up to
a whole number), Math.round (to the nearest whole number), and Math.abs,
which takes the absolute value of a number, meaning it negates negative values
but leaves positive ones as they are.