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

What is the importance of _.initial() function in JavaScript?


_.initial()

_.initial() is a function in underscore.js, which is a library of javascript. This method is used to differentiate the last element of an array from the rest of the elements. This method just ignores the last value of an array.

syntax

_.initial( array, n );

_.Initial() can take 2 parameters. 

array - The method takes the array and gives out all the elements except the last element.

- It is nothing but a number of elements that are to be trimmed from the given array. It is optional.

Example

<html>
<body>
<script 
   src ="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" >
</script>
</head>
<body>
<script type="text/javascript">
   document.write(_.initial([1,2,3,4,5]));
</script>
</body>
</html>

Output

1,2,3,4


If we provide the second parameter i.e a value(number), then the method _.initial() receives that value and trims those number of elements from the array from right to left and displays the remaining elements.

Example

In the following example, 4 is provided as the second parameter so 4 elements will be trimmed and the remaining elements will be displayed. Here since there are 5 elements in the array and the number that is passed as the second parameter is 4, after trimming the elements only 1 element is displayed as shown in the output.

<html>
<body>
<script 
   src ="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" >
</script>
</head>
<body>
<script type="text/javascript">
   document.write(_.initial([1,2,3,4,5],4));
</script>
</body>
</html>

Output

1