Javascript Engineering: The Science Behind

Javascript and Working With Objects

JavaScript Concepts Every Programmer Should Know

Eldar Jahijagic
Level Up Coding
Published in
4 min readMay 29, 2022

--

Photo by Chuttersnap

In addition to my previous two articles on Javascript, I’d like to have a thought on objects and working with them, which is something that developers not only in Javascript but in most languages have to deal with.

Objects

Javascript revolves around a simple object-based paradigm. And we all know about objects and classes, we’ve been working with these for our entire careers probably.

An object is a set of properties, and a property is an attribute of that object. It's very comparable to us humans. We have our attributes, whether that may be our first name, last name, date of birth, or height and weight.

Objects and object-oriented programming are actually inspired by objects in real life.

Following samples are a how-to for working with objects, from simple to more advanced cases.

Ways How to Instantiate Objects

The usual way for instantiating objects is the following

# Create new object
const site = {
name: "Medium",
domain: "medium.com",
type: "Writing Platform"
}

But the above is an object initializer, a comma-delimited list of properties enclosed in curly braces {}, and is also the shorter syntax. A more strict way would be the following.

# Create new object
const site = new Object();
site.name = "Medium";
site.domain = "medium.com";
site.type = "Writing Platform";

For setting the properties themselves, you can make use of that property’s key name, or assign it using the brackets []

site['name'] = "Medium";

The benefit of using this approach is that you can set property values using variables.

const propertyName = "name";
const propertyValue = "Medium";
site[propertyName] = propertyValue;

This might be very useful to know and keep in mind when we are working with collections, mapping lists, objects, types, etc.

Classes

Working with objects doesn’t go without working with classes.

You most probably know how classes work, so in short — it’s a template for objects, defining what properties and functions an instance ie. an object will have.

# Classes
class Website {
constructor(name, domain, type){
this.name = name;
this.domain = domain;
this.type = type;
}
// Getter
get url() {
return `https://www.${this.domain}`;
}
// Method
sayHello() {
return `Hello from ${this.name}!`;
}
}
const medium = new Website("Medium",
"medium.com",
"Writing Platform");
const url = medium.url;
const greeting = medium.sayHello();

In the above example, there are three fields defined within the constructor itself. This is the same as defining fields on their own beforehand.

An interesting thing is however the use of getters which is defined as a get function. It’s not invokable like regular functions but behaves like a property.

Fields

Fields or properties can actually be declared before the constructor.

# Fields and Private Fields
class Website {
name;
domain;
#type;

constructor(name, domain, type){
this.name = name;
this.domain = domain;
this.#type = type;
}
}
const medium = new Website("Medium",
"medium.com",
"Writing Platform");

Note how the # symbol can be used to declare private fields. This field won’t be publicly accessible outside the class.

Generators and Yielding Results

Generators and the keyword yield is something relatively new in Javascript. The yield keywords let us aggregate and yield results from within a loop — something that isn’t that common in other languages but is present in C# for quite a long time.

# Generator and Yielding results
class Website {
constructor(tabs) {
this.tabs = tabs;
}
*getTabs() {
for(const tab of this.tabs){
yield tab;
}
}

const medium = new Website(["Home",
"Recent","About Us",
"Register"]);
const generator = medium.getTabs();
const tabs = [...generator];

In order to get the values from a generator, we actually need to spread it, as the function itself is returning the type, not the values.

Extending Classes

Classes can also be extended in Javascript.

# Extending Classes
class BaseWebsite {
constructor(name, domain, type){
this.name = name;
this.domain = domain;
this.type = type;
}

sayHello() {
return "Hello!";
}
}
class HttpsWebsite extends BaseWebsite {
constructor(name, domain, type){
super(name, domain, type);
this.scheme = 'https';
}

sayHello() {
let superHello = super.sayHello();
return `${superHello} from ${this.name}`;
}
}
const medium = new HttpsWebsite("Medium",
"medium.com",
"Writing Platform");

const hello = medium.sayHello();

Making use of the extend and super keywords, we are able to extend the properties and methods of an existing class.

Base Class Method-Calls

In the aforementioned example, note how we can also declare the base function sayHello, override it, but still make use of it with the super keyword. The same is done within the constructor as well.

Mix-ins

Multiple inheritance is not possible in Javascript, ie. classes can only extend up to one superclass. Inheritance itself occurs during runtime, Javascript searches the prototype chain of the object, in order to find its declared properties and values.

However, we can leverage and use Mix-ins in order to accomplish this. Consider the following example

# Mixins
let WalkMixin = superclass => class extends superclass {
walk() {
return "I'm walking!";
}
};
let FlyMixin = superclass => class extends superclass {
fly() {
return "I'm flying!";
}
};
class BaseClass {}
class SampleClass extends WalkMixin(FlyMixin(BaseClass)) {};
const sample = new SampleClass();
console.log(sample.walk());
console.log(sample.fly());

If you inspect the instance sample you’ll notice that its prototype chain contains both the methods defined in the above mix-ins.

Note that this isn’t a Javascript feature, but more of a workaround.

I hope you found this article useful and enjoyable. It’s part of a series, on Javascript concepts that I recently started writing, so tune in! If you like the content, hit follow and join me on the journey of researching and writing more about the science and engineering behind Javascript.

Thank you for reading! 🎉

--

--

MSc. Telecommunications. BSc. Computer Science. Principal Software Engineer. Product Manager. Top writer in Software, Technology and Science🔬 Hit FOLLOW ↩