/  Technology   /  Array Coping in JavaScript
f3

Array Coping in JavaScript

 

We’ll learn how to copy an array in JavaScript. On an array, there are two types of copies that can be made.

  • Deep copy
  • Simple copy

In JavaScript, arrays are simply objects with attributes and functions. An array is only superficially replicated when it is assigned directly to another variable. This means that it only refers to the array, rather than copying all of its elements.

Array Copy.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Array Coping</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="array_coping.css">
</head>
<body>
    <h1><b>Please Inspect and check on console to get Results</b></h1>
    <script>
       const originalArray=["A","B","c"];
       const newArray=[...originalArray];
       newArray[0]="Apple";
       console.log(originalArray); //["A","B","c"];
       console.log(newArray);//["Apple","B","c"];
       const originalArray1=["A","B","c"];
       const badCopy=originalArray1;
       badCopy[0]="Apple";
       console.log(originalArray1);//["Apple","B","c"]
       console.log(badCopy);["Apple","B","c"]
    </script>
</body>
</html>

In the first method we are using the […] spread operator which copies the previous array and assigning the copied array to a new variable, Therefore it makes changes on the copied array and does not manipulate the original array.

In the second method, we are referring the original array to a new variable, thus changes made will be affected to the original array.

array_coping.css

*{
    margin: 0px;
    padding:0px;
}
body{
    background-image: url('arraycopy.jpg');
    background-repeat: no-repeat;
    width:100%;
    background-size: cover;
    margin-top: 18%;
    margin-left: 27%;
}

Output:

f4

Console:

f5

 

Leave a comment