JavaScript Objects

JavaScript Objects

·

8 min read

It's time to take a deeper look at another type of storage: object.

The object initializer syntax starts with an open curly brace { and ends with a closed curly brace} with a list of key-value pairs in the middle. Let's take a look at a person's object:

const person = {
    hairColor: "brown",
    toes: 10,
    grumpy: true
}

This object demonstrates that we can use numbers, strings and booleans as values.

This person has "brow" hairColor, 10 toes and is grumpy, unfortunately.

We can retrieve these values by key:

console.log(person.toes);//10
console.log(person.hairColor);//brown

We can even store other objects as values! But let's not get carried away for now

What is an Object?

JavaScript is an object-oriented language and in JavaScript, nearly everything is an object or acts like an object. So, to work with JavaScript effectively and efficiently we need to understand how objects work as well as how to create our own objects and use them.

A JavaScript object is just a collection of named values. These named values are usually referred to as properties of the object. If you remember from the JavaScript arrays chapter, an array is a collection of values, where each value has an index (a numeric key) that starts from zero and increments by one for each value. An object is similar to an array, but the difference is that you define the keys yourself, such as name, age, gender, and so on. In the following section, we'll learn about objects in detail.

Objects creation

Object literal (direct way)

In JavaScript, objects start with an open curly brace { and end with a closed curly brace}. With an optional list of properties. We can put key-value pairs in between these braces. where the key (or property name) is always a string and value (or property value) can be any data type, like strings, numbers, Booleans or complex datatype like arrays functions, and other objects. Additionally, properties with functions as their values are often called methods to distinguish them from other properties.

Let's take a look at a simple object:

const team = {
    name:"Mets",
    wins: 86,
    inPlayoffs: false,
};

In this object team, we have three keys: name, wins and inplayoffs

The value associated with name is "Mets", with wins is 86 and with inPlayoffs is false. This is the easiest and preferred way to create a new object in JavaScript, which is known as object literals syntax

The property names generally do not need to be quoted unless they are reserved words, if they contain spaces or special characters (anything other than letters, numbers and the _ and $ characters), or if they start with a number, as shown in the following example:

const person ={
    "first name": "Peter",
    "current age": 28,
    gender:"Male"
}

Note: Since ECMAScript 5 , reserved words can be used as objet's property names without quoting. However, you should avoid doing this for better compatibilit.

2.Object.create()

the method creates a new object with the specified prototype and priorities of the old object.

Note: Every JavaScript funtion has a prototype object property by defalut (it is empty by defalut). Methods or properties may be attached to this property

const newPerson = Object.create(person);
//this create a new object with old object added in its prototype

We can now add new properties and data to newPerson object using the method we are learning here.

Note: The newPerson will have access to the parent person object keys and value as it's been added to newPerson prototype chain and this is one way we do inheritance in JavaScript. That is, newPerson will store a link to person object. This parent object is also consulted when a property is read.

Don't worry if you did not get this right now we will discuss in the future

The parent can have a parent and so on. This repeated until we reach an object that does not have any parent i.e the parent is null

3.Object Instance

The use of an object constructor in conjunction with the "new" keyword allows us to initialize new objects.

const newObj = new Object();
newObj.name = "Mike";
newObj.location = "New York";

However, the above method using new Object() is not well suited to programs that require the creation of multiple objects of the same kind, as it would involve repeatedly writing the above lines of code for each such object. To deal with this problem, we can use the next method

4.Object constructor

Constructors can be useful when we need a way to create an object "type" that can be used multiple times without having to redefine the object every time and this could be achieved using the Object Constructor function

function Vehicle(name, modle){
    this.name = name;
    this.modle = modle;
}
let car1 = new Vehicle("Fiesta", 2019);
let car2 = new Vehicle("DC avanti", 2018);

Note : this is a keyword that is used for object oriented programming

Retrieve Values

OK, awesome! It's time to retrieve values from our object.

In the last stage, we created an object with keys and values:

const team ={
    name:"Mets",
    wins:86,
    inPlayoffs: false,
};

The key name corresponds to the string "Mets".

If we wanted to retrieve the name of the team, we can do this in two ways:

console.log(team.name);//Mets
console.log(team['name']);//Mets

We can use the . property accessor operator or we can use brackets[ ] just like with arrays!

You can even supply a variable in the brackets [ ]

Array of Objects

Things get interesting when we start to put objects inside the array and vice-versa!

Let's take our team example again:

const team ={
    name:"Mets",
    wins: 86,
    inPlayoffs: false,
}

In a league, we might have many teams:

const teams = [team1, team2, team3];
for(let i=0; i<teams.length; i++){
    console.log(teams[i].name);
}

This example loops over each team and logs out the name of each team.

This code assumes that each team has a name property. If the team is an object without a name property, this will log undefind.

Enumerated Types

Code is more readable and maintainable when numbers are defined.

Take the following example:

const card = {
    suit:1,
    value:5
}

What is this card's suit? We know the value is 1, but what does that mean?

Let's define CARD_SUITS:

const CARD_SUITS ={
    DIAMONDS: 0,
    HEARTS: 1,
    SPADES: 2,
    CLUBS: 3,
}

Using this object we can clearly label our card suit:

const card ={
    suit: CARD_SUITS.HEARTS,
    value:5
}

The value of the suit would still be 1, however, this clearly defines what that suit means in its definition!

Also, if we ever want to change what suit corresponds to which value, we only need to change it once in CARD_SUITS.

This type of object is commonly referred to as an Enumeration. As with any pre-defined constant, it's common to use UPPER_SNAKE_CASE for enumerations in JavaScrips

Importing Files

It's time to import our first file! Let's import the ORDER_TYPES we just created into numberOfPizzas.js

We can use require to pull in the exports from orderType.js

const ORDER_TYPES = require('./fileLcation');

Find the Number of Keys

There are a couple of ways to get all the keys in an object

We can use the in operator to iterate over all properties:

const object = { a:1, b:2, c:3};
for(let key in object){
    console.log(key);
}

Over three iterations this will log a, b, and c which are the keys of the object.

Additionally, we can use some methods on the object constructor itself, which will return an array of the requested data:

const object  = {a:1, b:2, c:3};
console.log(Object.keys(object));
//['a','b','c']
console.log(Object.values(object));
//[1,2,3]

There are actually quit a few methods on object, you can find

Edit Object Values

Sometimes it's necessary to edit the values in an object!

We can edit the value directly, similar to the syntax for retrieving values:

const person ={
    name: "James",
    age: 22
}
person.name = "Sally";
person["age"] = 30;

console.log(person.name);//Sally
console.log(person.age);//30

Just like retrieval we can use the . or [ ] notation.

We can also remove keys completely:

const person = {
    name: "Bob"
}
delete person.name;
console.log(person.name);//undefined

He lost his own name. How sand

Object References

It's an important distintion in JavaScript that objects are passed by reference!

Let's create a function that modifies an object:

function modify(object){
    object.massage = "Hello World";
}

Let's create an object and pass it to this funtion :

const store = {
    name: "Seven Eleven"
}
modify(store);
console.log(store.massage);//Hello World

Look at taht! The store's massage has been updated.

Inside the modify function the object argument is referencing the same memory as the store. This is what it means to pass by reference.

When the modify function updates the object, it is updated everywhere else it is referenced

It is always a good idea to be careful about modifying objects directly! Modifying a reference like this is reffered to as a side effect in funtional programming.

The function is modifing something outside of its scope, potentially leading to unexpected consequences!