Modifying Arrays
Part of the Fundamentals section of Coddy's JavaScript journey — lesson 59 of 77.
In addition to accessing the elements of an array, you can also modify them. To modify a specific element in an array, you can assign a new value to it using its index.
Here's an example:
let myArray = ["apple", "banana", "cherry"]
myArray[1] = "orange";
console.log(myArray);Output:
["apple", "orange", "cherry"]banana was changed to an orange
Challenge
EasyCreate a function named changeElement that receives 3 arguments:
- First argument is an array
- Second argument is an index
- Third argument is a new element
The function will return the modified array by changing the element in an index that is stored in the second argument with the value in the third argument.
For example, with the following arguments: changeElement<strong>(</strong>[1, 2, 3], 0, 9) the function will return [9, 2, 3]
Cheat sheet
To modify an array element, assign a new value using its index:
let myArray = ["apple", "banana", "cherry"];
myArray[1] = "orange";
console.log(myArray); // ["apple", "orange", "cherry"]Try it yourself
function changeElement(arr, index, newElement) {
// 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