JavaScript - Lesson 03
JavaScript - Lesson 03
Presented by:
Ahsan Ali Mansoor
3+ Years of experience / Team Lead (React JS)
Sr. Full Stack Developer at eBridge.tech
Objects
• Objects are used to store keyed collections of various data and more complex entities
• We can imagine an object as a cabinet with signed files. Every piece of data is stored in its file by
the key. It’s easy to find a file by add/remove a file its name(Key).
• An empty object (“empty cabinet”) can be created using one of two syntaxes:
• Delete a Property with delete operator (return true either property exist or not).
Syntax: delete person.age; // or delete person["age"];
• Access Property with Dot notation.
• Access Property with square brackets.
• Add a Property of any type.
• Keys can have space but accessible only with square brackets.
Objects – Computed properties
• We can use square brackets in an object literal. That’s called computed properties.
let userColor = 'fvtcolor';
user[userColor] = 'blue’
console.log(user)
The meaning of a computed property is simple: [userColor] means that the property name should be
taken from the variable userColor.
• With “hasOwnProperty”
Syntax: user.hasOwnProperty("car") //true means property exist
There will be no error if the property doesn’t exist! Accessing a non-existing property just returns
undefined
• There is also exists a special operator "in" to check for the existence of a property.
Syntax: "key" in object
console.log('name' in user) //true means property exist
Property name usually a quoted string. If we omit quotes, that would mean a variable containing the
actual name will be tested.
Objects – Property existence check
Usually, the strict comparison "=== undefined" check the property existence just fine. But there’s a
special case when it fails, but "in” and “hasOwnProperty” works correctly.
console.log(user.bloodTest === undefined) //Again returns true which means the property doesn’t
exist
console.log('bloodTest' in user) //true
console.log(user.hasOwnProperty('bloodTest’)) //true
Objects – “for…in” loop
To walk over all keys of an object, there exists a special form of the loop: for..in.
The syntax:
for (key in object) {
// executes the body for each key among object properties
}
let codes = {
"49": "Germany",
"41": "Switzerland",
"44": "Great Britain",
"1": "USA"
};
Two objects are equal only if they are the same object. Means two variables pointing to same
object.
let a = {};
let b = a; // copy the reference
And here two independent objects are not equal, even though both are empty:
let a = {};
let b = {}; // two independent objects
console.log( a == b ); // false
What is Deep Copy & Shallow Copy?
Deep Copy – by value:
Primitive values: strings, numbers, booleans – are assigned/copied “as a whole value” which is called
deep.
As a result we have two independent variables, each one is storing the string "Hello!".
Objects – Copying by reference (Shallow Copy)
By default, objects are copied by referenced (Shallow copied).
Means: A variable stores not the object itself, but its “address in memory”, in other words “a
reference” to it.
We can use any variable to access the cabinet and modify its contents:
There’s no built-in method for that in JavaScript. Actually, that’s rarely needed.
Objects – Deep Copy for primitive values
There are three methods of doing such thing but only for primitive values.
Objects inside objects still copied by reference but we will see later on how
to overcome this.
It copies all properties of user into the empty object and returns it. Actually,
the same as the loop, but shorter.
Objects – Deep Copy for primitive values
Object.assign & for in loop only for primitive keys.
Now it’s not enough to copy clone.sizes = user.sizes, because the user.sizes is
an object, it will be copied by reference. So clone and user will share the
same sizes:
let user = {
name: "John",
sizes: { height: 182, width: 50 }
};
Off the note: When receiving data from a web server, the data is always
a string. Parse the data with JSON.parse(), and the data becomes a
JavaScript object.
Objects – Cloning (Summary)
With for…in loop
for (let key in user) { clone[key] = user[key];}
Spread Operator
let objOne = {name: "sabir", class: 18}
let objTwo = {...objOne}
If the receiving object (user) already has the same named property, it will be
overwritten.
Objects – Const object
Const only fixes the value of object itself. All object properties can be changed.
const user = {name: "John"}
user.age = 25; // (*)
console.log(user.age); // 25
The const would give an error if we try to set user to something else, for instance:
// Error (can't reassign user)
user = {
name: "Pete"
};
Objects – Property flags and descriptors
Problem: What if we want to fix object properties so they can not be changed?
Property flags
Object properties, besides a value, have three special attributes (so-called “flags”):
We didn’t see them yet, because generally they do not show up. When we create a property “the
usual way”, all of them are true. But we can change them anytime.
Objects – Property flags and descriptors
How to get Property flag
let user = {name: "John"}
let descriptor = Object.getOwnPropertyDescriptor(user, 'name');
console.log( JSON.stringify(descriptor ) );
{
"value": "John","writable": false,"enumerable": false,"configurable": false
}
Objects – Property value shorthand
• In real code we often use existing variables as values for property
names. For instance:
var person1 = {
firstName:"John",
lastName: "Doe"
}
var person2 = {
firstName:"Mary",
lastName: "Doe"
}
var person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName:"John",
lastName: "Doe"
}
var person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var person1 = {
firstName: "Mary",
lastName: "Doe"
}
var person1 = {
firstName:"John",
lastName: "Doe"
}