Javascript Objects-01

Table of contents

In this topic, we are going to study Objects in depth

Object stores the value in key and its value format.

Syntax: -

 const obj={
name:'rahul',
roll_no:298220,
college:'abc college'
}

Here obj is object_name you can change it as you want

name:'rahul' is a property

name is key

rahul is value

Another ex is below for a better understanding: -

const obj1={
    type:'sslv',
    range:500,
    body:'cylinder',
    fuel:'cng',
    config : {
        name:'mars'
    }
 }
 console.log(obj1);

Loop in Object: -

we have for in for Object for loop

const obj1={
    type:'sslv',
    range:500,
    body:'cylinder',
    fuel:'cng',
    config: {
        name:'mars'
    }
 };

     for (const x in obj1)
    {
        console.log(obj1[x]);
    }
Output: -

sslv
500
cylinder
cng
{ name: 'mars' }

Simple challenge

From obj1 what is the Output of: -

 for(const x in obj1)
{
    console.log(x);
}

Way 2 for create an object

const obj2=new Object()//constructor
obj2.redbook='red_bood';
obj2.type='comedy'
console.log(obj2);
Output: -
    {
    redbook:red_book,
    type:comedy
    }

Now I have a scenario in which we have object A with some properties and we have object B now we want to access all the properties of object A in object B.

For that we have Object.create


const powers={
    fly:true,
    cordinate:Math.random()+2
}
const obj3 = Object.create(powers);
console.log(obj3);
console.log(obj3.cordinate);
console.log(Object.getPrototypeOf(obj3));

Now Question is we have an output of console.log(obj3.cordinate) which is 2.502983 but {} output for console.log(obj3) well for that we have to understand this in the console of the browser.

It is there but in the [[prototype]]

Challenge: - Return all the strings from the given array

const name=['mouse',45,'number',67,52,5,098];

Hint:- use typeof (I will provide solution in last but 1st solve it by yourself)

this: -

this keyword behaves differently in different situations

It has different value where it is used

1)Alone it refers to a global object(window).

2)In function this keyword refer to global object(window)

3)In a method(any function inside an object),this refer to the owner object

Another way of Object

const obj5={
    comics:'marvel',
    pen:'',
    printComic:function(){
        this.pen+='red  book'
        console.log(this);

    }
}
console.log(obj5.printComic());

One point if any function inside the object is called METHOD.