Objects in JavaScript

javascript
Elvis Duru

Elvis Duru / August 6, 2021 

5 min read --- views

An object in JavaScript is a self-contained collection of named properties that map to any JavaScript value such as strings, number, booleans, arrays, functions and even objects. If a property's value is a function it is known as a method.

Objects are usually created to represent entities of the real world, like users, orders and so on. They are often used to keep any related information and functionality together in the same place.

An Example

JS
const employee = {
	firstName: "John",
	lastName: "Doe",
	salary: 1000,
	department: "Engineering",
	role: "Junior Frontend Developer"
	printName() {
		console.log(this.firstName + " " + this.lastname;
	}
}

Creating Objects

Objects can be created using an object literal or the inbuilt constructor function.

JS
// Object literal
const user = {}

// Creating object via a contructor function
const user = new Object();

ES6 provides a shorthand method of creating objects if property key is the same as a variable name that the property value is assigned to:

JS
const name = "Elvis Duru";
const age = 25;

// Old long way
const user = {name: name, age: age};

// Short ES6 way
const user = {name, age}

Accessing Properties

You can access the properties of an object using the dot notation or bracket notation:

JS
// Dot notation
user.name
>> "Elvis Duru"

// Bracket notation
user["name"]
>> "Elvis Duru"

// If you try to access a property that does not exist you get undefined
user.salary
>> undefined

// You can also call methods using the dot or bracket  notation
employee.printName()
employee["printName"]()

The dot notation is common but the bracket notation has some advantages. It can let you access properties that don't follow the variable naming rules. It also lets you evaluate an expression and use it as the property key:

JS
user["na" + "me"]
>> "Elvis Duru"

Checking if Properties or Methods Exist

The in operator and the hasOwnProperty() method can be used to check whether an object has a particular property or method

JS
'age' in user
>> true

user.hasOwnproperty('name');
>. true

Finding all the Properties of an Object

We can loop through all properties in an object using the for in loop:

JS
for (const key in user) {
	console.log(`${key}: ${user[key]}`)
}
>> "name: Elvis Duru"
>> "age: 25"

/* To make sure an object's own properties are returned, we can modify the example above
*/

// We can do this
for (const key in user) {
	if(user.hasOwnProperty(key)) {
		console.log(`${key}: ${user[key]}`)
	}
}

The object.keys() method returns an array of all the keys of an object. Also the object.values() method returns an array of all the values of an object.

JS
console.log(Object.keys(user))
>> ["name", "age"]

console.log(Object.values(user))
>> ["Elvis Duru", 25]

Adding Properties

New properties and methods can be added to an existing object at any time:

JS
const user = {
	firstName: 'Elvis',
	lastName: 'Duru'
}

user.middleName = 'Ihechi'

user
>> {
		firstName: 'Elvis',
		lastName: 'Duru',
		middleName: 'Ihechi'
	}

Never rely on properties to always appear in the order they were entered.

Removing Properties

You can use the delete operator to remove properties from an object

JS
delete user.middlename;
>> true
user
>> {
			firstName: 'Elvis',
			lastName: 'Duru'
		}

Nested Objects

It's possible for objects to contain other objects and data types:

JS
const user = {
	firstName: 'Elvis',
	lastName: 'Duru',
	scores: [10, 10, 5, 9, 10],
	abilities: {
		speech: true,
		flight: false,
	}

Objects Are Copied By Reference

Just like arrays, objects are copied by reference.

JS
const userA = {name: 'Elvis'}
const userB = userA;
// Changing the value of the name property in the object assigned to userB.
userB.name = 'Daniel';
// results in the name value of userA changing as well
userA
>> {name: 'Daniel'}

this

To access an object, a method can use the this keyword. The value of this is the object that calls the method. For instance:

JS
let user = {
  name: "John",
  age: 30,

  sayHi() {
    // "this" is the "current object"
    alert(this.name);
  }

};

user.sayHi(); // John

this is not bound

In JavaScript, this can be used in any function, even if it's not a method of an object.

JS
/*
The value of this is evaluated at run-time, depending on the context.
*/
function sayHi() {
  alert( this.name );
}

let user = { name: "John" };
let admin = { name: "Admin" };

// use the same function in two objects
user.f = sayHi;
admin.f = sayHi;

// these calls have different this
// "this" inside the function is the object "before the dot"
user.f(); // John  (this == user)
admin.f(); // Admin  (this == admin)

admin['f'](); // Admin (dot or square brackets access the method – doesn't matter)

// this is undefined in strict mode but the window object in non-strict mode.
sayHi(); // undefined

Arrow functions have no this

Arrow functions don't have their "own" this. If this is referenced from such function, it's taken from the outer "normal: function:

JS
let user = {
  firstName: "Ilya",
  sayHi() {
    let arrow = () => alert(this.firstName);
    arrow();
  }
};

user.sayHi(); // Ilya

if you use arrow functions within an object method, the this context stays as the object, not window.

Changing this with bind

bind is a method that's present in every function. It allows you to change the this context.

JS
function sayThis () {
  console.log(this)
}
const boundFunc = sayThis.bind({hippy: 'hipster'})
boundFunc()
>> {hippy: "hipster"}

Conclusion

That's it! Hopefully this helps explains the fundamental bits about Objects in JavaScript and some ways you can work with them. Feel free to leave let me know if I missed anything. Thanks for reading!

Get the latest articles, in your inbox

Every couple of weeks, I share the best content from my blog. It's short, sweet, and practical. I'd love you to join. You may opt out at any time.