Skip to main content

Objects

Resources

There are eight data types in JavaScript, seven of them are called “primitive”, because their values contain a single thing. In contrast, a non-primitive type like objects are used to store keyed collections of various data and more complex entities.

An object can be created with {...} with an optional list of properties*.

  • A property is a key: value pair, where key, or property name - is a string, and the value can be anything. An empty object can be created using one of two syntaxes:
let user = new Object(); // "object constructor" syntax
let user = {}; // "object literal" syntax

A property has a key before the colon: and a value to the right of it.

let user = {        // an object
name: "John", // the value "John" is stored in a key named "name"
age: 30 // value 30 is stored in a key named age
};

We can also use multiword property names, but they must be quoted:

let user = {
name: "John",
age: 30,
"likes birds": true
};

1. Object Shorthand Notation

// normally, we would write it as follows
const name = "Bob";
const age = 28;
const color = "red";

const myObject = { name: name, age: age, color: color };

However, since 2015, with a shortcut to creating objects added to JavaScript, if we have a variable with the same name as that of the property to which we are assigning it, we only need to write it once.

const myObject = { name, age, color };
console.log({ name, age, color });
// now it logs as - { name: "Bob", age: 28, color: "red" }

2. Destructuring Assignment

When you have an object, you can extract a property of an object into a variable of the same name, or any named variable for an array.

const array = [1, 2, 3, 4, 5];
const [ zerothElemenet, firstElement ] = array;
// This creates zerothEle and firstEle, both of which point
// to the elements in the 0th and 1st indices of the array

const obj = { a: 1, b: 2 };
const { a, b } = obj;
// This creates two variables, a and b,
// const a = obj.a;
// const b = obj.b;

Object Property

1. Set a property

user.isAdmin = true; 

2. Remove a property

delete user.age;

3. Access property values

  • Property values are accessible using the dot notation.
console.log(user.name); // John
console.log(user.age); // 30

4. Square brackets

  • For multiword properties with whitespaces, the dot access doesn’t work. Instead, we can use an alternative square bracket notation that works with any string:
let user = {}; 

// set
user["likes birds"] = true;

// get
console.log(user["likes birds"]); // true

// delete
delete user["likes birds"];
  • Square brackets can provide a way to obtain the property name as the result of any expression that the dot notation cannot do:
let user = {
name: "John",
age: 30
};

let key = prompt("What do you want to know about the user?");

console.log(user[key]); // John (if 'name' was entered)
  • We can use square brackets in an object literal when creating an object → computed properties.
let fruit = prompt("Which fruit to buy?"); 

let bag = {
[fruit + "Computers"]: 5, // the name of the property is taken from the variable fruit
}

console.log(bag.appleComputers); // 5 if fruit is apple

5. Property value shorthand

function makeUser(name, age){
return {
name: name,
age: age,
// ... other properties
}
}

In the example above, properties have the same names as variables. There’s a special property value shorthand to make this shorter.

function makeUser(name, age){
return {
name, // same as name: name
age, // same as age:age
}
}

Both normal properties and shorthands in the same object is possible:

let user{
name, // name: name
age: 30
}

6. Property names limitation

A variable cannot have a name equal to one of the language-reserved words like “for”, “let”, “return” etc. But for an object property, there’s no such restriction. In short, there are no limitations on property names, they can be any strings or symbols.

// these properties are all ok
let obj = {
for: 1,
let: 2,
return: 3
}
console.log(obj.for + obj.let + obj.return); // 6

Other types are automatically converted to strings: A number 0 becomes a string "0" when used as a property key:

let obj = {
0: "test" // "0": "test"
};
// both logs access the same property
console.log(obj["0"]);
console.log(obj[0]);

7. Check property existence - in operator

  • We we read a non-existing property, it’ll return undefined. So checking for undefined can be a way to see if the property exists.
let user = {}; 

console.log(user.noSuchProperty === undefined); // true
  • We can also use the special operator in for that:
// syntax
// the left side must be a quoted string of property name/key
"key" in object

// example
let user = {
name: "John",
age : 30
};
console.log("age" in user); // true
console.log("blabla" in user); // false

1. for...in loop

It's commonly used to iterate over the enumerable properties of objects.

// syntax
for (keyName in object){
//... code
}
// example
let user = {
name: "John",
age: 30,
isAdmin: true
};

for (let key in user){
console.log(key); // name, age, isAdmin
console.log(user[key]); // John, 30, true
}

2. Objects Sort Order

Keys that are integers are sorted in ascending order, other keys are sorted in creation order.

// example
// integer properties
let codes = {
"49": "Germany",
"41": "Switzerland",
"44": "Great Britain",
//...,
"1": "USA"
};

for (let code in codes){
console.log(code); // 1, 41, 44, 49 -> sorted in ascending order
}

// non-integer
let user = {
name: "John",
surname: "Smith"
};

user.age = 25;

for(let prop in user){
console.log(prop); // name, surname, age -> creation order
}

→ In this example, to fix the issue with the phone codes, we can “cheat” by making the codes non-integer. Adding a plus "+" sign before each code is enough.