Javascript Interview Questions ( Objects ) - Output Based, Destructuring, Object Referencing, etc
In Javascript everything comes down to Objects but what are these Objects? You will get a lot of questions in your interviews related to Objects which might be tricky and I am writing this blog to make your understanding clearer. Simple!
P.S. : Please watch the video for better explanation. Javascript Interview Questions ( Objects ) - Output Based, Destructuring, Object Referencing, etc. This is written format for the video incase you want to follow along the tutorial.
What are Objects?
An object is a collection of related data and/or functionality.
An object can be created with figure brackets { } with an optional list of properties. A property is a ``` “key: value”
let user = { [key]name: "Roadside Coder"[value], age: 24 };
### How can you access, modify and delete properties of an object?
Let's say we have the above object "user"
- Access
console.log(user.name); //Roadside Coder or console.log(user["name"]); //Roadside Coder
- Modify
user.name = "Piyush" console.log(user["name"]); //Piyush
- Delete
delete user.age;
Let's check what did you learn till here.
**What will the output of the following code snippet?**
const func = (function(a){ delete a; return a; })(5);
console.log(func);
Let us know the answer in the comments and we will discuss the answer there. We are waiting!
**What if you want a multiword key in your object?**
Write it in "double quotes".
"like the video": true
How can you access a multiword key of an object?
You can use “square bracket notation” that works with any string:
let user = {};
// get alert(user["like the video"]); // true
// set user["like the video"] = true;
// delete delete user["like the video"];
### Computed Properties
While creating objects, we can use square brackets in an object literal which are computed properties.
let's see an example
let property = "firstName" let name = "Piyush Agarwal"
let person = { [property]: name, };
// Accessing alert( bag.firstName ); // Piyush Agarwal alert( bag[property] ); //Piyush Agarwal
The ```[property]
will be taken from property
which will be ["firstName"].
Please note that square bracket notation can be used for unknown and complex key names and dot notation is used for known and simple keys.
How to access keys in an object?
Well! You can used loops but for Objects we can use for...in loop.
Let's see how it works.
let user = { name: "Piyush", age: 24, };
for (let key in user) { alert( key ); // name, age alert( user\[key\] ); // Piyush, 24 }
```plaintext
key is an iterator that will iterate through the properties of the user object. you can access any property using the key property.
> Let's move to some Interview Questions
You might encounter such questions in your Interviews. Do solve on your own and then move to the solution.
**Q1. What will the otuput of the following code snippet?**
const obj = { a: 'one', b: 'two', a: 'three' }; console.log(obj);
I repeat see the question twice and let us know your answers in the comments.
## Solution
{ a: "three", b: "two" }
because the object will take the last specified value of the same property.
**Q2. Create a function ```
multiplyByTwo(obj)
``` that multiplies all numeric property values of obj by 2.**
// Initial let nums = { a: 100, b: 200, title: "My nums" };
multiplyNumeric(nums);
//expected output nums = { a: 200, b: 400, title: "My nums" };
## Solution
function multiplyByTwo(obj) { for (let key in obj) { if (typeof obj[key] == 'number') { obj[key] *= 2; } } }
First we check if the key value is numeric or not and then multiply the numeric value by 2. Simple!
**Q3- Find the output of the following code snippet.**
const a = {}; const b = { key: 'b' }; const c = { key: 'c' };
a[b] = 123; a[c] = 456;
console.log(a[b]);
Give us your answer in the comments.
And the answer is 456.🥁
Object keys are automatically converted into strings. We are trying to set an object as a key to object `a`, with the value of `123`.
However, when we stringify an object, it becomes `"[object Object]"`. So what we are saying here, is that `a["[object Object]"] = 123`. Then, we can try to do the same again. `c` is another object that we are implicitly stringifying. So then, `a["[object Object]"] = 456`.
Then, we log `a[b]`, which is actually `a["[object Object]"]`. We just set that to `456`, so it returns `456`.
**Q4 - What is JSON.Stringify and JSON.parse ?**
Do let us know in the comments after you watch the video here
[Objects in JavaScript](https://www.youtube.com/watch?v=XnFIX3c7xoI)
**Q5 - Spread Operator**
[...'Lydia'];
["L", "y", "d", "i", "a"]
**Q6- What's the output?
**
const user = { name: 'Lydia', age: 21 }; const admin = { admin: true, ...user };
console.log(admin);
{ admin: true, name: "Lydia", age: 21 }
**Q7 - What's the output of the following code snippet?
**
const settings = { username: 'lydiahallie', level: 19, health: 90, };
const data = JSON.stringify(settings, ['level', 'health']); console.log(data);// "{"level":19, "health":90}"
The second argument of `JSON.stringify` is the *replacer*. The replacer can either be a function or an array, and lets you control what and how the values should be stringified.
If the replacer is an *array*, only the property names included in the array will be added to the JSON string. In this case, only the properties with the names `"level"` and `"health"` are included, `"username"` is excluded. `data`is now equal to `"{"level":19, "health":90}"`.
If the replacer is a *function*, this function gets called on every property in the object you're stringifying. The value returned from this function will be the value of the property when it's added to the JSON string. If the value is `undefined`, this property is excluded from the JSON string.
**Q8 - What's the output?
**
const shape = { radius: 10, diameter() { return this.radius * 2; }, perimeter: () => 2 * Math.PI * this.radius, };
console.log(shape.diameter()); console.log(shape.perimeter());
20 and NaN
Note that the value of `diameter` is a regular function, whereas the value of `perimeter` is an arrow function.
With arrow functions, the `this` keyword refers to its current surrounding scope, unlike regular functions! This means that when we call `perimeter`, it doesn't refer to the shape object, but to its surrounding scope (window for example).
There is no value `radius` on that object, which returns `NaN`.
### Destructuring and renaming
Suppose you go to a grocery store which has so many items displayed on the shelves but you buy items which are required.
In the same way we take out specific properties from an object which is required.
Let's see an example
let user={ name:"Piyush", age:24 }
const {name}= user;
console.log(name);
const { name: myName } = { name: 'Lydia' };
console.log(name); //undefined
When we unpack the property `name` from the object on the right-hand side, we assign its value `"Lydia"` to a variable with the name `myName`.
With `{ name: myName }`, we tell JavaScript that we want to create a new variable called `myName` with the value of the `name` property on the right-hand side.
Since we try to log `name`, a variable that is not defined, `undefined` is returned on the left side assignment. Later, the value of `Lydia` is stored through the destructuring assignment
**Q- What's the output?**
function getItems(fruitList, ...args, favoriteFruit) { return [...fruitList, ...args, favoriteFruit] }
getItems(["banana", "apple"], "pear", "orange") //SyntaxError
...args
is a rest parameter. In this example, the rest parameter was the second parameter. This is not possible, and will throw a syntax error.
**Q- How will u make the above code snippet work?**
The rest parameter's value is an array containing all remaining arguments, and can only be the last parameter!
```jsx
function getItems(fruitList, favoriteFruit, ...args) {
return [...fruitList, ...args, favoriteFruit];
}
getItems(['banana', 'apple'], 'pear', 'orange');
The above example works. This returns the array [ 'banana', 'apple', 'orange', 'pear' ]
Referencing
Q - What's the output of the following code snippet?
let c = { greeting: 'Hey!' };
let d;
d = c;
c.greeting = 'Hello';
console.log(d.greeting); // Hello
Solution
In JavaScript, all objects interact by reference when setting them equal to each other. When you change one object, you change all of them.
Q - What is the output of the following code snippet?
console.log({a:1} == {a:1});
console.log({a:1} === {a:1});
Solution
false
false
In JavaScript, Objects are compared based on references.
In the above statement, we are comparing two different objects so their references will be different. Hence, we get the output as false for both of the statements.
Q - What's the output of the following code snippet? ( Referencing is not always there )
let person = { name: 'Lydia' };
const members = [person];
person = null;
console.log(members);
Solution
[{ name: "Lydia" }]
First, we declare a variable person
with the value of an object that has a name
property.
Then, we declare a variable called members
. We set the first element of that array equal to the value of the person
variable. Objects interact by reference when setting them equal to each other. When you assign a reference from one variable to another, you make a copy of that reference. (note that they don't have the same reference!)
Then, we set the variable person
equal to null
.
We are only modifying the value of the person
variable, and not the first element in the array, since that element has a different (copied) reference to the object. The first element in members
still holds its reference to the original object. When we log the members
array, the first element still holds the value of the object, which gets logged.
Q - What's the output of the following code snippet?
const value = { number: 10 };
const multiply = (x = { ...value }) => {
console.log((x.number *= 2));
};
multiply();
multiply();
multiply(value);
multiply(value);
Solution
20, 20, 20, 40
Explaination
In ES6, we can initialize parameters with a default value. The value of the parameter will be the default value, if no other value has been passed to the function, or if the value of the parameter is "undefined"
. In this case, we spread the properties of the value
object into a new object, so x
has the default value of { number: 10 }
.
The default argument is evaluated at call time! Every time we call the function, a new object is created. We invoke the multiply
function the first two times without passing a value: x
has the default value of { number: 10 }
. We then log the multiplied value of that number, which is 20
.
The third time we invoke multiply, we do pass an argument: the object called value
. The *=
operator is actually shorthand for x.number = x.number * 2
: we modify the value of x.number
, and log the multiplied value 20
.
The fourth time, we pass the value
object again. x.number
was previously modified to 20
, so x.number *= 2
logs 40
.
Q - What is the output of the following code snippet?
function changeAgeAndReference(person) {
person.age = 25;
person = {
name: 'John',
age: 50
};
return person;
}
const personObj1 = {
name: 'Alex',
age: 30
};
const personObj2 = changeAgeAndReference(personObj1);
console.log(personObj1); // -> ?
console.log(personObj2); // -> ?
Solution
{ name: 'Alex', age: 25 }
{ name: 'John', age: 50 }
The function first changes the property age on the original object it was passed in. It then reassigns the variable to a brand new object and returns that object. Here’s what the two objects are logged out.
Q - Difference between shallow copy vs deep copy.
**Shallow copy **
A shallow copy means that certain (sub-)values are still connected to the original variable.
Example 👇🏻
const user={
name: 'Jen',
age: 26
};
const copyOfUser =user;
console.log(user, 'user'); //{ name: 'Jen', age: 26 } user
console.log('------------After Modification-----------');
copyOfUser.age = 24;
/*
Here you would expect user object wouldn't change, but copyOfUser
and user object both share same memory address
*/
console.log(user, 'user');// ------------After Modification-----------
{ name: 'Jen', age: 24 } user
**Deep copy **
A deep copy means that all of the values of the new variable are copied and disconnected from the original variable
Example 👇🏻
const user = {
name: "Jen",
age: 26
}
console.log("=========Deep Copy========");
const copyOfUser = JSON.parse(JSON.stringify(user));
console.log("User=> ",user);
console.log("copyOfUser=> ", copyOfUser);
/*
=========Deep Copy========
User=> { name: 'Jen', age: 26 }
copyOfUser=> { name: 'Jen', age: 26 }
*/
console.log("---------After modification---------");
copyOfUser.name = "Piyush";
copyOfUser.age = 24;
/*
Here user object will not change
*/
console.log("User=> ",user);
console.log("copyOfUser=> ",copyOfUser);
/*
---------After modification---------
user=> { name: 'Jen', age: 26 }
copyOfUser=> { name: 'Piyush', age: 24 }
*/
**Q - How to clone an object without referencing its keys to original object? **
Solution
4 ways to clone an object 👇🏻
const obj = {a: 1 ,b: 2}
const objclone = Object.assign({},obj);
const objclone = JSON.parse(JSON.stringify(employee));
const objclone = { ...obj }
Finally coming to the end of this blog. Hope you had a great read.
Do give a 👍 if you liked the content. More such blogs coming on your way!
Connect with us on Twitter 👇🏻