A array element can be changed by providing new value at specified index value. It changes the value of array element only if its valid index in the array. If the index value is higher than array length it adds new element in the array. If there is any gap in between array length and specified index, it will adds empty element with undefined value in between to fill the array gap.
1
2 let arr = [10, 20, 30];
3
4
5 arr[2] = 40;
6
7
8 arr[5] = 100;
9
10
11
12 for(element of array) {
13 console.log(element);
14 }
In the above example, we have define array with 3 elements. An array element at position 2 is changed with new value 40. It will update the array element with new value. In the second example, we are updating array element at position 5 which is not present in the array. Hence, rather updating array element at position 5, it will add new element in array.
As array length is 3 and we are updating array at position 5, it adds new element at 5 with value 100 and it also adds 2 new element at index 3 and 4 with value undefined.
Compute square of each elements
Compute square of each elements
1 let array = [1, 2, 3, 4, 5];
2
3
4 console.log("Original array : ", array);
5
6
7 for(i = 0; i < array.length; i++) {
8 array[i] = array[i] * array[i];
9 }
10
11 console.log("Square of each elements :", array);
In the above example, an array is define and initialized with number values. An array is iterated using for loop and length property of array. An array elements are re-initialized by computing a square of each elements and printed.
1 Original array : [ 1, 2, 3, 4, 5 ]
2 Square of each elements : [ 1, 4, 9, 16, 25 ]
Convert each elements of string array to uppercase
Convert each elements of string array to uppercase
1 let array = ["Hello", "World", "in", "IOGyan"];
2
3
4 console.log("Original array : ", array);
5
6
7 for(i = 0; i < array.length; i++) {
8 array[i] = array[i].toUpperCase();
9 }
10
11 console.log("Uppercase elements :", array);
In the above example, an array is define and initialized with string literals. An array is iterated using for loop and length property of array. An array elements are re-initialized by converting each string element into uppercase using string method toUpperCase() and printed.
1 Original array : [ 'Hello', 'World', 'in', 'IOGyan' ]
2 Uppercase elements : [ 'HELLO', 'WORLD', 'IN', 'IOGYAN' ]
Related options for your search