has key-value pairs, separated by colon. The key is also known as property
Similarity: index of arrays are replaced by keys in objects.
Object literal syntax is directly writing properties inside {}
Order during retrieval does not matter in case of objects whereas order matters in arrays.
Arrays: used for structured data
Objects: used for unstructured data
Property lookup methods in objects:
- using dot notation
- using brackets notation: key is defined as string in [] inside quotes, the key name can be an expression also. Ex. obj['firstName']; Ex. obj[2+3]; Putting an expression won't work with dot notation. We need to use the final property name, and not the computed property name.
Hence, when we have a computed property name its recommended to use brackets notation.
undefined will be returned if a property doesn't exist and we try to access it.
obj['insta-id'] = '@juju';
Refer operator precedence table on MDN for more info.
Object Methods
Fns are a type of value. Hence, we can create key-value pair in which the value is a fn. Means, we can add fns to objects.
Fn expression becomes methods inside objects i.e a fn attached to an object as a value for a key.
Fn declaration inside an object won't work.
method is also a property on the object which holds a fn value.
We can have values in the form of : array, string, boolean, fn etc.
obj.propName(); // will get the fn value and execute it using the ()
'this' : refers to the object on which its called
const person = {
fName: 'Raja',
lName: 'Rajeshwar',
bYear: 1970,
job: 'King',
friends: ["Billu","Penchu","Ramesh"],
calcAge: function(){
// this will be the object which has called this method.
// Its used to reference the object, and not hardcode it.
console.log(this);
// a new property is created on the person object named 'age'
this.age = 2024 - this.bYear
return this.age;
}
}
person.calcAge(1970);
// age property will only exist if this fn was called atleast once else it won't exist.
person.age;
Arrays, Fns are all under the hood objects in JS. Hence, they have their own methods.