The Spread Operator Part 2
Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 19 of 65.
The spread operator can merge objects (JSON):
const personalInfo = {name: "John", age: 30};
const jobInfo = {company: "Tech Corp", position: "Developer"};
const completeProfile = {...personalInfo, ...jobInfo};Now the completeProfile will have all four keys: name, age, company and position:
console.log(completeProfile);
// Output: {name: "John", age: 30, company: "Tech Corp", position: "Developer"}It can also add new properties and override existing properties while copying:
const user = {name: "Alice", age: 25, mood: "sad"};
const userWithEmail = {
...user,
email: "alice@example.com",
mood: "happy"
};Challenge
EasyCreate a function named mergeCars that takes two car objects as parameters. The function should merge the second car's properties into the first car's properties and return a new car object without modifying any of the original objects.
Cheat sheet
The spread operator can merge objects:
const personalInfo = {name: "John", age: 30};
const jobInfo = {company: "Tech Corp", position: "Developer"};
const completeProfile = {...personalInfo, ...jobInfo};It can also add new properties and override existing properties while copying:
const user = {name: "Alice", age: 25, mood: "sad"};
const userWithEmail = {
...user,
email: "alice@example.com",
mood: "happy"
};Try it yourself
function mergeCars(car1, car2) {
// Write code here
}
// Do not write anything outside functionThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String FundamentalsIterate Over StringsTemplate LiteralsString MethodsRecap - String Weaver4JSON Part 2
Iterate Over JSONNested JSONJSON Optional ChainingShallow And Deep CopyRecap - Bicycle ShopRecap - Solar System10Manage Festival System
Project OverviewAdd Movies & Venues2Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays5Sets Part 1
What Is A Set?Iterating Over SetsAdding An ElementRemoving An ElementChecking If An Element ExistsSize And Is EmptyCopy And ClearRecap - Basic Of Sets8Arrays Interesting Topics
Array DestructuringSpread Syntax in ArraysSparse ArraysRecap - Arrays Workshop3JSON Part 1
What is a JSON?Check If Key ExistsObject MethodsThe Spread Operator Part 1The Spread Operator Part 2Remove KeysRecap - JSON Manipulate Keys