Object Basics
We have already seen some special built-ins in JavaScript, such as the Wrapper objects (Number, String, Boolean). There are also Math, Date, RegExp, and several others.
These objects look like objects in Java or C++, but JavaScript objects do not work the way objects work in object-oriented languages. A JavaScript object is closer to a dictionary in Python (or a HashMap in Java, or a hash table in C++).
const user = { name: "John", age: 21 };
console.log(typeof user); // object
console.log(user); // {"name":"John","age":21}
Object Syntax
keymust be a string (or symbol); you can drop the single/double quotes whenkeyis a valid identifier.valuecould be anything: any primitive or object.- A
key-valueis paired with a colon. - Commas separate properties. It is okay to have a trailing comma!
const user = {
name: {
first: "John",
last: "Smith",
},
age: 21,
"Job Title": "Teacher",
};
You can access property value with dot notation or square bracket notation:
const user = { name: "John", age: 21 };
console.log(user.name); // John
console.log(user["age"]); // 21
You can modify property value the same way:
const user = { name: "John", age: 21 };
user["name"] = "Jane";
user.age = 30;
console.log(user.name, user.age); // Jane 30
You can even add new properties the same way:
const user = { name: "John", age: 21 };
user.lastName = "Smith";
user["member since"] = 2007;
console.log(user); // {"name":"John","age":21,"lastName":"Smith","member since":2007}
And, you can remove properties:
const user = { name: "John", age: 21 };
delete user.age;
console.log(user.age); // undefined
You can create an empty object and then add properties to it:
const user = {};
user.name = "John";
console.log(user); // {"name":"John"}
Note that you can make an empty object using object constructor syntax as follows:
const obj = new Object();
But it is more common to use the object literal syntax instead:
const obj = {};
We can use square brackets in an object literal when creating an object. That is called computed properties.
const key = "age";
const value = 21;
const user = { [key]: value };
console.log(user); // {"age":21}
There is a common shorthand where you write just a variable name and get a key-value pair out of it, as in the example below:
const age = 21;
const user = { name: "John", age };
console.log(user);
If a variable is used as above, a key-value pair is created where the key is the variable’s name, and the value is the variable’s value. It is the same as:
const age = 21;
const user = { name: "John", age: age };
Destructuring Objects
Destructuring is a convenient syntax for pulling several properties out of an object at once:
const user = { name: "John", age: 21 };
let { name, age } = user;
console.log(name, age); // John 21
You can rename the properties:
const user = { name: "John", age: 21 };
let { name: userName, age: userAge } = user;
console.log(userName, userAge); // John 21
You can even do this:
const user = { firstName: "John", lastName: "Smith", age: 21 };
let { age, ...rest } = user;
console.log(age, rest); // 21 {"firstName":"John","lastName":"Smith"}
JSON
JSON (JavaScript Object Notation) is a standard text-based format for representing structured data based on JavaScript object syntax. It was popularized by Douglas Crockford and is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client so that it can be displayed on a web page, or vice versa).
JSON closely resembles JavaScript object literal syntax except:
- Property names (keys) must be enclosed in double-quotes.
- Property values are numbers, strings,
true,false,null, arrays, and objects. - Trailing commas, skipped elements (inside arrays), or
undefinedvalues not allowed.
There is a special built-in JSON object that contains methods for parsing JSON and converting values to JSON:
const user = { name: "John", age: 21 };
// Convert object to JSON string
const jsonString = JSON.stringify(user);
console.log(jsonString); // '{"name":"John","age":21}'
// Parse JSON string back to object
const parsed = JSON.parse(jsonString);
console.log(parsed.name); // John