javascript array first item code example
Example 1: javascript take first element of array
const array = [1,2,3,4,5];
const firstElement = array.shift();
// array -> [2,3,4,5]
// firstElement -> 1
Example 2: get first element of array javascript
// Method - 1 ([] operator)
var arr = [1, 2, 3, 4, 5];
var first = arr[0];
console.log(first);
// Method - 2 (Array.prototype.shift())
var arr = [1, 2, 3, 4, 5];
var first = arr.slice(0, 1).shift();
console.log(first);
// Method - 3 (Destructuring Assignment)
var arr = [1, 2, 3, 4, 5];
const [first] = arr;
console.log(first);
Example 3: js get first item from array
var colors = ["red", "green", "blue"];
var red=colors.shift();
//colors is now ["green","blue"];
Example 4: how to remove first element of array in javascript
let numbers = ["I'm Not A Number!", 1, 2, 3];
numbers.shift();