Using the JavaScript shift method you can remove the first element from Array. It’s removed zeroeth index element (value) and shifts the values at consecutive indexes down, then returns the removed value.
Note:
- It changes the length of the array and the original array.
Syntax
array.shift()
Return value
It returns removed elements from the array and if the length property is 0 (empty array), undefined is returned.
Example of JavaScript shift method
Let’s see the example how to Remove first element from array JavaScript?
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
arr.shift()
alert(arr);
</script>
</body>
</html>
Output:
Remove array element until array empty
following example, every iteration will remove the next element from an array until it is empty in js.
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
var names = ["Andrew", "Edward", "Paul", "Chris" ,"John"];
while( (i = names.shift()) !== undefined ) {
console.log(i);
}
</script>
</body>
</html>
Output
Q: How to JavaScript get the first element of an array?
Answer: It’s very easy, as you know array index starts from zero, so just get the value of index 0.
array[0]
Here is example get the first element of an array in js.
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
var names = ["Andrew", "Edward", "Paul", "Chris" ,"John"];
alert(names[0])
</script>
</body>
</html>
Output:
Do comment if you have suggestions or questions on this tutorial.
Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version