JavaScript Objects Cheat Sheet

Mon Aug 28 2023

JavaScript Objects Cheat Sheet

Let's revise on the objects in JavaScript.

Objects

An object is a group of properties (what the object has) and methods (what the object can do). We can use "." to access object's methods and properties.

const house = {
____address: "7 Bond Street",
____builtIn: "1950",
____type: "terraced",

____sell : function() {
____console.log("This house is for sale.")
____},

____live : function() {
____console.log("Someone lives in this house.")
____},

____renovate : function() {
____console.log("This house is being renovated.")
____}
}

console.log(house.address) //7 Bond Street
house.live()//Someone lives in this house.

"This" keyword

"This" refrences the object based on its immediate context.

const house = {
____address: "7 Bond Street",
____builtIn: "1950",
____type: "terraced",

____sell : function() {
____console.log(`The house at ${this.address} is for sale.`)
____},

____live : function() {
____console.log(`Someone lives in house at ${this.address}.`)
____},

____renovate : function() {
____console.log(`The house at ${this.address} is being renovated.`)
____}
}

house.renovate()//The house at Bond Street is being renovated.
house.live()//Someone lives in house at Bond Street.

If we use "this" outside of an object we reference the "Window" object.

console.log(this)//Window {window: Window, self: Window, document: document, name: '', location: Location, …}

Classes

Classes are a template for creating objects. They encapsulate data with code to work on that data.

class Rectangle {
____height = 2;
____width = 7;

____areaCalc() {
____return this.height * this.width
____}
}

Let's create more rectangles.

const rectangle1 = new Rectangle();
const rectangle2 = new Rectangle();

We've created two identical rectangles.

console.log(rectangle1.areaCalc())//14
console.log(rectangle2.areaCalc())//14

Classes: constructor function

The constructor method is a special method within a class for creating and initializing an object instance of that class. It accepts arguments and assigns properties.

class Book {
____constructor(title, author, year) {
________this.title = title;
________this.author = author;
________this.year = year;
____}
____published() {
________console.log(`"${this.title}" by ${this.author} was published in ${this.year}.`)
________}
}

const book1 = new Book("It", "Stephen King", 1986);

book1.published()//"It" by Stephen King was published in 1986.

Classes: "static" keyword

Used with variables, methods, blocks and nested classes to share the same variable or method of a class. It is the same for every instance of a class.

class Game {

____static numberOfGames = 0;

____ constructor(name) {
________ this.name = name;
________ Game.numberOfGames +=1;
____ }
}

const game1 = new Game("Snake");
const game2 = new Game("Bowling");
const game3 = new Game("Piggy in the Middle");

console.log(Game.numberOfGames)//3

Inheritance and "extends" keyword

The "extends" keyword is used in class declarations or class expressions to create a class that is a child of another class. It indicates that a class is inherited from another class.

Classes Book, Magazine and Comic have all function read in common.

class ReadingMaterial {
____ read() {
________ console.log(`I am reading "${this.title}".`)
____ }
}

class Book extends ReadingMaterial {
____ title = "It"
}
class Magazine extends ReadingMaterial {
____ title = "Glamour"
}
class Comic extends ReadingMaterial {
____ title = "Manga"
}

const book = new Book()

book.read()//I am reading "It".

Classes: "super" keyword

The "super" keyword is used to call parent class' variables and methods (constructors only).

class Animal {

____ constructor(name, age) {
________ this.name = name;
________ this.age = age;
____ }
}

class Dog extends Animal {

____ constructor(name, age, runningSpeed) {

________ super(name, age)
________ this.runningSpeed = runningSpeed;
____ }
}

class Cat extends Animal {

____ constructor(name, age, runningSpeed) {

________ super(name, age)
________ this.runningSpeed = runningSpeed;
____ }
}

class Bird extends Animal {

____ constructor(name, age, flyingSpeed) {

________ super(name, age)
________ this.flyingSpeed = flyingSpeed;
____ }
}

const dog = new Dog("Rocky", 5, "40km/h")
const cat = new Cat("Daisy", 7, "45km/h")
const bird = new Bird("Pongo", 2, "40km/h")

console.log(dog.name)//Rocky
console.log(bird.age)//2

Getters and Setters

The "get" method returns the variable value and makes it a "read-only" property, which should not be changed. It provides additional security and lets us set up some additional logic. The "set" method sets the value.

class Car {
____ constructor (power){
________ this._gas = 25;
________ this._power = power;
____ }
____ get power() {
________ return `${this._power}hp`
____ }
____ get gas() {
________ return `There's ${this._gas}L of gas in the tank. It's ${this._gas / 50 * 100}% full.`
____ }

We can set the maximum and minimum value of gas.

____set gas(value) {

____ if (value > 50) {
________ value = 50;
____ } else if (value < 0) {
________value = 0;
____ }
____ this._gas = value;
____ }
}

let car = new Car(400);

console.log(car.power)//400hp

If we change the value of gas to a number greater than 50, console will print the maximum value that has been set, which is 50. If the value of gas is below 0, console will print the minimum set valu, which is 0.

car.gas = -90;

console.log(car.gas)//There's 0L of gas in the tank. It's 0% full.

car.gas = 50;

console.log(car.gas)//There's 50L of gas in the tank. It's 100% full.

Example comes from a Youtube video by Bro Code .

Date()

let date = new Date();

console.log(date)//Mon Aug 28 2023 22:34:56 GMT+0100 (British Summer Time)

date = date.toLocaleDateString();

console.log(date)//28/08/2023

JavaScript stores dates as number of milliseconds since January 01, 1970. 1st of January 1970 00:00:00 UTC is therefore the reference point when we pass an argument inside Date() object.

let date = new Date(0);

console.log(date)//Thu Jan 01 1970 01:00:00 GMT+0100 (Greenwich Mean Time)

let dateToday = new Date(2023, 7, 28, 22, 34, 1, 5); let dateYesterday = new Date('August 27, 2023 22:45:00');

console.log(dateToday)//Sun Aug 28 2023 22:34:01 GMT+0100 (British Summer Time)
console.log(dateYesterday)//Sun Aug 27 2023 22:45:00 GMT+0100 (British Summer Time)

let date = new Date();

let year = date.getFullYear();
let day = date.getDate();
let weekDay = date.getDay();
let month = date.getMonth();
let hour = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
let milliSeconds = date.getMilliseconds();

In getDay() Sunday is 0, Monday is 1, etc.
In getMonth() January is 0, Febryary is 1, etc.

console.log(year)//2023
console.log(day)//28
console.log(weekDay)//1
console.log(month)//7
console.log(hour)//22
console.log(seconds)//25
console.log(milliSeconds)//701

Let's set a specific date.

let date = new Date();

date.setFullYear(2025)
date.setMonth(11)
date.setDate(31)
date.setHours(8)
date.setMinutes(5)
date.setSeconds(0)

console.log(date)//Wed Dec 31 2025 08:05:00 GMT+0000 (Greenwich Mean Time)

Let's display your current date and time.

let date = new Date();

document.getElementById('currentTime').innerHTML = todaysDate(date) + currentTime(date);

function todaysDate(date) {
___let year = date.getFullYear();
___let day = date.getDate();
___let month = date.getMonth() + 1;

___return `Today is ${day}/${month}/${year}`
}

function currentTime(date) {
___let hour = date.getHours();
___let minutes = date.getMinutes();

___return ` and the time is ${hour}:${minutes}.`
}

Illustration for the JavaScript Objects Cheat Sheet
Web illustrations by Storyset

Comments (0)


Be the first to leave a comment