Array Methods Part 1
Part of the Fundamentals section of Coddy's JavaScript journey — lesson 60 of 77.
Arrays are packed with many methods (functionalities). To access a method, write:
someArray.method()Here is a list of the basic methods:
push(element)- adds an element to the end of the arraypop()- removes an element from the end of the array and returns it
shift(element)- removes an element from the beginning of the array and returns itunshift(element)- adds an element to the beginning of the array
Here is an example of how to use the push method:
let myArray = ["orange", "banana", "apple"];
myArray.push("strawberry");
console.log(myArray);This will output ["orange", "banana", "apple", "strawberry"].
Example of the pop method:
let myArray = [1, 2, 3, 4, 5];
let lastElement = myArray.pop();
console.log(myArray);
console.log(lastElement);This will output [1, 2, 3, 4] and 5.
Example of the shift method:
let myArray = [1, 2, 3, 4, 5];
let firstElement = myArray.shift();
console.log(myArray);
console.log(firstElement);This will output [2, 3, 4, 5] and 1.
Example of the unshift method:
let myArray = [1, 2, 3, 4, 5];
myArray.unshift(0);
console.log(myArray);This will output [0, 1, 2, 3, 4, 5].
Challenge
EasyCreate a function named swapEnds that receives one argument:
- An array
The function swaps the first and the last elements of the array and returns the modified array.
For example with the following arguments: swapEnds([1, 2, 3, 4]) the function will return [4, 2, 3, 1]
Cheat sheet
Arrays have methods to add and remove elements:
push(element)- adds an element to the end of the arraypop()- removes an element from the end of the array and returns itshift()- removes an element from the beginning of the array and returns itunshift(element)- adds an element to the beginning of the array
Examples:
let myArray = ["orange", "banana", "apple"];
myArray.push("strawberry"); // ["orange", "banana", "apple", "strawberry"]
let lastElement = myArray.pop(); // returns "strawberry"
let firstElement = myArray.shift(); // returns "orange"
myArray.unshift("grape"); // adds "grape" to beginningTry it yourself
function swapEnds(arr) {
// Write code here
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Type Coercion7Bill Split Calculator
Welcome MessageCalculating The Tip And Total2Variables
NumbersStringBooleanNaming ConventionsEmpty VariablesRecap - Initialize VariablesConstants11Arrays Part 1
Declaring an ArrayAccessing Array ElementsModifying ArraysArray Methods Part 1Array Methods Part 2Recap - Array Processor3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsStrict vs Loose EqualityRecap - Simple Math6Basic IO
OutputOutput with VariablesType Conversion - Part 1Type Conversion - Part 2Recap - Till 120Recap - True or False