JavaScript Tutorial
  • 🍼Introduction
  • 🥛Hello Gamers
  • 🍯Variables
    • Action Game Example
  • 🌰Strings
    • RPG Example
  • 🍪Character Acces
    • Simulation Example
  • 🍩Plus (+) operator
    • Strategy Game Example
  • 🥜Functions
    • Adventure Game Example
  • 🍿Template strings
    • Strategy Game Example
  • 🍫Numbers
    • Sports Game Example
  • 🍬Converting Numbers to Strings
    • Fighting Game Example
  • 🍭Operations
    • FPS Game Example
  • 🍮Conditions
    • Platformer Game Example
  • 🎂Arrays
    • Puzzle Game Example
  • 🍰Objects
    • Racing Game Example
  • 🧁Arrow Functions
    • Rhythm Game Example
  • 🔌Shameless Plug
  • 🥧Implicit Return
    • Platform Game Example
  • 🍦String Methods
    • GRID Game Example
  • 🍨Object Literals
    • Board Game Example
  • 🍧DynamicProperty
    • Political Game Example
  • 🍡Reading Dynamic Property
    • Hide & Seek Game
  • 🥮Objects Continued
    • Medieval Game Example
  • 🥠Object Shorthands
    • Trivia Game example
  • 🔌Shameless Plug (again)
  • 🍥Destructuring & Concatenation
    • Dig a hole game example
  • 🍏Optional Chaining
    • Action Game Example
  • 🍐Nullish coalescing operator
    • Adventure Game Example
  • 🍊Refactoring If Conditions
    • Arcade Game Example
  • 🍋Implicit Conversion & Falcy Values
    • Strategy Game Example
  • 🍌Arrays of objects
    • Sports Game Example
  • 🍉Transforming Array of Objects
    • Fighters Game Example
  • 🍇Some important array methods
    • FPS Example
  • 🫐Reducing arrays of objects
    • Third Person Shooter Example
  • 🍓Try....catch
    • Platformer Example
  • 🍈Immutability
    • Puzzle game example
  • 🍒Creating new arrays or objects
    • Racing Game Example
  • 🔌Shameless Plug (again)
  • 🍑Immutable object operations
    • Basics
    • Rhythm Game Example
  • 🥭Classes
    • Basics
    • Platformer Game Example
  • 🍍Instance Method
    • Basics
    • Role-playing game example
  • 🥥Object Oriented Programming
    • Basics
    • Stealth Game Example
  • 🥝Getters & Setters
    • Basics
    • Survival Game Example
  • 🍅Static Methods & Chaining
    • Basics
    • Tactical Role Playing Game
  • 🍆Class Inheritance
    • Tower Defense Game Example
  • 🥑Use of Super
    • Vehicular Combat Game example
  • 🫒Public Class Field
    • MMORPG Example
  • 🥦Private class fields
    • Battle Royale Games Example
  • 🥬Aysnc/Await
    • Collectible Card Game example
    • Video Board game example
  • 🫑SetTimeout
    • Dice game example
  • 🥒Execution Order
    • Digital Collectible Card Game example
  • 🌶️The callback pattern
    • Life Simulation Game example
  • 🌽Promises
    • Music Game Example
  • 🥕Writing a function that returns a promise
    • Party game example
  • 🧄Introduction to JSON
    • Tile based game example
  • 🧅JSON.parse(string) / JSON.stringify(object)
    • Rhythm action game example
  • 🍠JSON Example for a game
    • Fetching JSON game data
  • 🥐Handling fetch errors
    • Fetch and HTTP Requests
  • 🥯ES Modules
    • Tower Defence Game Example
  • 🍞Default Export
    • Strategy Adventure Game Example
  • 🥖Fetch Wrapper
    • Strategy Role-playing game example
  • 🔌Final Shameless Plug
  • 🫓Lexical Scope and Arrow Functions
    • Vehicular Combat Game Example
  • 🥨Passing Functions
    • Vehicular simulation game example
  • 🥚Dynamic Imports
    • Video card game example
  • 🍠What is a closure
    • Video casino game example
  • 🎆Congratulations
Powered by GitBook
On this page

Destructuring & Concatenation

Object destructuring is a feature of JavaScript that allows you to extract values from an object and assign them to variables. It allows you to extract a specific set of properties from an object and create variables for them.

Here's an example of using object destructuring to extract the name and age properties from an object:

const person = { name: 'John', age: 30 };

const { name, age } = person;

console.log(name);  // 'John'
console.log(age);   // 3a

In this example, the const { name, age } = person; line uses object destructuring to extract the name and age properties from the person object and create variables for them. The variables name and age are then set to the values of the corresponding properties in the person object.

Object destructuring is often used in combination with function arguments to more easily access specific properties of an object. For example:

function greet({ name, age }) {
  console.log(`Hello, my name is ${name} and I am ${age} years old.`);
}

greet(person);  // "Hello, my name is John and I am 30 years old."

Object concatenation is the process of combining two or more objects into a single object. This can be useful when you want to create a new object that contains properties from multiple objects.

In JavaScript, you can use the spread operator (...) to concatenate objects. The spread operator allows you to spread the properties of an object out into a new object.

Here's an example of using the spread operator to concatenate two objects:

const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };

const obj3 = { ...obj1, ...obj2 };

console.log(obj3);  // { a: 1, b: 2, c: 3, d: 4 }

In this example, the obj3 object is created by spreading the properties of the obj1 and obj2 objects into a new object. The resulting object contains all the properties of both obj1 and obj2.

You can also use the spread operator to concatenate multiple objects at once. For example:

const obj4 = { e: 5, f: 6 };

const obj5 = { ...obj1, ...obj2, ...obj4 };

console.log(obj5);  // { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }

In this example, the obj5 object is created by spreading the properties of all three objects: obj1, obj2, and obj4. The resulting object contains all the properties of all three objects.

Imagine we have a game where players can build and upgrade different types of structures, such as barracks, farms, and mines. Each structure has its own set of properties, such as cost, production rate, and hit points.

We could represent each structure as an object, with its properties as key-value pairs. For example, here's an object for a basic farm:

const farm = {
  name: 'Farm',
  cost: 100,
  productionRate: 10,
  hitPoints: 50
};

Now let's say we want to create an upgraded version of the farm, called the "Advanced Farm". We could create a new object for the advanced farm, but it would be more efficient to use object concatenation to create the advanced farm object based on the basic farm object. We can do this using the spread operator:

const advancedFarm = {
  ...farm,
  name: 'Advanced Farm',
  cost: 150,
  productionRate: 15,
  hitPoints: 75
};

The advancedFarm object is created by spreading the properties of the farm object into a new object, and then adding or modifying a few properties to create the upgraded version. The resulting object has all the properties of the farm object, plus the additional properties for the upgraded version.

Now let's say we want to create a function that calculates the total cost to build and upgrade a given number of farms. We can use object destructuring to easily access the cost properties of the basic and advanced farm objects:

function calculateTotalCost(numFarms, numAdvancedFarms) {
  const { cost: basicCost } = farm;
  const { cost: advancedCost } = advancedFarm;
  return (numFarms * basicCost) + (numAdvancedFarms * advancedCost);
}

console.log(calculateTotalCost(5, 2));  // 1000

In this example, the calculateTotalCost() function uses object destructuring to extract the cost properties from the farm and advancedFarm objects and assign them to variables. The function then uses these variables to calculate the total cost to build and upgrade the specified number of farms.

PreviousShameless Plug (again)NextDig a hole game example

Last updated 2 years ago

🍥