6 Ways to Create Objects in Javascript — Intro to Object & Prototype

What are Objects in Javascript?

Primitives and Objects?

// primitives
typeof undefined // undefined
typeof true // boolean
typeof false // boolean
typeof 12 // number
typeof '' // string
typeof 10n // bigint
typeof Symbol() // symbol
// special primitive
typeof (null) // object
// weird globals
typeof NaN // number
typeof Number.NaN // number
typeof Infinity // number
// object derived
typeof (new Array()) // object
typeof (new String()) // object
typeof (new Number()) // object
typeof (new Map()) // object
typeof (new Set()) // object
typeof (new WeakSet()) // object
typeof (new WeakMap()) // object
typeof (new Object()) // object
typeof (new Date()) // object
typeof (new Boolean()) // object
// special shorthand for functions only
// but functions are still object derived

typeof (new Function()) // function
const str1 = 'some string';
const str2 = new String('some string');
typeof str1 // string
str1 instanceof String // false
typeof str2 // object
str2 instanceof String // true

Object initializer

const person = {
firstName: 'John',
lastName: 'Doe',
get name() {
return `${this.firstName} ${this.lastName}`
},
age: 30,
greet() {
console.log(`Hi! My name is ${this.name}`)
}
}
person.hasOwnProperty('name'); // true
person.hasOwnProperty('sample'); // false

Object constructor

const person = new Object();person.firstName = 'John';
person.lastName = 'Doe';
Object.defineProperty(person, 'name', {
get() {
return `${this.firstName} ${this.lastName}`
}
})
person.age = 30;
person.greet = function() {
console.log(`Hi! My name is ${this.name}`)
}
new Object(12); // Number
new Object(''); // String
new Object(true); // Boolean
new Object(() => 10); // Function
new Object([]); // Array
new Object(Symbol()); // Symbol
new Object(new Map()); // Map
new Object(new Set()); // Set
new Object({name: 'John Doe'}); // Object
...

Object create method

const person = Object.create(null);person.firstName = 'John';
person.lastName = 'Doe';
Object.defineProperty(person, 'name', {
get() {
return `${this.firstName} ${this.lastName}`
}
})
person.age = 30;
person.greet = function() {
console.log(`Hi! My name is ${this.name}`)
}
person.hasOwnProperty('name'); // TypeError: person.hasOwnProperty is not a method// attach prototype back on
Object.setPrototypeOf(person, Object.prototype)
person.hasOwnProperty('name'); // true
const personChild = Object.create(person, {
age: {
value: 5
},
name: {
get() {
return `${this.firstName} ${this.lastName} Jr.`
}
}
})
personChild.age // 5
personChild.name // "John Doe Jr."
personChild.greet() // "Hi! My name is John Doe Jr."
// personChild object inherits from person
{
age: 5
name: "John Doe Jr."
__proto__:
age: 30
firstName: "John"
greet: ƒ ()
lastName: "Doe"
name: "John Doe"
}

Factory Function

function createPerson(name, age) {
const person = Object.create(null);
const [firstName, ...lastNameArray] = name.split(/\s+/);
person.firstName = firstName;
person.lastName = lastNameArray.join(' ');
person.name = name;
person.age = age;
person.greet = function() {
console.log(`Hi! My name is ${this.name}`)
}

return person;
}
const person = createPerson('John Doe', 30);
// HOF
function withDateOfBirth(fn, dob) {
return (name, dob) => {
const age =
(new Date()).getFullYear() -
(new Date(dob)).getFullYear();
const obj = fn(name, age);
obj.dob = dob;

return obj;
}
}
// uses the createPerson factory function
const createPersonWithDOB = withDateOfBirth(createPerson);
const person = createPersonWithDOB('John Doe', '03/02/1990');// Extension
function extendObject(object, extension) {
const objCopy = {...object};
Object.setPrototypeOf(objCopy, extension);
return objCopy;
}
extendObject(person, {
get initials() {
return `${this.firstName[0]} ${this.lastName[0] ?? ''}`
}
})
/*
{
age: 31
dob: "03/02/1990"
firstName: "John"
greet: ƒ ()
lastName: "Doe"
name: "John Doe"
__proto__:
initials: "J D"
get initials: ƒ initials()

__proto__: Object
}
*/

Constructor Function

function Person(name, age) {
const [firstName, ...lastNameArray] = name.split(/\s+/);

this.firstName = firstName;
this.lastName = lastNameArray.join(' ');
this.name = name;
this.age = age;
this.greet = function() {
console.log(`Hi! My name is ${this.name}`)
}
}
const person = new Person('John Doe', 30)
/*
{
age: 30
firstName: "John"
greet: ƒ ()
lastName: "Doe"
name: "John Doe"
__proto__:
constructor: ƒ Person(name, age)
__proto__: Object
}
*/
const Person = (() => {
function Person(name, age) {
const [firstName, ...lastNameArray] = name.split(/\s+/);
this.firstName = firstName;
this.lastName = lastNameArray.join(' ');
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
console.log(`Hi! My name is ${this.name}`)
}

return Person;
})();
const person = new Person('John Doe', 30);
/*
{
age: 30
firstName: "John"
lastName: "Doe"
name: "John Doe"
__proto__:
greet: ƒ ()
constructor: ƒ Person(name, age)
__proto__: Object
}
*/

Class

class Person {
constructor(name, age) {
const [firstName, ...lastNameArray] = name.split(/\s+/);
this.firstName = firstName;
this.lastName = lastNameArray.join(' ');
this.name = name;
this.age = age;
}
greet() {
console.log(`Hi! My name is ${this.name}`)
}
}
const person = new Person('John Doe', 30);
/*
{
age: 30
firstName: "John"
lastName: "Doe"
name: "John Doe"
__proto__:
greet: ƒ ()
constructor: ƒ Person(name, age)
__proto__: Object
}
*/
function Parent(name) {
this.name = name;
this.isParent = true;
}
class Child extends Parent {
constructor(...args) {
super(...args);

this.isParent = false;
}
}
const parent = new Parent('John');
{
isParent: true
name: "John"
__proto__:
constructor: ƒ Parent(name)
__proto__: Object
}
const child = new Child('John Jr.');
{
isParent: false
name: "John Jr."
__proto__: Parent
constructor: class Child
__proto__: Object
}

Conclusion

Blog & YouTube Channel for Web, UI & Software Development - beforesemicolon.comyoutube.com/c/BeforeSemicolon

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store