Arrays & array methods
Computer Science · JavaScript
Question 1 of 10
0What does this JavaScript code log? const a = [2, 3, 6]; console.log(a.length)
Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.
How to type your answer
- Fractions: 3/4. Mixed numbers: 1 1/2.
- Decimals with a point or a comma: 0.75 or 0,75.
- Negative numbers start with a minus: -3/4.
- Percentages need the % sign: 75%.
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Arrays & array methods explained
An array is an ordered list of values, indexed from zero. The first element of scores is scores[0], and the last is scores[scores.length - 1]. JavaScript arrays provide methods that add, remove, search and transform items.
push and pop work at the end of an array, and shift and unshift work at the start. splice inserts or removes items anywhere, and these methods change the original array. map, filter and reduce do not: they return new results.
const scores = [4, 9, 2, 7];
const doubled = scores.map(s => s * 2);
const big = scores.filter(s => s > 5);
const sum = scores.reduce((acc, s) => acc + s, 0);
console.log(doubled, big, sum);
map applies a function to every element and returns an array of the same length. filter keeps the elements for which the function returns true. reduce combines all elements into one value, starting from the initial value 0. includes and indexOf search using strict equality.
Worked example
With scores equal to [4, 9, 2, 7], doubled is [8, 18, 4, 14]. filter keeps 9 and 7, so big has length 2. The reduce gives 4 + 9 + 2 + 7 = 22. The original scores array is unchanged.
What you will practise
New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.
Example questions
Easy
What does this JavaScript code log? const a = [8, 1, 3]; console.log(a.length)
Medium
What does this JavaScript code log? const a = [4, 9, 2]; console.log(a[2])
Hard
What does this JavaScript code log? const a = [4, 2, 8, 6]; console.log(a.map(x => x * 2).reduce((s, x) => s + x, 0))