JavaScript Essentials: Objects

CodeDraken
codeburst
Published in
9 min readOct 9, 2018

--

Essentials is a series that covers the most used and important methods for X topic along with some other fundamentals. In this post we cover Objects.

Table of Contents

JavaScript Essentials: Objects
— — Prerequisites
Objects the Basics
— — Basic Object Creation
— — Object Definitions
— — What is This?
— — What does ‘this’ point to?
— — Prototypes
— — Class Syntax
Important Guidelines and Fundamentals
Common Methods
— — Getters and Setters
— — Key-Pair Array into Object ( experimental )
— — Make an Object Immutable
— — Shallow Copy an Object
— — Deep Copy an Object
— — Convert Object to JSON
— — Loop an Object
— — Check if a Key Exists in an Object
— — Dynamic Keys
— — Binding ‘this’ on Classes
References and Links to Learn More

Prerequisites

It’s recommended that you know about types. Other JS topics would be helpful too but are not required.

Note: This is a long post covering both the fundamentals of objects and common methods. You can skip to the methods by clicking here.

You can access all the code shown here for copying/experimenting using this gist.

Objects the Basics

An object is a collection of related data and/or functionality (which usually consists of several variables and functions — which are called properties and methods when they are inside objects.)
MDN

Objects are just like objects in real life. They have properties, sometimes can do things and often extend another object.

For example, let’s imagine a dog.

dog gif from giphy

How would you describe a dog? What properties does it have? What can it do? Dogs evolved from wolves — so we could say they extend the properties of a wolf. What can a wolf do? What properties does a wolf have?

pseudo dog/wolf example

In this example, I’ve modeled a very simple wolf and dog. A wolf has a fur color, size, age, etc and it can run, eat and sleep. A dog is a type of wolf with some extra properties and actions.

A dog has everything a wolf does and gets a special name i.e “poodle”. It can do more actions like cuddle and pee on fire hydrants. You could go even deeper and extend what a dog does for a specific type of dog. i.e rescue dog extends dog and has an additional action “rescue”.

Basic Object Creation

There are quite a few ways to create objects. The simplest way is using an object literal — which is literally writing out the contents of an object. ( don’t worry we’ll cover more advanced Object creation later! )

Jeff the object literal

Note: The greet function syntax above is an ES6 feature. You could alternatively define a key like normal and give it a value of a function — either a reference to a function or inline a function. i.e greet: function() {} or greet: greetFunc etc.

Object Definitions

Property/Key — these are basically variables located in an object. They have a name which you use to access it and a value. i.e name: 'Jeff'

Method — methods are functions that live on an object and often make use of the object’s properties.

What is This?

I’m literally referring to this in JavaScript. This is perhaps the part of JS that confuses people the most.

This — a variable created by JavaScript when an execution context is created ( i.e running a function ) that points to an object. What object it points to depends on how the function is called.

Execution Context — when a function is called an execution context is created. This context holds function variables, this and a reference to the outer environment.

execution context diagram

What does ‘this’ point to?

We understand this is a value given to us by JavaScript when a function is called. What determines the object this points to? That depends on how the function is called.

Rules in order of precedence:

  1. Using an Arrow Function? (lexical) this comes from the outer lexical scope / containing function. If there is no containing function then it’s global, otherwise perform these checks again on the outer function.

2. Using the New Operator? (constructor functions) — if the function is called with the new keyword then this is set to the newly created object.

new keyword binding

3. Did you set this yourself? (explicit) — If you used .call .apply .bind or an argument to set this in a supported function then this is whatever value you set it to using explicit binding unless you used null or undefined which in that case it would point to the global object.

explicit binding

4. Was the function called as a method? (implicit)this is the preceding object. For obj.method obj is the value for this using implicit binding. Be aware that functions nested inside the method may not have the same this variable.

implicit binding

Note: The function doesn’t have to be inside the object. It can be a reference to a function i.e greet: greetFunc What matters is the function call is preceded by an object reference.

5. None of the above? (default) — by default this will refer to the global object. If strict mode is enabled it will be undefined.

default this value

If you’re interested in learning more about this then here are some reference links and my tutorial on it.

Prototypes

Prototypes is a way to add methods to your objects while only having one method exist in memory.

Inheritance — when an object shares the methods and properties of another object.

Classical Inheritance — this is what you find in languages like C#, Java, etc

Prototypal Inheritance — when a property can’t be found on an object it searches a chain like structure called the prototype. If it’s not found on the next prototype object it will look at the prototype of that prototype.

For example, when you have an Array and you use a method like .sort that method does not exist on the array itself — it exists on the prototype.

proto diagram

Here’s a simple example in code.

proto chain

Here’s a comparison of a traditional constructor vs prototypes.

object prototypes vs traditional methods

Class Syntax

Classes are popular in other Object Oriented programming languages and JavaScript decided to copy that. Classes in JS are not the same, they don’t introduce a new object model — they’re just syntactic sugar for prototypes.

Let’s define some parts of a Class.

  • Class Definition — how we define a class, can be a top level class or extend another class.
  • Constructor — method for initializing values on the class instance
  • Super — used to pass arguments to the parent class and use methods from the parent
  • Static Methods — methods that only work on the class constructor, not on instances
  • Instance Methods — methods with this set to the specific instance of a class

Here’s what it looks like in code, using the dog example from earlier with some changes.

ES6 Classes Syntax, extend, super, constructor, static

Important Guidelines and Fundamentals

Important guidelines to keep in mind.

  • Everything that’s not a primitive is an Object. ( learn about types )
  • There are many ways to create objects
  • Objects are ways to describe objects or data with properties and methods
  • this is determined at runtime
  • Classes are just syntactic sugar

Common Methods

Below are code blocks, some with a scenario/task described in a comment up top then some code below and others just showcasing methods.

For the most part, you’ll define your own methods on objects, but there are a few static methods on Object that are useful. I’ll cover those and techniques for doing certain things such as looping over an object.

Getters and Setters

We can use getters and setters to control access to our Object.

getter setter

Key-Pair Array into Object ( experimental )

Currently a stage-3 proposal.

Object.fromEntries, Object.entries

Make an Object Immutable

We can use Object.freeze() to make an Object immutable.

Qualities of a frozen object:

  • New properties cannot be added
  • Existing properties cannot be removed
  • Values of properties cannot be changed
  • The prototype cannot be changed
Object.freeze

Shallow Copy an Object

Shallow copying an Object means we’re copying values, but the references are the same. i.e objects point to the same object.

shallow copy, Object.assign, spread operator

Deep Copy an Object

Deep copying is making an entire copy of an Object with no shared references.

Convert Object to JSON

JSON.stringify

Loop an Object

Object.entries, for in, Object.values, Object.keys

Check if a Key Exists in an Object

key in object, hasOwnProperty

Dynamic Keys

Binding ‘this’ on Classes

More to be added

References and Links to Learn More

Read more JavaScript Essentials:

Thanks for reading! Leave any feedback or questions in the comments below.

--

--