What Objects and Classes Are In JavaScript

Photo by Kieran Wood on Unsplash

What Objects and Classes Are In JavaScript

Understanding JavaScript objects and classes, and how to use them

JavaScript is versatile as a programming language, and has so many use cases, especially for web development. Its ability to work with objects and classes, provides a flexible approach to organize and manipulate data. In this short exposition, let us get to see what objects and classes represent in JavaScript.

What are JavaScript Objects

In JavaScript, Objects are considered as collection of keyed-value pairs, which can be used to store various data types. Here, each key is a string, and each of the values can be of different data types. In JavaScript, we can create an object with figure brackets {…} with an optional list of properties. A property is a “key: value” pair, where key is a string (also called a “property name”), and value can be anything. For example;

let person = new Object(); //"object constructor" syntax
let person = {} // "object literal" syntax

Here new object() is the Object constructor syntax. It calls the object Constructor to create a new empty object named person. It us usually when you need to create dynamic objects or dealing with inheritance.

We can proceed to add properties into the {...} as key value pairs

let person = { //an object
    name:"Adai", // key = name, value = Adai
    state:"Calabar", //key = state, value = calabar
    age:18 // key = age, value = 18
}

In the person function above, we have three properties, and corresponding values of two data types, string and numeric data types. We can proceed to add boolean functions to the object like this;

let person = { //an object
    name:"Adai", // key = name, value = Adai
    state:"Calabar", //key = state, value = calabar
    age: 18, // key = age, value = 18
    isAdult: function() {
      return this.age >= 18; // Returns true if age is 18 or above, and false if less than 18   
    },
}
console.log(person.isAdult());

In the addition above, we are able to attach a boolean property to the person object. It gives a true or false response based on the age of the person.

What are JavaScript Classes

Creating objects in JavaScript would often involve more traditional constructor functions. By using classes, we are able to create objects with per-defined properties and methods. Classes are said to be the modern approach of creating objects in object-oriented programming.

The "class" syntax

In JavaScript, you define a class using the class keyword. Here is an example of a basic structure for defining a class in JavaScript;

class Person {
    constructor() { ... }
    method1() { ... }
    method2() { ... }
    ...
}

Furthermore, here is an example of how class works;

class Person {
    constructor(name, state, age) {
        this.name = name;
        this.state = state;
        this.age = age;
    }

    sayHello() {
        console.log(`Hello, my name is ${this.name}, I am from ${this.state}, and I'm ${this.age} years old.`);
    }

    celebrateBirthday() {
        this.age++;
        console.log(`Happy birthday! I'm now ${this.age} years old.`);
    }
}

// Creates a new instance of the Person class
let person = new Person("Adai", "Calabar", 25);

// Calling methods on the person object
person.sayHello(); // Hello, my name is Adai, I am from Calabar, and I'm 25 years old.
person.celebrateBirthday(); // Happy birthday! I'm now 26 years old.

In objects, the constructor method is automatically called by new. So, in the code sample above for example, when the new Person is called, the constructor, a new object is created, the constructor uses the given arguments, and assign the keys and values to the person.

Finally, we have seen how objects and classes work in JavaScript, their use cases, and goals. A thorough understanding of objects and classes, would aid you in to build more scalable and maintainable JavaScript applications. Practice makes perfect, so don't hesitate to try put different examples. You can leverage on this final example/assessment for more understanding. In the code block below, try to fill in the empty spaces in your code, editor and find the right answer for each line. Feel free to test the code in your local code editor.

class GroceryStore {
    constructor(storeName) {
        this.storeName = storeName;
        this.inventory = ____;
    }

    // add items to inventory
    addItem(itemName, quantity, price) {
        if (!this.inventory[itemName]) {
            this.inventory[itemName] = { quantity: 0, price: 0 };
        }
        this.inventory[itemName].quantity += quantity;
        this.inventory[itemName].price = price;
        console.log(`${quantity} ${___} added to ${this.storeName}'s inventory.`);
    }

    // Sell items
    sellItem(itemName, quantity) {
        if (!this.inventory[itemName] || this.inventory[itemName].quantity < quantity) {
            console.log(`Sorry, ${this.____} does not have enough ${itemName}(s) in stock.`);
            return;
        }
        this.inventory[itemName].quantity -= quantity;
        const totalPrice = quantity * this.inventory[itemName].price;
        console.log(`Sold ${quantity} ${itemName} for $${totalPrice}.`);
    }

    // Check inventory for Itemd
    checkInventory(itemName) {
        if (this.inventory[itemName]) {
            console.log(`${this.storeName}'s inventory: ${this.inventory[itemName].quantity} ${itemName} available.`);
        } else {
            console.log(`${this.storeName} does not have ${itemName} in stock.`);
        }
    }
}

// Create a grocery store using new
let myGroceryStore = new GroceryStore("Adai's Grocery Store");

// Add items to inventory
myGroceryStore.addItem("VolleyBall", 50, 15);
myGroceryStore.addItem("Bananas", 30, 75);

// Check inventory
myGroceryStore.checkInventory("___"); 
myGroceryStore.checkInventory("Oranges"); 

// Sell items
myGroceryStore.sellItem("___", 10); 
myGroceryStore.sellItem("Bananas", 40);