To get and remove the first element of an array, you can use the shift()
method like this:
const arr = [1, 2, 3, 4];
const firstElement = arr.shift();
console.log(firstElement); // Output: 1
console.log(arr); // Output: [2, 3, 4]
In the above example, the shift()
method is called on the arr
array, which removes the first element (1) and returns it. The updated array is stored in the arr
variable, and the removed element is stored in the firstElement
variable.
If you want to get the first element of an array without removing it, you can use the [0]
syntax like this:
const arr = [1, 2, 3, 4];
const firstElement = arr[0];
console.log(firstElement); // Output: 1
console.log(arr); // Output: [1, 2, 3, 4]
In the above example, we are accessing the first element of the arr
array using the [0]
syntax, which returns the value 1. The original array remains unchanged.