Loops and Array of Objects in ECMAScript

Create new Javascript file named product.js. This file contains code demo as below:

class Product {

    constructor(id, name, price, quantity) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.quantity = quantity;
    }

    total() {
        return this.price * this.quantity;
    }

    toString() {
        return 'Id: ' + this.id + '\nName: ' + this.name + '\nPrice: ' + this.price + '\nQuantity: ' + this.quantity;
    }

}

module.exports = Product;




Create new Javascript file named index.js. This file contains code demo as below:

let Product = require('./product');

let product1 = new Product('p01', 'name 1', 5, 2);
let product2 = new Product('p02', 'name 2', 11, 6);
let product3 = new Product('p03', 'name 3', 21, 5);

let products = [product1, product2, product3];

console.log('Product List');
for (const product of products) {
    console.log(product.toString());
    console.log('Total: ' + product.total());
    console.log('===========================');
}

console.log('Product List');
for (const index in products) {
    console.log(products[index].toString());
    console.log('Total: ' + products[index].total());
    console.log('===========================');
}




Use node index.js statement run code demo

Product List
Id: p01
Name: name 1
Price: 5
Quantity: 2
Total: 10
===========================
Id: p02
Name: name 2
Price: 11
Quantity: 6
Total: 66
===========================
Id: p03
Name: name 3
Price: 21
Quantity: 5
Total: 105
===========================

Product List
Id: p01
Name: name 1
Price: 5
Quantity: 2
Total: 10
===========================
Id: p02
Name: name 2
Price: 11
Quantity: 6
Total: 66
===========================
Id: p03
Name: name 3
Price: 21
Quantity: 5
Total: 105
===========================