Arrays, Objects and Classes
Array Methods
| Method | Does | Mutates? |
|---|---|---|
| push / pop | Add / remove at end | Yes |
| unshift / shift | Add / remove at start | Yes |
| splice | Insert / remove anywhere | Yes |
| slice | Copy a portion | No |
| map / filter / reduce | Transform / select / combine | No |
| find / includes / indexOf | Search | No |
| sort | Sort (as strings by default!) | Yes |
console.log([10, 9, 1, 100].sort());
console.log([10, 9, 1, 100].sort((a, b) => a - b));
[ 1, 10, 100, 9 ]
[ 1, 9, 10, 100 ]
Objects, Destructuring and Spread
const student = { name: "Meera", roll: 12, branch: "CSE" };
const { name, ...rest } = student; // destructuring
const updated = { ...student, roll: 15 }; // spread copy
console.log(name, rest);
console.log(updated);
console.log(Object.keys(student), JSON.stringify(student));
Meera { roll: 12, branch: 'CSE' }
{ name: 'Meera', roll: 15, branch: 'CSE' }
[ 'name', 'roll', 'branch' ] {"name":"Meera","roll":12,"branch":"CSE"}
Classes
class Animal {
#sound; // private field
constructor(name, sound) { this.name = name; this.#sound = sound; }
speak() { return this.name + " says " + this.#sound; }
}
class Dog extends Animal {
constructor(name) { super(name, "woof"); }
fetch() { return this.name + " fetches the ball"; }
}
const d = new Dog("Bruno");
console.log(d.speak());
console.log(d.fetch());
Bruno says woof
Bruno fetches the ball
Track your progress through the JavaScript course