JavaScript - tutorial - 10 - objects - OOP

revision:


Content

JavaScript objects: variables that can contain many values. creating objects object methods how to display JavaScript objects? different approaches to retrieve an object value JavaScript object accessors Object-oriented programming (OOP) JavaScript object examples


JavaScript objects: variables that can contain many values.

top

JavaScript objects are containers for named values called "properties" or "methods". In JavaScript, almost "everything" is an object:

booleans can be objects (if defined with the "new" keyword),
numbers can be objects (if defined with the "new" keyword),
strings can be objects (if defined with the "new" keyword),
dates are always objects,
maths are always objects,
regular expressions are always objects,
arrays are always objects,
functions are always objects,
objects are always objects.
All JavaScript values, except primitives, are objects.

A primitive value is a value that has no "properties" or "methods". A primitive data type is data that has a primitive value. JavaScript defines 5 types of primitive data types: string, number, boolean, null, undefined. Primitive values are immutable (they are hardcoded and therefore cannot be changed).

Objects are variables

Objects are variables too, but they can contain many values, which are written as "name : value" pairs (name and value separated by a colon). The named values, in JavaScript objects, are called properties. Methods are actions that can be performed on objects.

An object literal is a list of "name:value" pairs ( e.g. age:50 ) inside curly braces ( {} ). A JavaScript object can be created and defined with an object literal in one statement.

Properties can be put into {...} as "key: value" pairs.

A property has a key (also known as “name” or “identifier”) before the colon ":" and a value to the right of it. The "name:values" pairs in JavaScript objects are called "properties".

Examples: object literal









code:
                    <div class="spec">
                        <a id="id1"></a><br><br>     
                        <a id="id2"></a><br><br>
                        <a id="id2a"></a><br><br>
                        <a id="id2b"></a><br><br>
                    </div>
                    <script>
                        var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
                        document.getElementById("id1").innerHTML = person.firstName + " is " + person.age + " years old.";
        
                        let user =  {
                            name: "John",
                            age: 30
                        };
                        let result = (user.name + ", " + user.age);
                        document.getElementById('id2').innerHTML = result;
        
                        var person = {
                            name: "James T. Kirk",
                            birth: 2233,
                            isEgotistical: true,
                            ship: {
                                name: "USS Enterprise",
                                number: "NCC-1701",
                                commissioned: 2245
                            },
                            getInfo: function() {
                                return this.name + " commands the " + this.ship.name;
                            }
                        };
                        document.getElementById('id2a').innerHTML = (person.name + " commands the " + person.ship.name); 
                        
                        let user1 = {
                            name: "John",
                            age: 30,
                            "likes birds": true  // multiword property name must be quoted
                        };
                        document.getElementById('id2b').innerHTML = (user1.name + ", " + user1.age );
                    </script>
                

Object properties can be accessed in two ways: 1/ objectName.propertyName or 2/ objectName["propertyName"].

Examples: access objet properties





code:e
                    <div class="spec">
                        <a id="id3"></a><br><br>
                        <a id="id3a"></a><br><br>
                    </div>
                    <script>
                        var person = {
                            firstName: "John",
                            lastName : "Doe",
                            id     :  5566
                        };
                        document.getElementById("id3").innerHTML = person.firstName + " " + person.lastName;
                        document.getElementById("id3a").innerHTML = person["firstName"] + " " + person["lastName"];
                    </script>
                

Objects can also have methods, i.e. actions that can be performed on objects. Methods are stored in properties as function definitions. A method is a function definition stored as a property value.

An object method is accessed with the following syntax : objectName.methodName(). If you access a method without the () parentheses, it will return the function definition.

Examples: object methods







code:
                    <div class="spec">
                        <a id="id4"></a><br><br>
                        <a id="id4a"></a><br><br>
                        <a id="id4b"></a><br><br>
                    </div>
                    <script>
                        var person = {
                            firstName: "John",
                            lastName : "Doe",
                            age: 30,
                            id     : 5566,
                            fullName : function() {
                                return this.firstName + " " + this.lastName;
                            }
                        };
                        document.getElementById("id4").innerHTML = person.fullName();
                        document.getElementById("id4a").innerHTML = person.fullName() +"<br>";
                        document.getElementById("id4b").innerHTML = person.fullName;
                    
                    </script>
                

When a JavaScript variable is declared with the keyword "new", the variable is created as an object.

the "this" word

In a function definition, "this" refers to the "owner" of the function. In other words, this.firstName means the firstName property of this object.

Examples: this

code:
                    <div class="spec">
                        <a id="id5"></a>
                    </div>
                    <script>
                        var person = {
                            firstName: "John",
                            lastName : "Doe",
                            id     : 5566,
                            fullName : function() {
                                return this.firstName + " " + this.lastName;
                            }
                        };
                        document.getElementById("id5").innerHTML = person.fullName();
                    </script>
                

In this example, this represents the person object, because the person object "owns" the fullName method.


creating objects

top

In JavaScript, objects can be created in the following ways:

1/ using the object literal syntax

Examples: use object literal

code:
                    <p class="spec" id="id6"></p>
                    <script>
                        const obj = {
                            name : "louis"
                        }
                        var x = Object.values(obj);
                        console.log(obj); // {name: 'louis'} 
                        document.getElementById("id6").innerHTML = "name is : " + x;
                    </script>
                

2/ using a constructor function

Examples: use constructor function

code:
                    <p class="spec" id="id7"></p>
                    <script>
                        function myProfile(name){
                            this.name = name;
                        }
                        const obj_a = new myProfile("louis");
                        var y = Object.values(obj_a);
                        console.log(obj_a); // myProfile {name: 'louis'}   
                        document.getElementById("id7").innerHTML = "name is : " + y;
                    </script>
                

3/ using a factory function

Examples: use factory function

code:
                    <p class="spec" id="id8"></p>
                    <script>
                        function myProfile(name){
                                return{
                                    name : name
                                }
                            }
                        const obj_b = myProfile("louis");
                        var z = Object.values(obj_b);
                        console.log(obj_b);// {name: 'louis'}
                        document.getElementById("id8").innerHTML =  "name is : " + z;
                    </script>
                

object methods

top

An object can be converted into an array with three methods:

Object.keys() : helps to retrieve all keys belonging to an object as an "array".

It creates an array that contains the properties of an object.

Examples: Object.keys()

code:
                    <p class="spec" id="id9"></p>
                    <script>
                        const fruits = { apple: 28, orange: 17, pear: 54 };
                        const keys = Object.keys(fruits);
                        console.log(keys); // ["apple", "orange", "pear"]  
                        document.getElementById("id9").innerHTML = "fruits : " + keys;  
                    </script>
                

Object.values() : helps to retrieve all values belonging to an object as an "array".

It creates an array that contains the values of every property in an object.

Examples: Object.values()

code:
                    <p class="spec" id="id10"></p>
                    <script>
                        const fruits_a = { apple: 28, orange: 17, pear: 54 };
                        const values = Object.values(fruits_a);
                        console.log(values); // [28, 17, 54]
                        document.getElementById("id10").innerHTML = "Fruits prices : " + values;  
                    </script>
                

Use Object.values() method to collect all the values of an object into an array. The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a "for...in loop". The only difference is that a "for...in" loop enumerates properties in the prototype chain as well.

base

                    const info = { name: "Matt", country: "Finland", age: 35 };
                    const person = {
                        firstName: 'John',
                        lastName: 'Doe',
                        age: 25
                    };
                

longhand

                        let data = [];
                        for (let key in info) {
                            data.push(info[key]);
                        }
                    

shorthand

                    const data = Object.values(info);

                    var check = ['x', 'y', 'z'];
                    console.log(Object.values(check));

                    const profile = Object.values(person);
                    console.log(profile);
                

Object.entries() : creates an array of arrays. Each inner array has two items: the first item is the property; the second item is the value.

Examples: Object.entries()

code:
                    <p class="spec" id="id11"></p>
                    <script>
                            const fruits_b = { apple: 28, orange: 17, pear: 54 };
                            const entries = Object.entries(fruits_b);
                            console.log(entries); // [["apple", 28], ["orange", 17], ["pear", 54]]
                            document.getElementById("id11").innerHTML =  "fruits + prices : " + entries;  
                    </script>
                

This feature was introduced in ES8 that allows you to convert a literal object into a key/value pair array.

longhand

                    
                

shorthand

                    const credits = { producer: 'John', director: 'Jane', assistant: 'Peter' };
                    const arr = Object.entries(credits);
                    console.log(arr);
                    /** Output:
                    [ [ 'producer', 'John' ],
                      [ 'director', 'Jane' ],
                      [ 'assistant', 'Peter' ]
                    ]
                    **/                    

                

how to display JavaScript objects?

top

Displaying a JavaScript object will output [object Object]. Some common solutions to display JavaScript objects are:

1 - displaying the object properties by name : the properties of an object can be displayed as a string

2 - displaying the object properties in a loop : the properties of an object can be collected in a loop.

3 - displaying the object using Object.values() : any JavaScript object can be converted to an array using Object.values().

4 - displaying the object using JSON.stringify() : any JavaScript object can be stringified (converted to a string) with the JavaScript function JSON.stringify().


Examples: display JS objects









code:
                    <div class="spec">
                        <a id="id12"></a><br><br>
                        <a id="id12a"></a><br><br>
                        <a id="id12b"></a><br><br>
                        <a id="id12c"></a><br><br>
                    </div>
                    <script>
                        // var person = {name:"John", age:50, city:"New York"};
                        var x, txt = "";
                        var person = {name:"John", age:50, city:"New York"};
                        for (x in person) {
                            txt += person[x] + ",  ";
                        };
                        var myArray = Object.values(person);
                        var myString = JSON.stringify(person);
        
                        document.getElementById("id12").innerHTML = "1 - " + person.name + ", " + person.age + ", " + person.city;
                        document.getElementById("id12a").innerHTML = "2 - " + txt;
                        document.getElementById("id12b").innerHTML = "3 - " + myArray;
                        document.getElementById("id12c").innerHTML = "4 - " + myString;
                    </script>
                

different approaches to retrieve an object value

top

approach 1: using a number as the index

Using the Object.keys() method: retrieve all keys belonging to an Object, loop through the keys using a "while-loop", and then with a particular key as a numeric index, retrieve the value that is assigned to it.

approach 2: using a key as the index

Using a for-each loop : loop through the object's keys, which are returned as an "array"; then with a particular key as the element at hand, access the value assigned to it.

approach 3: using for...in loop

Using a for. . . loop : loop through the object's key which are returned as an "array"; then with a particular key as the element at hand, access the value assigned to it.

Examples: retrieve object values

1 - Object.keys() method

2 - forEach loop

3 - for . . . loop

code:
                    <div>
                        <p class="spec">1 - Object.keys() method</p>
                        <p class="spec" id="id13"></p>
                        <p class="spec">2 - forEach loop</p>
                        <p class="spec" id="id13a"></p>
                        <p class="spec">3 - for . . . loop</p>
                        <p class="spec" id="id13b"></p>
                    </div>
                    <script>
                        const profile = {
                            name : "Alexander",
                            email: "me@you.com",
                            gender : "male"
                        }
        
                        let i = 0;
                        while( i < Object.keys(profile).length ){
                            console.log( Object.keys(profile)[i]+' = '+ Object.values(profile)[i] );
                            document.getElementById("id13").innerHTML += ( Object.keys(profile)[i]+ ' = ' + Object.values(profile)[i] ) + "<br>";
                            i++;
                        }
        
                        Object.keys(profile).forEach( (key) => {
                            console.log( key +' = '+ profile[key] );
                            document.getElementById("id13a").innerHTML += (key + " = " + profile[key]) + "<br>";
                        });    
        
                        for (let key in profile) {
                            console.log(key +' = '+ profile[key]);
                            document.getElementById("id13b").innerHTML += (key + " = " + profile[key]) + "<br>"; 
        
                        }
                    </script>
                

code:
                    <p class="spec" id="id14"></p>
                    <script>
                        const car = {  make: "Honda",  model: "Civic", year: 2022}
                       
                        for (const key in car) {
                            if (car.hasOwnProperty(key)) {
                                console.log(`${key}: ${car[key]}`)
                                document.getElementById("id14").innerHTML += `${key}: ${car[key]}` + "<br>";
                            }
                        }
                    </script>
                

P.S. hasOwnProperty is a useful function because it allows to filter out properties that don't belong directly to the given object.


JavaScript object accessors

top

JavaScript accessors (getters and setters): getters (the "get" keyword) and setters (the "set" keyword) allow you to define object accessors (computed properties).

JavaScript can secure better data quality when using getters and setters. Using getters and setters gives simpler syntax, allows equal syntax for properties and methods, can secure better data quality, and is useful for doing things behind-the-scenes.

The "Object.defineProperty()" method can also be used to add getters and setters.


Object-oriented programming (OOP)

top

Object-oriented programming combines a group of variables (properties) and functions (methods) into a unit called an "object".

These objects are organized into classes where individual objects can be grouped together. OOP can help to consider objects in a program's code and the different actions that could happen in relation to the objects.

A class is a user-defined data type.

It consists of data members and member functions, which can be accessed and used by creating an "instance of that class".
It represents the set of properties or methods that are common to all objects of one type.
A class is like a blueprint for an object.E.g. a class of cars.

Example: defining a class using ES6




code:
                    <div class="spec">
                        <a id="id15"></a><br>
                        <a id="id15a"></a><br>
                        <a id="id15b"></a><br>
                    </div>
                    <script>
                        class Vehicle {
                            constructor(name, maker, engine) {
                                this.name = name;
                                this.maker =  maker;
                                this.engine = engine;
                            }
                            getDetails(){
                                return (`The name of the bike is ${this.name}.`)
                            }
                        }
                        // Making object with the help of the constructor
                        let bike1 = new Vehicle('Hayabusa', 'Suzuki', '1340cc');
                        let bike2 = new Vehicle('Ninja', 'Kawasaki', '998cc');
                                
                        document.getElementById("id15").innerText = bike1.name;
                        document.getElementById("id15a").textContent = bike2.maker; 
                        document.getElementById("id15b").innerHTML = bike1.getDetails();
                    </script>
                

Example: traditional way of defining class.




code:
                    <div class="spec">
                        <a id="id16"></a><br>
                        <a id="id16a"></a><br>
                        <a id="id16b"></a><br>
                    </div>
                    <script>
                        function Vehicles(name,maker,engine){
                            this.name = name,
                            this.maker = maker,
                            this.engine = engine
                        };
                        Vehicles.prototype.getDetails = function(){
                            return ('The name of the bike is '+ this.name);
                        }
                        let bike_1 = new Vehicles('Hayabusa','Suzuki','1340cc');
                        let bike_2 = new Vehicles('Ninja','Kawasaki','998cc');
                        
                        document.getElementById("id16").innerHTML = (bike_1.name);
                        document.getElementById("id16a").innerHTML = (bike_2.maker);
                        document.getElementById("id16b").innerHTML = (bike_1.getDetails());
                    </script>
                

Object is the basic unit of object-oriented programming: both data and function that operate on data are bundled as a unit called an object.

An object represents real-life entities and is an instance of a class.
When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated.
An object has an identity, state, and behavior. Each object contains data and code to manipulate the data.
Objects can interact without having to know details of each other's data or code. It is sufficient to know the type of message accepted and type of response returned by the objects.

Example: using an object literal to define an object



code:
                    <div  class="spec">
                        <a id="id17"></a><br>
                        <a id="id17a"></a><br>
                        <a id="id17b"></a>
                    </div>
                    <script>
                        let personA = {
                                first_name:'Anthony',
                                last_name: 'Bouverot',
                            //method
                            getFunction : function(){
                                return (`The name of the person is ${personA.first_name} ${personA.last_name}`)
                                },
                            //object within object
                                phone_number : {
                                    mobile:'12345',
                                    landline:'6789'
                                }
                        }
                        document.getElementById("id17").innerHTML = personA.getFunction(); 
                        document.getElementById("id17a").innerHTML = "home number is " + personA.phone_number.landline;
                        document.getElementById("id17b").innerHTML = "mobile number is " + personA.phone_number.mobile;
                    </script>
                

Example: using an object constructor to define an object



code:
                    <div class="spec">
                        <a id="id18"></a><br>
                        <a id="id18a"></a><br>
                    </div>
                    <script>
                        function people(first_name,last_name){
                            this.first_name = first_name;
                            this.last_name = last_name;
                        }
                        //creating new instances of person object
                        let people1 = new people('Wilfried','Van Moer');
                        let people2 = new people('Paul','Van Himst');
                        document.getElementById("id18").innerHTML = people1.first_name;
                        document.getElementById("id18a").innerHTML = `${people2.first_name} ${people2.last_name}`;
                    </script>
                

Example: the Object.create() method for a simple object with some properties


code:
                    <div class="spec">
                        <a id="id19"></a><br>
                    </div>
                    <script>
                        const coder = {
                            isStudying : false,
                            printIntroduction : function(){
                                document.getElementById("id19").innerText =`My name is ${this.name}. Am I studying?: ${this.isStudying}.`;
                            }
                        }
                        // Object.create() method
                        const me = Object.create(coder);
                        // "name" is a property set on "me", but not on "coder"
                        me.name = 'Peter'; 
                        // Inherited properties can be overwritten
                        me.isStudying = true; 
                        me.printIntroduction(); 
                    
                

Object-oriented programming has four basic concepts: encapsulation, abstraction, inheritance and polymorphism. Understanding the general framework of how they work will help to understand the basics of a computer program.

Encapsulation: through the process of encapsulation, classes cannot change or interact with the specific variables and functions of an object.

The principle of encapsulation works in a digital way to form a protective barrier around the information that separates it from the rest of the code.
In encapsulation, the variables or data of a class are hidden from any other class and can be accessed only through any member function of their class, in which they are declared.
In encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.

example: encapsulation = the process of wrapping property and function within a single unit.


code:
                    <div class="spec">
                        <a id="id20"></a><br>
                    </div>
                    <script>
                        class Human{
                            constructor(name,id){
                                this.name = name;
                                this.id = id;
                            }
                            add_Address(add){
                                this.add = add;
                            }
                            getDetails(){
                                document.getElementById("id20").innerHTML = (`name is ${this.name}, address is ${this.add}`);
                            }
                        
                        }
                        let human1 = new Human('Roger',21);
                        human1.add_Address('San Francisco');
                        human1.getDetails();
                    </script>
                

Abstraction is like an extension of encapsulation because it hides certain properties and methods from the outside code to make the interface of the objects simpler.

Abstraction helps isolate the impact of changes made to the code so that if something goes wrong, the change will only affect the variables shown and not the outside code.
Data abstraction refers to providing only essential information about the data to the outside world, hiding the background details or implementation.

example: abstraction




code:
                    <div class="spec-2">
                        <a id="id21"></a><br>
                        <a id="id21a"></a><br>
                        <a id="id21b"></a><br>
                    </div>
                    <script>
                        function persons(fname,lname){
                            let firstname = fname;
                            let lastname = lname;
                            let getDetails_noaccess = function(){
                                return (`First name is: ${firstname} Last name is: ${lastname}`);
                            }
                        
                            this.getDetails_access = function(){
                                return (`first name is: ${firstname}, last name is: ${lastname}`);
                            }
                        }
                        let persons1 = new persons('Chris','Lemmens');
                        document.getElementById("id21").innerHTML = persons1.firstname;
                        document.getElementById("id21a").innerHTML = persons1.getDetails_noaccess;
                        document.getElementById("id21b").innerHTML = persons1.getDetails_access();
        
                        console.log(persons1.firstname);
                        console.log(persons1.getDetails_noaccess);
                        console.log(persons1.getDetails_access());
                    </script>
                

Inheritance: instead of redefining the properties and methods for every type of HTML element, they can be defined once in a generic object.

Naming that object something like "HTMLElement" will cause other objects to inherit its properties and methods so you can reduce unnecessary code.
The main object is the superclass and all objects that follow it are subclasses. Subclasses can have separate elements while adding what they need from the superclass.
The capability of a class to derive properties and characteristics from another class is called inheritance. Inheritance is a concept in which some property and methods of an object is being used by another Object.

Example: inheritance


code:
                    <div class="spec">
                        <a id="id22"></a><br>
                    </div>
                    <script>
                        class person_A{
                            constructor(name){
                                this.name = name;
                            }
                            //method to return the string
                            toString(){
                                return (`Name of person: ${this.name}`);
                            }
                        }
                        class student extends person_A{
                            constructor(name,id){
                                //super keyword to for calling above class constructor
                                super(name);
                                this.id = id;
                            }
                            toString(){
                                return (`${super.toString()},Student ID: ${this.id}`);
                            }
                        }
                        let student1 = new student('Ernst',24);
                        document.getElementById("id22").innerHTML = student1.toString();
                    </script>
                

Polymorphism, meaning "many forms or shapes", allows programmers to render multiple HTML elements depending on the type of object.

This concept allows programmers to redefine the way something works by changing how it is done or by changing the parts in which it is done.
Terms of polymorphism are called overriding and overloading.
In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form.

In dynamic binding, the code to be executed in response to the function call is decided at runtime. Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at run time

Message passing is a form of communication used in object-oriented programming as well as parallel programming. Objects communicate with one another by sending and receiving information to each other. A message for an object is a request for execution of a procedure and therefore will invoke a function in the receiving object that generates the desired results. Message passing involves specifying the name of the object, the name of the function, and the information to be sent.


JavaScript object examples

top

Examples

examples

creating a JavaScript Object.

code:
                    var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
                    document.getElementById("dem01").innerHTML = person.firstName + " is " + person.age + " years old.";
                
code:
                    var person = new Object();
                    person.firstName = "John";
                    person.lastName = "Doe";
                    person.age = 50;
                    person.eyeColor = "blue"; 

                document.getElementById("dem02").innerHTML = person.firstName + " is " + person.age + " years old.";
                

JavaScript objects are mutable : any change to a copy of an object will also change the original.

code:
                    var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}
                    var xb = person;
                    xb.age = 10;
                    document.getElementById("dem03").innerHTML = person.firstName + " is " + person.age + " years old.";
                

ways to access an object property : use .property or ["property"].

code:
                    var person = {
                        firstname:"John",
                        lastname:"Doe",
                        age:50,
                        eyecolor:"blue"
                    };
                    document.getElementById("dem04").innerHTML = person.firstname + " is " + person.age + " years old.";
                

Codes:

                    var person = {
                        firstname:"John",
                        lastname:"Doe",
                        age:50,
                        eyecolor:"blue"
                    };
                    document.getElementById("dem05").innerHTML = person["firstname"] + " is " + person["age"] + " years old.";
                

JavaScript object properties

code:
                    var txt = "";
                    var person = {fname:"John", lname:"Doe", age:25}; 
                    var x;
                    for (x in person) {
                        txt += person[x] + " , ";
                    }
                    document.getElementById("dem06").innerHTML = txt;
                

add new properties to existing objects.

code:
                    var person = {
                        firstname:"John",
                        lastname:"Doe",
                        age:50,
                        eyecolor:"blue"
                    };
                    person.nationality = "English";
                    document.getElementById("dem07").innerHTML =  person.firstname + " is " + person.nationality + ".";
                

delete object properties.

code:
                    var person = {
                        firstname:"John",
                        lastname:"Doe",
                        age:50,
                        eyecolor:"blue"
                    };
                    delete person.age;
                    document.getElementById("dem08").innerHTML =  person.firstname + " is " + person.age + " years old.";
                

JavaScript object constructors


code:
                    // Constructor function for Person objects
                    function Person(first, last, age, eye) {
                        this.firstName = first;
                        this.lastName = last;
                        this.age = age;
                        this.eyeColor = eye;
                    }
                    // Create a Person object
                    var myFather = new Person("John", "Doe", 50, "blue");
                    var myMother = new Person("Sally", "Rally", 48, "green");
                    // Display age
                    document.getElementById("demo09a").innerHTML = "My father is " + myFather.age + " and " + 
                    "My mother is " + myMother.age + ".";
                    myFather.nationality = "English";
                    myMother.nationality = "American";
                    // Display nationality 
                    document.getElementById("demo09b").innerHTML = "My father is " + myFather.nationality + 
                    " and " + "my mother is " + myMother.nationality + ".";
                

Github - object examples

examples
object-assign:
                    const target = { a: 1, b: 2 };
                    const source = { b: 4, c: 5 };
                    const returnedTarget = Object.assign(target, source);
                    console.log(target);
                    // expected output: Object { a: 1, b: 4, c: 5 }
                    console.log(returnedTarget);
                    // expected output: Object { a: 1, b: 4, c: 5 }
                
object-create:
                    const person = {
                        isHuman: false,
                        printIntroduction: function() {
                        console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
                        }
                    };
                    const me = Object.create(person);
                    me.name = 'Matthew'; // "name" is a property set on "me", but not on "person"
                    me.isHuman = true; // inherited properties can be overwritten
                    me.printIntroduction();
                    // expected output: "My name is Matthew. Am I human? true"
                
object-defineproperties:
                    const object1 = {};
                    Object.defineProperties(object1, {
                        property1: {
                            value: 42,
                            writable: true
                        },
                        property2: {}
                        });
                    console.log(object1.property1);
                    // expected output: 42
                
object-defineproperty:
                    const object1 = {};
                    Object.defineProperty(object1, 'property1', {
                        value: 42,
                        writable: false
                    });
                    object1.property1 = 77;
                    // throws an error in strict mode
                    console.log(object1.property1);
                    // expected output: 42
                
object-entries:
                    const object1 = {
                        a: 'somestring',
                        b: 42
                    };
                    for (let [key, value] of Object.entries(object1)) {
                        console.log(`${key}: ${value}`);
                    }
                    // expected output:
                    // "a: somestring"
                    // "b: 42"
                    // order is not guaranteed
                
object-freeze:
                    const obj = {
                        prop: 42
                    };
                    Object.freeze(obj);
                    obj.prop = 33;
                    // Throws an error in strict mode
                    console.log(obj.prop);
                    // expected output: 42
                
object-fromentries:
                    const entries = new Map([
                        ['foo', 'bar'],
                        ['baz', 42]
                    ]);
                    const obj = Object.fromEntries(entries);
                    console.log(obj);
                    // expected output: Object { foo: "bar", baz: 42 }
                
object-getownpropertydescriptor:
                    const object1 = {
                        property1: 42
                    };
                    const descriptor1 = Object.getOwnPropertyDescriptor(object1, 'property1');
                    console.log(descriptor1.configurable);
                    // expected output: true
                    console.log(descriptor1.value);
                    // expected output: 42
                
object-getownpropertydescriptors:
                    const object1 = {
                        property1: 42
                    };
                    const descriptors1 = Object.getOwnPropertyDescriptors(object1);
                    console.log(descriptors1.property1.writable);
                    // expected output: true
                    console.log(descriptors1.property1.value);
                    // expected output: 42
                
object-getownpropertynames:
                    const object1 = {
                        a: 1,
                        b: 2,
                        c: 3
                    };
                    console.log(Object.getOwnPropertyNames(object1));
                    // expected output: Array ["a", "b", "c"]
                
object-getownpropertysymbols:
                    const object1 = {};
                    const a = Symbol('a');
                    const b = Symbol.for('b');
                    object1[a] = 'localSymbol';
                    object1[b] = 'globalSymbol';
                    const objectSymbols = Object.getOwnPropertySymbols(object1);
                    console.log(objectSymbols.length);
                    // expected output: 2
                
object-getprototypeof:
                    const prototype1 = {};
                    const object1 = Object.create(prototype1);
                    console.log(Object.getPrototypeOf(object1) === prototype1);
                    // expected output: true
                
object-isextensible:
                    const object1 = {};
                    console.log(Object.isExtensible(object1));
                    // expected output: true
                    Object.preventExtensions(object1);
                    console.log(Object.isExtensible(object1));
                    // expected output: false
                
object-isfrozen:
                    const object1 = {
                        property1: 42
                    };
                    console.log(Object.isFrozen(object1));
                    // expected output: false                 
                    Object.freeze(object1);
                    console.log(Object.isFrozen(object1));
                    // expected output: true
                
object-issealed:
                    const object1 = {
                        property1: 42
                    };
                    console.log(Object.isSealed(object1));
                    // expected output: false
                    Object.seal(object1);
                    console.log(Object.isSealed(object1));
                    // expected output: true
                
object-keys:
                    const object1 = {
                        a: 'somestring',
                        b: 42,
                        c: false
                    };
                    console.log(Object.keys(object1));
                    // expected output: Array ["a", "b", "c"]
                    
                
object-preventextensions:
                    const object1 = {};
                    Object.preventExtensions(object1);
                    try {
                    Object.defineProperty(object1, 'property1', {
                        value: 42
                    });
                    } catch (e) {
                    console.log(e);
                    // Expected output: TypeError: Cannot define property property1, object is not extensible
                    } 
                
object-prototype-hasownproperty:
                    const object1 = {};
                    object1.property1 = 42;
                    console.log(object1.hasOwnProperty('property1'));
                    // expected output: true
                    console.log(object1.hasOwnProperty('toString'));
                    // expected output: false
                    console.log(object1.hasOwnProperty('hasOwnProperty'));
                    // expected output: false
                
object-prototype-isprototypeof:
                    function object1() {}
                    function object2() {}
                    object1.prototype = Object.create(object2.prototype);
                    const object3 = new object1();
                    console.log(object1.prototype.isPrototypeOf(object3));
                    // expected output: true
                    console.log(object2.prototype.isPrototypeOf(object3));
                    // expected output: true
                
object-prototype-prototypeisenumerable:
                    const object1 = {};
                    const array1 = [];
                    object1.property1 = 42;
                    array1[0] = 42;
                    console.log(object1.propertyIsEnumerable('property1'));
                    // expected output: true
                    console.log(array1.propertyIsEnumerable(0));
                    // expected output: true
                    console.log(array1.propertyIsEnumerable('length'));
                    // expected output: false
                
object-prototype-seal:
                    const object1 = {
                        property1: 42
                    };
                    Object.seal(object1);
                    object1.property1 = 33;
                    console.log(object1.property1);
                    // expected output: 33
                    delete object1.property1; // cannot delete when sealed
                    console.log(object1.property1);
                    // expected output: 33
                
object-prototype-tolocalestring:
                    const date1 = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
                    console.log(date1.toLocaleString('ar-EG'));
                    // expected output: "٢٠‏/١٢‏/٢٠١٢ ٤:٠٠:٠٠ ص"
                    const number1 = 123456.789;
                    console.log(number1.toLocaleString('de-DE'));
                    // expected output: "123.456,789"
                
object-prototype-tostring:
                    function Dog(name) {
                        this.name = name;
                    }
                    const dog1 = new Dog('Gabby');
                    Dog.prototype.toString = function dogToString() {
                        return `${this.name}`;
                    };
                    console.log(dog1.toString());
                    // expected output: "Gabby"
                
object-prototype-valueof:
                    function MyNumberType(n) {
                        this.number = n;
                    }
                    MyNumberType.prototype.valueOf = function() {
                        return this.number;
                    };
                    const object1 = new MyNumberType(4);
                    console.log(object1 + 3);
                    // expected output: 7
                
object-values:
                    const object1 = {
                        a: 'somestring',
                        b: 42,
                        c: false
                    };
                    console.log(Object.values(object1));
                    // expected output: Array ["somestring", 42, false]
                

JavaScript.info - examples

examples
literals and properties:
                    let user = {     // an object
                        name: "John",  // by key "name" store value "John"
                        age: 30        // by key "age" store value 30
                    };
                    // get property values of the object:
                    alert( user.name ); // John
                    alert( user.age ); // 30

                    let user = {
                        name: "John",
                        age: 30,
                        "likes birds": true  // multiword property name must be quoted
                    };

                    let user = {
                        name: "John",
                        age: 30,
                    }
                
square brackets:
                    let user = {};
                    // set
                    user["likes birds"] = true;
                    // get
                    alert(user["likes birds"]); // true
                    // delete
                    delete user["likes birds"];

                    let key = "likes birds";
                    // same as user["likes birds"] = true;
                    user[key] = true;

                    let user = {
                        name: "John",
                        age: 30
                    };
                    let key = prompt("What do you want to know about the user?", "name");
                    // access by variable
                    alert( user[key] ); // John (if enter "name")
                
computed properties:
                    let fruit = prompt("Which fruit to buy?", "apple");
                    let bag = {
                    [fruit]: 5, // the name of the property is taken from the variable fruit
                    };
                    alert( bag.apple ); // 5 if fruit="apple"

                    let fruit = 'apple';
                    let bag = {
                    [fruit + 'Computers']: 5 // bag.appleComputers = 5
                    };
                
property value shorthand:
                    function makeUser(name, age) {
                        return {
                        name: name,
                        age: age,
                        // ...other properties
                        };
                    }
                    let user = makeUser("John", 30);
                    alert(user.name); // John

                    function makeUser(name, age) {
                        return {
                        name, // same as name: name
                        age,  // same as age: age
                        // ...
                        };
                    }

                    let user = {
                        name,  // same as name:name
                        age: 30
                    };
                
property names limitations:
                    // these properties are all right
                    let obj = {
                    for: 1,
                    let: 2,
                    return: 3
                    };
                    alert( obj.for + obj.let + obj.return );  // 6

                    let obj = {
                        0: "test" // same as "0": "test"
                    };
                    // both alerts access the same property (the number 0 is converted to string "0")
                    alert( obj["0"] ); // test
                    alert( obj[0] ); // test (same property)
                
"in" operator:
                    let user = { name: "John", age: 30 };
                    alert( "age" in user ); // true, user.age exists
                    alert( "blabla" in user ); // false, user.blabla doesn't exist

                    let user = { age: 30 };
                    let key = "age";
                    alert( key in user ); // true, property "age" exists
                
"for...in" loop:
                    let user = {
                        name: "John",
                        age: 30,
                        isAdmin: true
                    };
                    for (let key in user) {
                        // keys
                        alert( key );  // name, age, isAdmin
                        // values for the keys
                        alert( user[key] ); // John, 30, true
                    }

                    let codes = {
                        "49": "Germany",
                        "41": "Switzerland",
                        "44": "Great Britain",
                        // ..,
                        "1": "USA"
                    };
                    for (let code in codes) {
                        alert(code); // 1, 41, 44, 49
                    }

                    let user = {
                        name: "John",
                        surname: "Smith"
                    };
                    user.age = 25; // add one more
                    // non-integer properties are listed in the creation order
                    for (let prop in user) {
                    alert( prop ); // name, surname, age
                    }

                    let codes = {
                        "+49": "Germany",
                        "+41": "Switzerland",
                        "+44": "Great Britain",
                        // ..,
                        "+1": "USA"
                    };
                    for (let code in codes) {
                    alert( +code ); // 49, 41, 44, 1
                    }