Exercises: JavaScript Arrays
Standard Exercises
0. What does the following code do? What do you expect to be printed by the end of the script?
var fruits = ["Apple", "Kiwi", "Peach"];
console.log(fruits[1]);1. Create an array called ‘vegetables’ containing the values: Broccoli, Mushroom, Carrot. After doing so, print it with the following code;
console.log(vegetables); // Should print "Broccoli,Mushroom,Carrot"2. Add the vegetable "Sweetcorn" to the array of vegetables using the ‘push’ method.
console.log(vegetables); // Should print "Broccoli,Mushroom,Carrot,Sweetcorn"3. Sort the vegetables array using the ‘sort’ method and store the sorted array in the same variable.
console.log(vegetables); // Should print "Broccoli,Carrot,Mushroom,Sweetcorn"4. Remove the last element from the vegetables array using the 'pop' method.
console.log(vegetables); // Should print "Broccoli,Carrot,Mushroom"5. Remove the first element from the vegetables array using the 'splice(position, count)' method.
console.log(vegetables); // Should print "Carrot,Mushroom"6. Print out the length of the vegetables array using .length. The result should now be "2".
7. Print out the second element in the vegetables array. This should print out ‘Mushroom’.
Advanced Exercises
8. Create an array called ‘names’ containing the values: Ben, Caroline, David
9. Use the ‘unshift()’ method to add the name "Alex" to the start of the array.
console.log(names); // Should print Alex,Ben,Caroline,David10. Use ‘splice(index, 0, value)’ to insert the name "Emily" into the array after ‘Ben’.
console.log(names); // Should print "Alex,Ben,Emily,Caroline,David11. Use ‘concat’ to append the values in array2 to array1.
var names1 = ["Cecile", "Louis"]
var names2 = ["Tobias", "Robin"]
// use concat to create the array ‘allNames’ by joining names1 and names2 together.
console.log(allNames); // Should print Cecile,Louis,Tobias,Robin12. Write the function firstAndLast(anArray) which returns true if the first and last elements of an array are the same. Note. The function shouldn’t crash if passed an empty array!
console.log( firstAndLast(["Abba", "Korn", "Slipknot"]) ); // Should print false
console.log( firstAndLast(["Abba", "Korn", "Abba"]) ); // Should print true
console.log( firstAndLast([]) ); // Should print false and not crash!console.log("Hello World");