w3resource

JavaScript: Clone an array

JavaScript Array: Exercise-2 with Solution

Write a JavaScript function to clone an array.

Test Data:
console.log(array_Clone([1, 2, 4, 0]));
console.log(array_Clone([1, 2, [4, 0]]));
[1, 2, 4, 0]
[1, 2, [4, 0]]

Pictorial Presentation:

JavaScript: Clone an array

Sample Solution:

HTML Code:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS array Clone</title>
</head>
<body>
</body>
</html>

JavaScript Code:

var array_Clone = function(arra1) {
 return arra1.slice(0);
    };
console.log(array_Clone([1, 2, 4, 0]));
console.log(array_Clone([1, 2, [4, 0]]));

Sample Output:

[1,2,4,0]
[1,2,[4,0]]

Flowchart:

Flowchart: JavaScript: Display the colors entered in an array by a specific format

ES6 Version:

var array_Clone = arra1 => arra1.slice(0);
console.log(array_Clone([1, 2, 4, 0]));
console.log(array_Clone([1, 2, [4, 0]])); 

Live Demo :

See the Pen JavaScript - Clone an array- array-ex-1 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript function to check whether an 'input' is an array or not.
Next: Write a JavaScript function to get the first element of an array. Passing a parameter 'n' will return the first 'n' elements of the array.

What is the difficulty level of this exercise?



JavaScript: Tips of the Day

JavaScript: semicolon (;)

function nums(a, b) {
  if (a > b) console.log('a is bigger');
  else console.log('b is bigger');
  return;
  a + b;
}

console.log(nums(4, 2));
console.log(nums(1, 2));

In JavaScript, we don't have to write the semicolon (;) explicitly, however the JavaScript engine still adds them after statements. This is called Automatic Semicolon Insertion. A statement can for example be variables, or keywords like throw, return, break, etc.
Here, we wrote a return statement, and another value a + b on a new line. However, since it's a new line, the engine doesn't know that it's actually the value that we wanted to return. Instead, it automatically added a semicolon after return. You could see this as:

return;
a + b;
This means that a + b is never reached, since a function stops running after the return keyword. If no value gets returned, like here, the function returns undefined. Note that there is no automatic insertion after if/else statements!

Ref: https://bit.ly/3jFRBje