Arrays
An ordered list of values. Indexes start at 0.
JavaScript
const fruits = ['mango', 'apple', 'banana'];
fruits[0]; // 'mango'
fruits.length; // 3
fruits[1] = 'orange'; // change an item
fruits.push('kiwi'); // add to end
fruits.pop(); // remove from end
fruits.unshift('lime'); // add to start
fruits.shift(); // remove from start
fruits.indexOf('banana'); // position, or -1
fruits.includes('apple'); // true or false
fruits.slice(1, 3); // copy a part
fruits.splice(1, 1); // remove 1 item at index 1
fruits.join(', '); // 'mango, banana'
fruits.sort(); // sorts alphabetically (in place)
fruits.reverse();
// Higher-order methods: very commonly used
const nums = [1, 2, 3, 4, 5];
nums.forEach(n => console.log(n)); // do something for each
const doubled = nums.map(n => n * 2); // [2,4,6,8,10]
const evens = nums.filter(n => n % 2 === 0); // [2,4]
const total = nums.reduce((sum, n) => sum + n, 0); // 15
const found = nums.find(n => n > 3); // 4
// 2D array
const grid = [[1,2],[3,4]];
grid[1][0]; // 3Objects
A collection of key: value pairs (properties). Values can be functions (methods).
JavaScript
const student = {
name: 'Kamal',
age: 21,
courses: ['HTML', 'JS'],
address: { city: 'Negombo', zip: '11500' },
greet() {
return 'Hi, I am ' + this.name; // this = the object
}
};
student.name; // dot notation
student['age']; // bracket notation (use when key is in a variable)
student.address.city; // nested
student.email = '[email protected]'; // add property
delete student.age; // remove property
student.greet(); // call a method
Object.keys(student); // array of keys
Object.values(student); // array of values
Object.entries(student); // array of [key, value]
const { name, courses } = student; // destructuring
const copy = { ...student, age: 22 }; // spread: copy with changesArray of objects is the most common data shape in web apps (products, users, orders):
JavaScript
const products = [
{ id: 1, name: 'Pen', price: 50 },
{ id: 2, name: 'Book', price: 250 }
];
const cheap = products.filter(p => p.price < 100);
const names = products.map(p => p.name);
const totalPrice = products.reduce((s, p) => s + p.price, 0);