Objects in JavaScript

Henna Singh
5 min readApr 8, 2022
#BuildTogether Day 61/100

Fridays are supposed to be exciting but this time, it wasn’t. But that’s life, isn’t it? You just make do at times. ;)

100DaysOfCode was supposed to be a learning journey but it is turning out to be my diary entry as well which I think I am kind of liking, only that it is a little more open-source :P

Sometimes I find it hard to balance my thoughts to separate different sides of my life. I now acknowledge that I need to maintain boundaries and perhaps not mix them, a little Friday wisdom I guess 😇

On another note, I am leading Diversity Scholarships at MongoDB World 2022 this year. I am both excited and nervous about it :D. If you identify yourself as belonging to underrepresented groups in technology (women, lgbtqia, latinx. women of color, and more), please feel free to apply and share in your network as well 🙏

Let’s continue to Javascript objects and this was an informational study 😍

Objects

JavaScript loves objects as it can model real-world things and helps make data structures that make the web possible ;)

Simply put, objects are containers storing related data and functionality.

Creating Object Literals

Curly braces are used to designate an object literal

let spaceship = {}; //spaceship is an empty object

Data in an object is unordered and organized into key-value pairs. A key is like a variable name that points to a location in memory that holds a value.

A key’s value can be any primitive data type or a function. Keys are strings, if there is no special characters in it, quotes can be omitted.

// An object literal with two key-value pairslet spaceship = {
'Fuel Type': 'diesel',
color: 'silver'
};

The spaceship object has two properties Fuel Type and color. 'Fuel Type' has quotation marks because it contains a space character.

Accessing Properties

There are two ways we can access an object’s property:

dot notation .

object’s name followed by the dot operator

let spaceship = {
homePlanet: 'Earth',
color: 'silver'
};
spaceship.homePlanet; // Returns 'Earth',
spaceship.color; // Returns 'silver',
spaceship.favoriteIcecream; // Returns undefined as this does not exist

bracket notation []

bracket notation is recommended when accessing keys that have numbers, spaces, or special characters in them. Code throws an error without the notation in these situations.

let spaceship = {
'Fuel Type': 'Turbo Fuel',
'Active Duty': true,
homePlanet: 'Earth',
numCrew: 5
};
spaceship['Active Duty']; // Returns true
spaceship['Fuel Type']; // Returns 'Turbo Fuel'
spaceship['numCrew']; // Returns 5
ORlet propName = 'Active Duty';let isActive = spaceship[propName]console.log(spaceship[propName])

Property Assignment

Objects are mutable, i.e they can be updated after we create them.

  • The property is replaced with a new value if it already exists on the object.
  • A new property is added, if no property with that name exists.
const spaceship = {type: 'shuttle'};spaceship = {type: 'alien'}; // TypeError: Assignment to constant variable.spaceship.type = 'alien'; // Changes the value of the type property
spaceship.speed = 'Mach 5'; // Creates a new key of 'speed' with a value of 'Mach 5'
const spaceship = {
homePlanet: 'Earth',
mission: 'Explore the universe'
};

delete spaceship.mission; // Removes the mission property

Methods

A function inside an object is called a method. A property is what an object has, while a method is what an object does.

For example console is a global javascript object and .log() is a method on that object. Math is also a global javascript object and .floor() is a method on it.

Old Way

The key serves as our method’s name, while the value is an anonymous function expression.

const alienShip = {
invade: function () {
console.log('Hello! We have come to dominate your planet. Instead of Earth, it shall be called New Xaculon.')
}
};

New Way

With the new syntax introduced in ES6, the colon and function keyword can be omitted.

const alienShip = {
invade () {
console.log('Hello! We have come to dominate your planet. Instead of Earth, it shall be called New Xaculon.')
}
};
alienShip.invade(); // Invoking Object Methods

Nested Objects

In application code, objects are often nested — an object may have another object as a property which in turn can have a property that’s an array of even more objects!

A nested spaceship object

spaceship.nanoelectronics['back-up'].battery; // Returns 'Lithium'
  • First spaceship.nanoelectronics expression is evaluated, which results in an object containing the back-up and computer objects.
  • The back-up object is accessed by appending ['back-up'].
  • The back-up object has a battery property, accessed with .battery which returned the value stored there: 'Lithium'

Pass By Reference

Objects are passed by reference which means when a variable assigned to an object is passed to a function as an argument, the computer interprets the parameter name as pointing to space in the memory that holds the object.

If the function changes the object properties, it is mutating the object permanently (even if the object is assigned to a constvariable).

const spaceship = {
homePlanet : 'Earth',
color : 'silver'
};

let paintIt = obj => {
obj.color = 'glorious gold'
};

paintIt(spaceship);

spaceship.color // Returns 'glorious gold'

The function paintIt() permanently changed the color of our spaceship object. Although re-assignment of spaceship variable does not work in the same way.

  • When spaceship is passed into that function, obj became a reference to the memory location of the spaceship object, but not to the spaceship variable. This is because the obj parameter of the tryReassignment() function is a variable in its own right. The body of tryReassignment() has no knowledge of the spaceship variable at all!
  • When we did the reassignment in the body of tryReassignment(), the obj variable came to refer to the memory location of the object {'identified' : false, 'transport type' : 'flying'}, while the spaceship variable was completely unchanged from its earlier value.

Looping Through Objects

Loops are programming tools that repeat a block of code until a condition is met.

The objects in JavaScript are iterated with the for...in syntax :)

for...in iterates through each element of the spaceship.crew object. In each iteration, the variable crewMemb is set to one of spaceship.crew's keys, and logs crew member’s name and degree.

Notes at a glance

  • Objects store collections of key-value pairs.
  • Each key-value pair is a property — when a property is a function it is known as a method.
  • An object literal is composed of comma-separated key-value pairs surrounded by curly braces.
  • To access, add or edit a property within an object, use dot notation or bracket notation.
  • To add methods to object literals use key-value syntax with anonymous function expressions as values or use the new ES6 method syntax.
  • To navigate complex, nested objects, use chaining operators.
  • Objects are mutable — their properties can be changed even when declared with const.
  • Objects are passed by reference — when changes to an object passed into a function are made, the changes are permanent.
  • To iterate through objects use the For...in syntax.

That is all in Objects today :D

If you fancy following my 100Days Journey, please feel free to stop by 😍

--

--

Henna Singh

Technical Speaker and an aspiring writer with avid addiction to gadgets, meet-up groups, and paper crafts. Currently pursuing Full Stack Bootcamp from Nucamp