A brief overview of JavaScript Objects

Srinjoy Santra
5 min readMar 19, 2019
Photo by Clément H on Unsplash

In JS, an object is an unordered collection of associated key/value pairs (properties). Each property can reference a primitive type (string, number, boolean, null, undefined) or another object (array, functions, etc).

There are two types of two forms of objects,

  • Literal (Declarative form)
const developer = {
name: 'Srinjoy Santra',
age: 21,
"isGraduate": false
};
  • Constructed form
const developer = new Object();
developer.name = 'Srinjoy Santra';
developer.age = 21;
developer['isGraduate'] = false;

Let’s break these down and see what’s going:

  • The variable that is assigned to the object is named developer.
  • Curly brackets are used to define the developer object.
  • Individual keys (e,g, name) are associated with a single value ('Srinjoy Santra' in this case). These key/value pairs are connected by a colon (:).
  • Each distinct key/value pair, known as a property of that object, is separated from other properties by a comma (,). The developer object, therefore, contains three properties.
  • The second form creates a new empty object.
  • Then the properties are added one by one.
Photo by Tim Gouw on Unsplash

Create and Modify Properties

Accessing Object Properties

There are two ways to access object values,

  • Dot notation
developer.age; // 21
  • Bracket notation
developer['isGradute']; // false

Both notations are equivalent but there’s a catch.

Suppose we try to access a new property from the developer object.

developer.1 // Uncaught SyntaxError: Unexpected number

developer[1]; // (returns the value of the `1` property)

Also, if we try to access a property of it using another variable that stores a key.

const  variable = 'name';developer[variable]; // "Srinjoy Santra"developer.variable; // undefined

Updating objects

  • Updating existing properties
developer.age += 3; // 24
developer.isGraduate = true; // true
  • Adding a new property
developer['company'] = 'Google'; // 'Google' Kidding!
  • Deleting a property
delete developer.company; // true

Passing an object

Objects in JS are mutable, unlike primitives. If you pass an object into a function, JS passes a reference to that object.

function upgradeSkills(object){
object.skiils[3]='Python';
}
developer.skills = ['Javascript','HTML','CSS'];
upgradeSkills(developer)
developer.skills
//(4) ["Javascript", "HTML", "CSS", "Python"]

Well, that’s cool, unless an impostor object gets an opportunity to copy the details of the developer object.

impostor = developer
impostor.name = 'John Smith'; /* That's the most used FB name */
impostor
//{name: "John Smith", age: 24, isGraduate: true, skills: //Array(4)}
developer
//{name: "John Smith", age: 24, isGraduate: true, skills: //Array(4)}

Since objects are passed as references, making changes to the copy directly affects the original object. In both the objects, impostor and developer , the name is "John Smith" now.

Comparing an object with another object

Suppose another newImpostor gains access to the developer object values and fill up the details as follows.

const newImposter = {
name : 'John Smith',
age : 24,
isGraduate : true,
skills : ['Javascript','HTML','CSS','Python']
}
newImposter === developer // false

The fact is, the last expression returns true only when the two references exactly to the same object.

impostor === developer // true
Photo by Chester wade on Unsplash

Invoking Object Methods

Remember, in the definition of JS object, I mentioned that an object can have another object like methods/functions etc as its property.

developer.greeting = function () {
console.log('Hello!');
};
developer['greeting']();// "Hello!"

A clarification needs to be done. Methods and functions are used interchangeably. But they have a slight difference. A method is a part of an object while a function is not. Do look up the link below. https://stackoverflow.com/questions/155609/whats-the-difference-between-a-method-and-a-function

Passing arguments into methods

developer['hobby'] = function tell(task) {
console.log(`My hobby is ${task}.`);
};
developer.hobby(); // "My hobby is blogging."

Did you notice that this time apart from passing arguments to the method, we have also named the function? Both (anonymous or named) are valid syntax.

A Method Can Access the Object it was Called On

developer.identify = function() {
console.log(`I am ${this.name}.`);
}
developer.name = 'Srinjoy Santra';
developer.identify();//"I am Srinjoy Santra."

What’s this? This is a reserved keyword. The value of this is determined when a method is invoked and its value is the object on which the method was called.

Don’t worry if you did not get it now. We’ll come back to this again.

Photo by Amy Humphries on Unsplash

Beware of Globals

The keywordthis is not bound. A classic example of that is the code below.

function knows() {
this.knowledge = true
}

knows();// undefined

#1. How the function is invoked determines the value of this inside function.

Scroll up and read how the identify() function was called.

developer.identify();

So, inside the object this will refer to the developer object.

#2. When a regular function is invoked, the value of this is the global window object.

The knows() function was called like a regular function (not called as a method on an object).

knows();

The window object is a part of W3C specifications which has access to a ton of information about the page itself.

Well, if that was enough to digest but there’s more.

Global variables are properties and global functions are methods on the window object

var javascriptIsCrazy = true;
(window.javascriptIsCrazy === javascriptIsCrazy); // true
let mentalCondition = 'sane';
(window.mentalCondition === mentalCondtition); // false
knows === this.knows; // true
knows === window.knows; // true

A variable declared outside of a function with a let or const will not add the variable as a property of window object.

Avoid Globals

Among countless reasons why we should not use globals, the two cases of tight coupling and name collisions are very common. Check this for more such cases. http://wiki.c2.com/?GlobalVariablesAreBad

Tight Coupling

let nation = 'India';
function greeting(){
console.log(`${nation} greets with Namaskar.`);}

If we refactor the global variable nation to country it breaks the function.

Photo by Ian Schneider on Unsplash

Extracting Properties and Values

Object() constructor function has access to several methods. Two notable methods are

Object.keys()

Object.keys(developer)
\\(7) ["name", "age", "isGraduate", "skills", "hobby", "identify", \\"greeting"]

Object.values()

Object.values(developer)
(7) ["Srinjoy Santra", 24, true, Array(4), ƒ, ƒ, ƒ]

Object.keys() is supported by every browser whereas Object.values() being added recently in 2017 may not be supported by all.

Do you see a mistake in there? Mention in the comments.

Did you like it? Show your support through claps 👏.

Follow me and stay tuned for further articles.

I’m Srinjoy Santra. An aspiring web developer. You can connect with me on LinkedIn, visit my Github account, or follow me on Twitter.

You can also check me out at Quora, Instagram, and Wordpress.

(This article is taken from the notes I made while I was doing Udacity’s Front-end Web Development Nanodegree)

--

--