Javascript object and It's method

Javascript object and It's method

Everything in javascript is an object.

What is an Object?

Object in simple words is an entity with properties and type.

It contains key-value pair. These key-value pairs are called properties.

Accessing properties

  • Using Dot [.] operator

    To access value we use the [.] operator followed by the property name (key).

    In the below example, "name" is the name of the property or a key and Bee is the value.

      const obj = {name: "bee"}
      console.log(obj.name); // This will print bee
    
  • Using Square brackets []

      const obj = {peanut: 20}
      console.log(obj['peanut']); // This will print 20
    

    In the above example, we use square brackets to access the value of the key.

Object Initializing in javascript

  • Using Object Literals

  • Using Instance of Object

  • Using constructor function

To check if the key exists or not

we use the "in" operator to check whether the key exists in the object or not

in returns either true or false;

In the above example,

name key is present inside the object so it printed true and since the email key was not present it printed false.

We can also use hasOwnProperty to check if the key is present or not

if(obj.hasOwnPropert(key)){
    console.log("Present");
}else{
    console.log("Not Present");
}

Creating Object Copies

  1. Assigning to an existing object.

    In the above example, "newobj" named object is being made to point to the memory of object "obj". So It is pointing by reference which means the change made in "obj" will also be changed in "newobj" and vice-versa.

  2. Using spread operator.

    In the above example, we use spread operators(...) to copy object. The spread operator creates a shallow copy thus we see changes made "obj" doesn't reflect to "newobj".

  3. Using Object.Assign()

Object.assign() takes two parameters

  1. target object where we have to copy the properties.

  2. source object from where we copy the properties.

Like spread operators, they also do the shallow copy.

Looping over the object

  1. Using For in Loop

    For in loop is used to iterate over object.

  2. Using Object.keys()

    This method iterates over keys

  3. Using Object.values()

    This method iterates over values

  4. Using Object.entries()

    This is another ES8 method to iterate over objects.

That concludes this article thanks for reading any feedback is welcomed.

THANK YOU