JavaScript Answers

How to Get the Last Value Inserted into a JavaScript Set?

Spread the love

To get the last value inserted into a JavaScript set, we can spread the set entries into an array.

Then we can call the pop method on the returned array to return the last entry inserted into the set.

For instance, we can write:

const a = new Set([1, 2, 3]);
const lastValue = [...a].pop();

We create a new set with the Set constructor.

Then we call add to add a new entry into the set.

Next, we spread a set into an array and then call pop to return the last element from the set and remove that entry from the array.

The returned item is assigned to lastValue.

Therefore, from the console log, we see that lastValue is 10.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *