Arrays
An array is an ordered list in square brackets. Counting starts at 0.
const cities = ["Kathmandu", "Pokhara", "Biratnagar"];
console.log(cities[0]);
console.log(cities.length);
cities.push("Lalitpur");
console.log(cities);
Output:
Kathmandu
3
[ 'Kathmandu', 'Pokhara', 'Biratnagar', 'Lalitpur' ]
Loop over an array with for...of:
const marks = [72, 85, 64, 90];
let total = 0;
for (const m of marks) {
total += m;
}
console.log(total / marks.length);
Output:
77.75
Handy array methods
map makes a new array by changing each item. filter keeps only items that pass a test. The small arrow functions x => ... are explained in the next lesson.
const marks = [72, 85, 64, 90, 38];
console.log(marks.map(m => m + 5));
console.log(marks.filter(m => m >= 60));
Output:
[ 77, 90, 69, 95, 43 ]
[ 72, 85, 64, 90 ]
Objects
An object stores named values (properties) in curly brackets. Use it for one thing described by labels.
const student = { name: "Anita", age: 17, city: "Butwal" };
console.log(student.name);
student.age = 18;
student.grade = "A";
console.log(student);
Output:
Anita
{ name: 'Anita', age: 18, city: 'Butwal', grade: 'A' }
Real programs often use an array of objects:
const students = [
{ name: "Sita", marks: 72 },
{ name: "Ram", marks: 85 },
];
for (const s of students) {
console.log(`${s.name}: ${s.marks}`);
}
Output:
Sita: 72
Ram: 85
Try it yourself
- Make an array of five subjects and print them one per line.
- Use
filterto keep marks of 40 or more. - Create an object for a book and print its title and author.
Next lesson: functions.

Comments
Loading comments…