Programming

JavaScript arrays: push and length

Keep several values in one list, add an item at the end and read the count.

All lessons · JavaScript lessons: learn from scratch

What an array is

An array keeps several values in one variable: names, games, scores. You do not need a separate variable for each.

let meyveler = ["Alma", "Armud", "Banan"];
console.log(meyveler);
// ["Alma", "Armud", "Banan"]

push: add to the end

push() puts an item at the end of the array. The old items stay. One call can add several items.

let oyunlar = ["Minecraft", "Roblox"];
oyunlar.push("GTA", "FIFA");
console.log(oyunlar);
// ["Minecraft", "Roblox", "GTA", "FIFA"]

length and the index

length is the number of items. It is not a method, so there are no parentheses: meyveler.length. The index starts at 0. A missing index returns undefined.

let heyvanlar = ["Pişik", "İt"];
console.log(heyvanlar.length); // 2
heyvanlar.push("Dovşan");
console.log(heyvanlar.length); // 3
console.log(heyvanlar[0]); // Pişik
console.log(heyvanlar[5]); // undefined

Questions

What does push do? It adds a new item at the end of the array.

Can I write length()? No. length is a property, written without parentheses.

Which index is the first item? 0. The second is 1.

What does a missing index give? undefined. The array does not invent an item.

Author: Nibras Code