JavaScript Program to change the Value of an Array Elements
Last Updated :
07 Nov, 2023
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.
An item can be replaced in an array using the following approaches:
Method 1: Accessing Index
To 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.
Javascript
let colors = [ "red" , "green" , "blue" ];
colors[1] = "yellow" ;
console.log(colors);
|
Output
[ 'red', 'yellow', 'blue' ]
Method 2: Using Array Methods
JavaScript 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.
Javascript
let fruits = [ "apple" , "banana" , "cherry" ];
fruits.splice(1, 1, "orange" );
console.log(fruits);
|
Output
[ 'apple', 'orange', 'cherry' ]
Method 3: Using fill() method
The 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= [ ]
// startIndex(inclusive) and endIndex(exclusive)
arr.fill (element ,startIndex,endIndex);
console.log(arr);
Example: In this example, we will see how to change the value of array elements by using fill( ) method.
Javascript
let arr= [ "HTML" , "REACT" , "JAVASCRIPT" , "NODEJS" ];
arr.fill( "MONGODB" ,3,4 )
console.log(arr);
|
Output
[ 'HTML', 'REACT', 'JAVASCRIPT', 'MONGODB' ]
Share your thoughts in the comments
Please Login to comment...