Objects Javascript

Q1. What is the output?

const obj = {
	a: "one",
	b: "two",
	a: "three",
}

console.log(obj);

Answer

{
	a: "three", 
	b: "two",
}

Q2. Create a function multiplyByTwo(obj) that multiplies all numeric property values of nums by 2.

let nums = {
	a: 100,
	b: 200,
	title: "My nums",
};

multiplyByTwo(obj);

Answer

function multiplyByTwo(obj) {
	for (key in obj) {
		if (typeof obj[key] === "number") {
			obj[key] = obj[key] * 2;
		}
	}
}

console.log(obj);

Q3. What is the output of the following code (Imp)

const a = {};
const b = { key: "b" };
const c = { key: "c" };

a[b] = 123;
a[c] = 456;

console.log(a[b]);

Answer

const a = {};
const b = { key: "b" };
const c = { key: "c" };

a[b] = 123;
a[c] = 456;

console.log(a[b]); // 456

Q5. What's the output? Spread Operator

Spread Operator & Rest Operator Javascript

console.log([..."Lydia"]); // spread operator

Answer

['L', 'y', 'd', 'i', 'a']

Q6. What's the output? Spread Operator

const user = { name: "Lydia", age: 21 };
const admin = { admin: true, ...user};

console.log(admin);

Answer

{
	admin: true,
	name: "Lydia",
	age: 21,
}

Q7. What's the output? JSON.stringify

JSON.stringify JSON.parse Javascript

const settings = {
	username: "Chaitanya",
	level: 19,
	health: 90,
};

const data = JSON.stringify(settings, ["level", "health"]);
console.log(data); // { level: 19, health: 90 }

Q8. What's the output? this keyword

This Keyword Javascript

const shape = {
	radius: 10,
	diameter() {
		return this.radius * 2;
	}, 
	perimeter: () => 2 * Math.PI * this.radius,
};

console.log(shape.diameter());
console.log(shape.perimeter());

Answer

console.log(shape.diameter()); // 20
console.log(shape.perimeter()); // NAN

Q10. What's the output?

function getItems(fruitList, favoriteFruit, ...args) {
	return [...fruitList, ...args, favoriteFruit];
}

console.log(getItems(["banana", "apple"], "pear", "orange"));

Q15. What's the output?

function changeAgeAndReference(person) {
	person.age = 25;
	person = {
		name: "John",
		age: 50,
	};
	return person;
}

const personObj1 = {
	name: "Alex",
	age: 30,
};

const personObj2 = ChageAgeAndReference(personObj1);

console.log(personObj1) // -> ?
console.log(personObj2) // -> ?

Answer

console.log(personObj1) // { name: "Alex", age: 25 }
console.log(personObj2) // { name: "John", age: 50 }

Q16. What's shallow copy and Deep copy?

Deep & Shallow Copy Javascript

Q17. How to deep copy / clone an object?

Deep & Shallow Copy Javascript