JavaScript - with() method

revision:


Category : array

The with() method of Array instances is the copying version of using the bracket notation to change the value of a given index. It returns a new array with the element at the given index replaced with the given value.

Syntax :

        array.with(index, value)
    

Parameters:

index : Zero-based index at which to change the array, converted to an integer. Negative index counts back from the end of the array — if "index < 0", "index + array.length" is used. If the index after normalization is out of bounds, a "RangeError" is thrown.

value : any value to be assigned to the given index.

Examples:

            
        

Practical examples

example: creating a new array with a single element changed.

code:
                    <div>
                        <p id="with-1"></p>
                        <p id="with-2"></p>
                        <p id="with-3"></p>
                    </div>
                    <script>
                        const arr = [1, 2, 3, 4, 5];
                        document.getElementById('with-1').innerHTML = "array : " + arr;
                        console.log(arr.with(2, 6)); // [1, 2, 6, 4, 5]
                        document.getElementById('with-2').innerHTML = "array.with : " + arr.with(2, 6);
                        console.log(arr); // [1, 2, 3, 4, 5]
                        document.getElementById('with-3').innerHTML = "array : " + arr;
                        
                    </script>
                

example:
code:
                    
                

example:
code: