JavaScript: Essentials & Interview Questions - Part 2

Narendra Singh Rathore
2 min readSep 2, 2019

→ Part 1

NOTE: References from multiple site( w3school, MDN, freecodeCamp )

1. How deep copy and shallow copy works: Objects

A deep copy means that all of the values of the new variable are copied and disconnected from the original variable. A shallow copy means that certain (sub-)values are still connected to the original variable.

Shallow coping object will only copy top level reference from object, whereas nested properties will still have reference to old copy of object.

const person = {
name:'Narendra',
car:'Buggati',
address: {
city:'Dubai',
pincode: 1234
}
};

We can make shallow copy using ES6 spread syntax and Object.assign()

const p1 = { ...person } ;// OR Object.assign({}, person);
p1.name = 'Rudy';
p1.address.city = 'Mexico';
console.log(person); // name:'Narendra', address:{city:'Mexico'}

So as we can see, we still can alter inner nested property after we make a shallow copy from an object, as it's still referencing to old object inner properties by reference.

To make deep copy, we can use JSON.

The JSON object contains methods for parsing JavaScript Object Notation (JSON) and converting values to JSON. It can’t be called or constructed, and aside from its two method properties, it has no interesting functionality of its own.

const p1_Stringified = JSON.stringfy(person) ;const p1 = JSON.parse(p1_Stringified);
p1.name = 'Rudy';
p1.address.city = 'Mexico';
console.log(person); // name:'Narendra', address:{city:'Dubai'}

That's how we can create a deep copy from an object without leaving any inner references.

2. Correctly Type-Checking Objects

Object.prototype.toString.call()

3. Check property exist on object

Usually, the strict comparison "=== undefined" check the property existance just fine. But there’s a special case when it fails, but "in" works correctly.

let person = {
name: undefined
};

console.log( person.name); // undefined

console.log( "name" in person ); // true, the property does exist!

4. Ordering of properties in Object

Integer properties are sorted, other appear in creation order.

let a = {
10: "10",
"6": "6",
a:"a",
"1": 1,
b:"b"
};
for( let props in a){
console.log(props); // output: 1 , 6, 10, a, b
}

Integer property means a string that can be converted to-and-from an integer without change.

let a = String(Math.trunc(Number("1"))); // "1", same, integer property
let b = String(Math.trunc(Number("+2"))) // "2", not same "+2" ⇒ not integer property
let c = String(Math.trunc(Number("5.6"))) //"5", not same "5.6" ⇒ not integer property

--

--