JavaScript Objects
Tags: javascript, codenewbie, tutorial, webdev
Published: 2021-02-06 16:36:32

{% youtube Je5d0cjOhyQ %}

---
The object data type is the 8th data type and only the non-primitive data type. In this article, we will see how to create and access objects in JavaScript.

---
### How to create an object
Objects are created with curly brackets containing properties, `{ ... }`. 

Empty objects are objects with no property list.

> A property is a `"key": value` pair. Keys are in quotes if it is multi-word but without quotes if in a single word. The values are anything. The key is also called name and value, identifier.

Note: It is a good practice to use the camelCase naming convention for keys, `myName`, not `my name`.

See the below syntax:

```
obj = { key1: value1, key2: value2, ..., keyN: valueN }
```

The syntax above is called **object literal syntax**

See the example below:

```js
const person = { 
    myName: "John Doe", 
    age: 34,
    isDoctor: true
}
```

> Property names are always in strings even though not specified. That is, `age` property is the same as `"age"`.


When you write object properties in multiple lines, as shown above, it is called the **trailing** or **hanging** comma.

Every box (object) has keys to access specific items (values).


An empty object can also be filled by appending properties to it.

```js
const person= {};

person.name = "John Doe";
person.age= 34;
person.isDoctor= true
``` 

To create a new object, the syntax is shown below:

```js
obj = new Object();
```

---
### Accessing Keys
There are two ways to access key properties in JavaScript, they are:
- Dot notation
- Square bracket 

#### Dot Notation
See the example below on how to access the value, 34:

```js 
const person = { 
    "my name": "John Doe", 
    age: 34,
    isDoctor: true
}

person.age; // 34 => dot notation
```

`person.age` accessed the value, 34 through **dot notation**

---
#### Square brackets
The dot notation doesn't work when keys contain special characters like space.

```js 
const person = { 
    age: 34,
    isDoctor: true
}

person["my name"] = "John Doe";

console.log(person); 
// { age: 34, isDoctor: true, 'my name': 'John Doe' }

person["my name"]; // John Doe => square brackets notation
```

---
### Computed Properties
Square brackets can be used in an object literal also to create object properties. Such properties are called **computed properties**.

See the example below:

```js 
const name = "myName" ;

const person = { 
    [name]: "John Doe",
    age: 34,
    isDoctor: true
}

console.log(person.myName);  // John Doe
```

---
### Object in a function
We can also have a function nesting object(s). The example above is similar to the code below but with a better style. The advantage of the code below is that the object is now locally scoped in the function (to avoid scope pollution).

```js
const personDetails = name => {
  const person = {
    name: name,
    age: 34,
    isDoctor: true
  };

  return person;
};

const p = personDetails("John Doe");

console.log(p.name); // John Doe
```

---
<a href="https://www.whogohost.com/host/aff.php?aff=7390&page=hosting" target="_blank"><img src="https://www.whogohost.com/images/affiliates/unlimited-hosting-728-x-90.png" /></a>

---
### Property Value Shorthand
It is also possible to use as many variables (and parameters) as values for property names (keys).

```js
const personDetails = (name, age, isDoctor) => {
  return {
    name: name,
    age: age,
    isDoctor: isDoctor
  };
};

const person = personDetails("John Doe", 34, true);

console.log(person.name); // John Doe
console.log(person.age); // 34
console.log(person.isDoctor); // true
```

It is common to use **special property value shorthand**. The function `personDetails()` above is called **factory function**. Factory function allows the creation of similar objects.

Instead of `name:name`, `age:age`, `isDoctor:isDoctor` we can just write `name`, `age`, `isDoctor` respectively.

```js
const personDetails = (name, age, isDoctor) => {
  return {
    name,
    age,
    isDoctor
  };
};

const person = personDetails("John Doe", 34, true);

console.log(person.name);
```

Both normal and shorthand properties can be in the same object.

```js
const personDetails = (age, isDoctor) => {
  return {
    name: "John Doe",
    age,
    isDoctor
  };
};

const person = personDetails(34, true);

console.log(person.name);
```

Alternatively declare the `obj` before returning it.

```js
const personDetails = (age, isDoctor) => {

  const obj = {
    name: "John Doe",
    age,
    isDoctor
  };

  return obj;
};

const person = personDetails(34, true);

console.log(person.name);
```

---
### Undefined properties
Accessing property values that do not exist in an object returns `undefined`.

```js
const person = { 
    age: 34,
    isDoctor: true
}

console.log(person.name); // undefined
```

---
### Property existence test
Properties can be tested for existence.

```js
const person = { 
    age: 34,
    isDoctor: true
}

person.name === undefined; // true
```

Alternatively, properties can be tested for existence by the special operator `in`.

The example above is the same as below:

```js
const person = { 
    age: 34,
    isDoctor: true
}

"name" in person; // false
```

Here is another example

```js
const person = { 
    name: undefined,
    age: 34,
    isDoctor: true
}

"name" in person; // true 
```

The result fails if `person.name` is used. 

See example below:

```js
const person = { 
    name: undefined,
    age: 34,
    isDoctor: true
}

person.name; // undefined
```

---
### Looping through Objects
To loop through object keys or values, the `for...in` syntax is used.

```js
for (key in object) {
  // statements to loop through keys
}
```

See the example below:

```js
const person = { 
    yourName: "John Doe", 
    age: 34,
    isDoctor: true
};

for (let key in person) {
    // keys
    console.log(key);  // yourName, age, isDoctor

    // values for the keys
    console.log(person[key]); // John Doe, 34, true
}
```

---
### Ordered Objects
Objects are sorted if the keys are integers

See the example below:

```js
const person = { 
    "20": "John Doe", 
    "1": 34,
    "3": true
};

for (let key in person) {
    // keys
    console.log(key);  // 1, 3, 20

    // values for the keys
    console.log(person[key]); // 34, true, John Doe
}
```

The ordering above does not work for non-integer keys or decimal number keys.

```js
const person = { 
    "+1": "John Doe", 
    "2.0": 34,
    "bool": true
};

for (let key in person) {
    // keys
    console.log(key);  // +1, 2.0, bool

    // values for the keys
    console.log(person[key]); // John Doe, 34, true
}
```

**Happy coding!**

---
[![Buy me a Coffee](https://res.cloudinary.com/bizstak/image/upload/v1610317510/ko-fi-trans_fr3su4.png)](https://www.buymeacoffee.com/techstackmedia)

---

### TechStack | Domain
- Purchase a `.com` domain name as low as $9.99.
- Purchase a `.net` domain name as low as $12.99.
- Get cheaper domain names as low as $3.
-  Build a website with ease.

<a href="https://domain.mno8.net/c/2653712/848391/9560" target="_top" id="848391"><img src="//a.impactradius-go.com/display-ad/9560-848391" border="0" alt="" width="300" height="250"/></a><img height="0" width="0" src="https://imp.pxf.io/i/2653712/848391/9560" style="position:absolute;visibility:hidden;" border="0" />