.pop() without changing the origianal variable?

Hello, is it possible to sustain a variable the same as it was after using the pop() method?

var i = ["one", "two", "three", "four"]
var n = i.pop()

For example, can the “n” variable be set to the last item of the “i” array without removing that item from the array?

Hey there,

good question!
You can use slice to create a copy:

var i = ["one", "two", "three", "four"];
console.log("before", i);

var n = i.slice().pop();
console.log("after", i); 
// ["one", "two", "three", "four"]

MDN: slice

1 Like

To get the value of the last element in an array, you could access the index array.length - 1.

const nums = [1, 2, 3, 4, 5];
const lastNum = nums[nums.length - 1];

console.log(nums); // [1, 2, 3, 4, 5];
console.log(lastNum); // 5

why not just var n = i.slice(-1)?

Yes, you are right,
I was focused on popping it.

This would return the last value in an array, pop returns only the value.

then add a [0] at the end of it