![]() |
In this article, we will learn how to change the value of an array element in JavaScript. Changing an element is done by using various approaches. Changing the value of an array element in JavaScript is a common operation. Arrays in JavaScript are mutable, meaning you can modify their elements after they are created. You may want to change an element’s value based on its index or certain conditions. Table of Content Accessing IndexTo change the value of an array element in JavaScript, simply access the element you want to change by its index and assign a new value to it. Syntax: colors[1] = "yellow"; Example: In this example, we will see how to change the value of array elements by Accessing its Index.
Output [ 'red', 'yellow', 'blue' ] Using Array MethodsJavaScript provides array methods like splice(), pop(), push(), shift(), and unshift(), which can be used to change elements based on specific requirements. Syntax: Array.splice(start_index, delete_count, value1, value2, value3, ...) Example: In this example, we will see how to change the value of array elements by using array methods.
Output [ 'apple', 'orange', 'cherry' ] Using fill() methodThe fill() method in javascript is used to change the content of original array at specific index. It takes three parameter (element,startidx,endidx) Syntax: let arr= [ ] Example: In this example, we will see how to change the value of array elements by using fill( ) method.
Output [ 'HTML', 'REACT', 'JAVASCRIPT', 'MONGODB' ] Using the map() methodThe map() method creates a new array populated with the results of calling a provided function on every element in the calling array. It’s particularly useful when you want to transform each element of the array. Syntax: let newArray = array.map(callback(currentValue[, index[, array]]) Example: In this example, we will see how to change the value of array elements by using the map() method.
Output [ 2, 4, 6, 8, 10 ] Using the forEach() MethodThe forEach() method executes a provided function once for each array element. This method is useful when you want to iterate over an array and change elements based on a specific condition. Unlike map(), which returns a new array, forEach() modifies the original array.
Output [ 1, 4, 3, 8, 5, 12 ] Using the findIndex MethodIn this approach, we use the findIndex method to locate the index of an element that meets a specific condition and then change its value. The findIndex method returns the index of the first element that satisfies the provided testing function, allowing us to directly access and modify the element. Example:
Output [ 1, 2, 10, 4, 5 ] |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |