JavaScript/Arrays/Exercises

Topic: Arrays

1. What is the output of the following script?

"use strict"; const x = []; x[1] = 5; console.log(x); x[2] = [, , 42]; console.log(x); 
Click to see solution
[undefined, 5] [undefined, 5, [undefined, undefined, 42]] 



2. Add elements

  • Create an array with all odd numbers that are smaller than 10.
  • Show the array with the alert command.
  • Show how many elements the array contains.
  • Add 2, 4, 6, 8 to the end of the array and show it again.
  • Insert the value 20 on the 20th array element and show the array again.
Click to see solution
"use strict"; // literal notation const arr = [1, 3, 5, 7, 9]; alert(arr); // or: console.log(arr); alert("The array contains " + arr.length + " elements."); // add elements arr.push(2, 4, 6, 8); alert(arr); // one certain element arr[19] = 20; // 19! alert(arr); alert("The array now contains " + arr.length + " elements."); 



3. Remove elements

  • Create an array with all numbers from 1 to 6.
  • Show the array with the alert command.
  • Delete the first and last element and show the resulting array.
Click to see solution
"use strict"; const arr = [1, 2, 3, 4, 5, 6]; alert(arr); // or: console.log(arr); // remove elements const first = arr.shift(); alert("Removed the first element: " + first); alert(arr); const last = arr.pop(); alert("Removed the last element: " + last); alert(arr); 



4. Combine elements

  • Create an empty array.
  • Add 0, 1, 2 to the array with the push method and show the array.
  • Create the string "0 + 1 + 2" out of the array using the join method and show the string.
Click to see solution
"use strict"; const arr = []; arr.push(0); arr.push(1); arr.push(2); alert(arr); const str = arr.join(" + "); alert(str);