Objects in JavaScript. Basic code examples open

Objects in JavaScript. Basic code examples

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators

Objects are a complex type of data that can contain various properties that describe its state, methods that describe it conduct.

Creation of a new object

:

    let user = new Object();//now the object will be called user

The expression new Object() represents a call to a constructor – a function, a new object is created. To call a constructor the new operator is applied. Calling a constructor is actually like calling a regular function.

The second way to create an object is to use curly braces:

    let user = {};

Properties of the object

Properties are the data stored by our object. To specify an object property, add a dot, write the name of the property and the equals sign set the property.

Consider an example:

    let user = {};//let's create an empty object
    user.name = "Alexander";//set the name property to our object
    user.age = 33;//let's set the age property of our object

We can set properties when creating an object:

    let user = { name: "Alexander", age: 33 };

There is another option for setting properties:

    let name = "Alexander";//let's create ordinary variables and set their values
    let age = 33;
    let account = { name, age };//let's pass the variables to the array
    console.log(account.name);//Alexander

Methods of objects

An object’s methods are functions that define its behavior or the actions it performs. For example, let’s define a method that would display a person’s name and age:

    let person = {};//create an object
    person.name = "Alexander";//add properties
    person.age = 33;

    //and now we will create an anonymous function and add it to the object
    person.display = function () {

        //the function will output the properties of our object to the console
        console.log(person.name);
        console.log(person.age);

    };

    // display method call
    person.display();

Like properties, methods can be added when creating an object:

    let person = {

        name: "Alexander",//let's set the properties of the object
        age: 33,
        
        //let's set the method of the object
        display: function () {

            console.log(this.name);
            console.log(this.age);

        }
    };
To refer to the properties or methods of an object within that object, the this keyword is used. It means reference to the current object.

We can not add the word function when specifying an object method:

    let person = {

        name: "Alexander",
        age: 33,

        display() {

            console.log(this.name);
            console.log(this.age);

        },
        
        //if necessary, we can pass parameters to the object method
        display_with_parameters(parameter) {
            console.log(parameter);

        }

person.display();

    };

Arrays syntax

There is also an alternative way to define properties and methods using array syntax:

    let person = {};//create an object
    person["name"] = "Alexander";//set the properties
    person["age"] = 33;
    person["display"] = function () {

        console.log(person.name);
        console.log(person.age);
    };

    //call the method
    person["display"]();

Strings as properties and methods

The names of the properties and methods of an object are always strings. That is, we could have previously defined an object rewrite like this:

    let person = {
        //in this case, the names of properties and methods are enclosed in quotes
        "name": "Alexander",
        "age": 33,
        "display": function () {

            console.log(user.name);
            console.log(user.age);
        }
    };

    //call method
    person.display();

Enclosing the name in a string can help identify the name of properties that consist of two words or separated
space:

    let person = {
        name: "Alex",
        age: 33,
        "full name": "Alexander",
        "display info": function () {

            console.log(user.name);
            console.log(user.age);
        }
    };
    //you must use array syntax when using quotation marks to refer to an object's properties and methods
    console.log(user["full name"]);
    user["display info"]();

Comparison of objects

For example, compare two objects:

    const person = { name: "Alexander" };
    const newperson = { name: "Bob" };
    console.log(person == newperson);    // false
    console.log(person === newperson); // false

If the values in the objects are the same, we will still get false:

    const person = { name: "Alexander" };
    const newperson = { name: "Alexander" };
    console.log(person == newperson);    // false
    console.log(person === newperson); //false

And when two constants or variables store a reference to the same object, we get true:

    const person = { name: "Alexander" };
    const newperson = person;

    console.log(person == newperson);    // true
    console.log(person === newperson); //true

Dynamic Determination of Property and Method Names

The array syntax allows us to define property names outside of the object:

    const prop1 = "name";
    const prop2 = "age";

    let person = {
        [prop1]: "Alexander",
        [prop2]: 33
    };

    console.log(person);           // {name: "Tom", age: 37}
    console.log(person.name);      // Alexander
    console.log(person["age"]);    // 33

Thanks to this, for example, you can dynamically create objects with arbitrary property names:

    function createObject(propName, propValue) {
        return {
            [propName]: propValue,
            print() {
                console.log(`${propName}: ${propValue}`);
            }
        };
    }
    let person = createObject("name", "Tom");
    person.print();     // name: Tom

    let book = createObject("title", "JavaScript Reference");
    book.print();   // title: JavaScript Reference

Removing object properties

We can delete properties and methods using the delete operator:

    delete object.property;
    delete object["property"];

Let’s delete the property:

    let person = {};//create an object
    person.name = "Alexander";
    person.age = 33;
    person.display = function () {

        console.log(person.name);
        console.log(person.age);

    };

    delete person.name; // delete property
    delete person["name"];// arrays syntax alternative

Constant objects

To make an object truly constant and remove the ability to change the object, you need to apply a special
the Object.freeze() method. An object is passed to this method as a parameter, which must be made constant:

    const person = { name: "Alexander", age: 33 };
    Object.freeze(person);//let's freeze our object and take away the ability to edit the object
    person.name = "Bob";
    console.log(person.name);//Alexander

Creating an object from variables and constants

    function getSalary(status) {
        if (status === "senior") return 1500;
        else return 500;
    }
    const name = "Alexander";
    const age = 33;

    const person = { name: name, age: age, salary: getSalary() };

    console.log(person);

The same applies to passing functions to object methods:

    function display() {
        console.log(this.name, this.age);
    }

    const place = function (location) {
        console.log(location)
    };

    const name = "Alexander";
    const age = 33;
    const salary = 500;
    const person = { name, age, salary, display, place };

    person.display();
    person.place("Wroclaw");

Object.fromEntries() function

Using the Object.fromEntries() function, you can create an object from a set of key-value pairs, where the key will then be represents the name of the property.

For example, let’s create an object from arrays:

    const Data = [["name", "Alexander"], ["age", 33]];
    const person = Object.fromEntries(Data);
    console.log(person); // {name: "Alexander", age: 33}

Objects within objects

Some objects can contain other objects as properties. Consider an example:

    var country = {

        name: "England",
        language: "english",
        capital: {
            name: "London",
            population: 8982000,
        }
    };
    console.log("Capital: " + country.capital.name); //London
    console.log("Population: " + country["capital"]["population"]);

Arrays can also be used as properties, including arrays of other objects:

    var country = {

        name: "England",
        languages: ["English", "Hindi"],
        capital: {
            name: "London",
            population: 8982000
        },
        "places to visit": [
            { name: "Tower of London", adress: 'London EC3N 4AB' },
            { name: "Buckingham Palace", adress: 'London SW1A 1AA' },
            { name: "London Eye", adress: 'Lambeth, London' }
        ]
    };

    // output all elements from country.languages
    
    for (var i = 0; i < country.languages.length; i++)
        document.write(country.languages[i] +);

    // output all elements from country.cities
    
    for (var i = 0; i < country['places to visit'].length; i++)
        document.write(country['places to visit'][i].name +);

Checking the presence of properties and methods in the object

When specifying new properties and methods of an object, it is important to check whether the object already has such methods and properties. For this, the in operator is used in JavaScript:

    "property or method" in object
If the property exists returns true otherwise false

For example, we learn that a number of properties do not exist in the object:

    const profile = {};
    profile.name = "Alexander";
    profile.age = 33;

    profile.print = function () {
        console.log(this.name);
        console.log(this.age);
    };

    const hasNameProp = "name" in profile;
    console.log(hasNameProp); // true - the name property is in the profile

    const hasWeightProp = "weight" in profile;
    console.log(hasWeightProp); // false - profile does not have a property or method called weight

    const hasPrintMethod = "print" in profile;
    console.log(hasPrintMethod); // true - profile has a print method

Alternative method:

const hasNameProp = profile.name !== undefined;
console.log(hasNameProp); // true

And since objects represent the Object type, which means that it has all its methods and properties, objects can also use the hasOwnProperty() method, which is defined on the Object type:

    const hasNameProp = profile.hasOwnProperty("name");
    console.log(hasNameProp); // true
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation