Objects in Javascript

Objects
The object is a container for data. If functions are piping then objects are boxes.
Declaration:    var obj = {key : value}

example:
 var abc= {
name: "william",
OS: "windows"
};
document.write( abc.name);      // william


variable assigned to keys in an object are called properties.

Functions assigned to keys in an object are called methods.

here is example:

var dummy={
name:"william",
greeting:function(){document.write("i am inside function <br>")}
};
document.write(dummy.name+"<br>");
dummy.greeting();



Here is link to practical: https://codepen.io/preptuts/pen/WapKwL?editors=0011


To delete the property as given below:


delete dummy.name;
document.write(dummy.name+"<br>");  // undefined


adding data outside the curly braces to object

var car={};
car.name="ford";
car.color="black";
car.fuel="patrol";
car.speed= function(){
  document.write("120KMLPS");
};
car.speed(); //120KMLPS

Overwrite by reassigning another value

var obj={}
obj.myProp="a value";
obj.myProp="abrand new value";
document.write(obj.myProp);

Objects can hold any type of data link number array etc.

var obj={
randomNumb:200,
arraList:[1,2,3,4],
//innerObj: {
 // greeting: function(){document.write("greeting here");};
//}
};
document.write(obj.randomNumb); // 200

Difference between Array And Objects

the array has a zero-based index, not in case of objects. Without objects you cannot access the data with numerical index, you simply access the data by its key. 

You use an array if you want a list of an item on their hand if you want a list of item with the key value then you use objects.


//array //
var arr = [ " myVal" ];
document.write(arr[0]);



//Objects 
var obj ={};
obj.mykey="myval";
document.write(obj.mykey);






Comments

Post a Comment