<aside> 💡

This section is where your code goes from working to clean. These are the tools senior engineers use every day.

</aside>

1. Ternary Operator

A shorter way to write a simple if/else.

// if/else
if (age >= 18) {
  console.log("Adult");
} else {
  console.log("Minor");
}

// ternary — same thing, one line
let status = age >= 18 ? "Adult" : "Minor";
console.log(status);

condition ? valueIfTrue : valueIfFalse

In practice

let balance = 200;
let price = 50;

let result = balance >= price ? "Purchase approved" : "Not enough balance";
console.log(result); // Purchase approved

Mental model: Ternary = a question with two possible answers. Yes or no. Left or right.


2. Destructuring Objects

Pull values out of an object into their own variables.

let student = {
  name: "Ahmed",
  age: 22,
  city: "Oslo"
};

// without destructuring
let name = student.name;
let age = student.age;

// with destructuring
let { name, age, city } = student;

console.log(name); // Ahmed
console.log(age);  // 22
console.log(city); // Oslo

Rename while destructuring

let { name: studentName } = student;
console.log(studentName); // Ahmed

In practice

let order = {
  customer: "Faadumo",
  amount: 500,
  status: "pending"
};

let { customer, amount, status } = order;
console.log(customer + " sent " + amount + " NOK. Status: " + status);
// Faadumo sent 500 NOK. Status: pending

Mental model: Destructuring = unpacking a bag. Instead of reaching in every time, you lay everything out on the table.


3. Destructuring Arrays

Pull values out of an array into their own variables.