Objects in JavaScript For beginners

ericawanja

Ericawanja

Posted on August 3, 2022

Objects in JavaScript For beginners

Objects are dictionary like items which are defined as a key-value pair.

It is a reference data type. That is, object variables are assigned reference pointer that points the location storage in memory. Loosely speaking, if you modify the assigned variable(pointer) then the original value in the memory will be modified too.

Unlike arrays, objects are unordered hence you cannot use indexes to access items. Don't worry we will discuss later how to access items.

Example of an object;

let person = {
    firstName: 'John',
    lastName: 'Doe'
};
Enter fullscreen mode Exit fullscreen mode

How to create an object in JavaScript

  • Object literal

This is the easiest way to create objects in JavaScript where you define and initialize the object inside curly brackets with a key:value pair.

Image description

The key, which is also referred to as a property name must be a string while the value property can be of any data type.

For instance;

let person = {
    firstName: 'John',
    lastName: 'Doe'
};
Enter fullscreen mode Exit fullscreen mode

The variable person has two properties, i.e firstName and lastName

  • New Object keyword

We can use the new Object()constructor to initialize an object.
Notice in this case, you will have to add the properties later.

const person = new Object(); //initializing an object
person.firstName = "John"; // adding property firstName with a value of John
person.lastName = "Doe";
Enter fullscreen mode Exit fullscreen mode
  • Object constructor

Object constructor function acts as a blueprint for creating multiple objects. The key values are passed as function parameters.

function Student(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
}
//lets create student1 and student2 objects
const student1= new Student("John", "Doe", 50, "blue");
const student2 = new Student("Sally", "Rally", 48, "green");
Enter fullscreen mode Exit fullscreen mode

## When should you use objects

  1. Objects are useful in storing with a key-value pair
  2. Useful in grouping values with similar characteristics together to make your code more readable. ## Drawbacks of JavaScript objects
  3. Object properties are unordered, hence does not support accessing items with indexes. You must know the property name.
  4. Does not support operations such as adding or removing an item at a particular position.

## How to access items in an object

Object properties can be accessed using a dot or bracket notation.

For instance:

    let person = {
       firstName: 'John',
       lastName: 'Doe'
};

person.firstName // outputs 'John'
person ['lastName'] //outputs 'Doe'

//Notice that the property is passed as a string in the bracket notation.
Enter fullscreen mode Exit fullscreen mode

If you access an unassigned property in an object it outputs undefined and not null

person.age //undefined
Enter fullscreen mode Exit fullscreen mode

The dot operation can only be used if the property is a valid JavaScript identifier.

A dot operation will throw an error if the property name has a space, hyphen or if the property is dynamically determined. In such circumstances use the bracket notation.

let address = {
    'building no': 3960,
    street: 'North 1st street',
    state: 'CA',
    country: 'USA'
};
address['building no'] //3960
Enter fullscreen mode Exit fullscreen mode

How to add and change properties in an object

Adding properties in objects is so simple. Access the property and assign a value to it. Let's add age and building no to our person object.

Similarly, you can change a value property by assigning it to a new value.

let person = {
   firstName: 'John',
   lastName: 'Doe'
};

person.age = 16
person['building no'] = 3960
//change the firstName to Jane
person.firstName = 'Jane'

console.log(person.age)//16

console.log(person['building no'])//3960
Enter fullscreen mode Exit fullscreen mode

How to delete properties in an object

The delete operator is used to delete both the property and its value in objects.

delete person.age 
delete person['building no']

/* Before deletion: person.age = 16, 
                   person['building no'] = 3960
after deletion, person.age = undefined
                  person['building no']= undefined
*/
Enter fullscreen mode Exit fullscreen mode

## How to iterate an object
The fastest way to transverse an object is using for..in loop.

For instance;

let person = {
    firstName: 'John',
    lastName: 'Doe'
};

for(let x in person){
    console.log(x  ) // outputs all the properties
}

Enter fullscreen mode Exit fullscreen mode

How to check if a property exists in an object

Use the in operator to check if a certain property exists in the object. It returns a boolean.

'age' in person // true
'country' in person //false
Enter fullscreen mode Exit fullscreen mode

similarly, the hasOwnProperty() method can be used to check if the property exist.

person.hasOwnProperty('age') //true
Enter fullscreen mode Exit fullscreen mode

in vs hasOwnProperty()

in returns true if the object exists in the object even if it has been inherited from another object.

let obj={
    age:16
}
const obj2= Object.create(obj) // 

console.log('age'in obj2) //outputs true
Enter fullscreen mode Exit fullscreen mode

However hasOwnProperty() method returns true only if the property is a direct property of the object.

let obj={
    age:16
}
const obj2= Object.create(obj) // 
obj2['name'] = 'John' //adding the name property

obj2.hasOwnProperty('age') //false
obj2.hasOwnProperty('name') //true
Enter fullscreen mode Exit fullscreen mode

Note;obj2.hasOwnProperty('age') returns false because age is not a direct property of the obj2.

object methods

An object method, is an object property that is a function.

let person = {
   firstName: 'John',
   lastName: 'Doe',
   fullName: function(){
    return this.firstName + " " + this.lastName 
   }
};

console.log(person.fullName()) // John Doe
Enter fullscreen mode Exit fullscreen mode

this keyword is used to refer to the object

Note: You can also pass parameters in the method

Conclusion

Objects are a very important data-type in JavaScript since it forms a building block of many other data structures such as linked list and modern JavaScript classes.

💖 💪 🙅 🚩
ericawanja
Ericawanja

Posted on August 3, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

JavaScript Variables
javascript JavaScript Variables

March 2, 2023

Data Types In JavaScript
javascript Data Types In JavaScript

January 27, 2023

Why are the results like this?
javascript Why are the results like this?

December 27, 2022