Computer >> Computer tutorials >  >> Programming >> Javascript

Array slice() in JavaScript


The JavaScript Array slice() method returns the new array of selected items in a bigger array. It doesn’t change the original array.

Following is the code for the array slice() method −

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .sample {
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>JavaScript Array Slice</h1>
<div class="sample"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to get elements between first and fourth elements
</h3>
<script>
   let fillEle = document.querySelector(".sample");
   let arr = ["H", "E", "L", "L", "O"];
   fillEle.innerHTML = arr;
   document.querySelector(".Btn").addEventListener("click", () => {
      fillEle.innerHTML = arr.slice(1,4);
   });
</script>
</body>
</html>

Output

Array slice() in JavaScript

On clicking the “CLICK HERE” button −

Array slice() in JavaScript