Lesson 1.6Code~1 h
Code power tools
Destructuring, spread, sorting, the ternary operator and the Math toolbox — the shorthand real ML code is written in.
Module 1 · 0/8 done
Shorthand you’ll see everywhere
Machine-learning code is full of small bits of shorthand. None of them let you do anything new — but they make code much shorter, and you’ll meet them in every example from here on. Let’s learn to read them.
Destructuring unpacks arrays and objects into separate variables. Spread (three dots, ...) does the opposite: it unpacks an array into a list of items — handy for copying, combining, and passing arrays to functions like Math.max that expect separate numbers.
// Destructuring: unpack arrays and objects into variables in one line.
const point = [3, 4]
const [x, y] = point
console.log(x, y)
const house = { size: 120, rooms: 3, price: 250000 }
const { size, price } = house
console.log(size, price)
// Functions often return several things this way:
function minMax(xs: number[]): [number, number] {
return [Math.min(...xs), Math.max(...xs)] // ...xs spreads the array into arguments
}
const [lo, hi] = minMax([4, 9, 1, 7])
console.log(lo, hi)
// Spread also copies and combines arrays and objects:
const a = [1, 2], b = [3, 4]
console.log([...a, ...b, 5])
console.log({ ...house, price: 260000 }) // a copy with one field changed
// Rest parameters collect any number of arguments into an array:
const total = (...nums: number[]) => nums.reduce((s, n) => s + n, 0)
console.log(total(1, 2, 3, 4))
Press Run (⌘/Ctrl + Enter) to see output here.