Using Array.keys() blew my mind.

Featured on Hashnode

Context to why I used Array.keys?

In the eCommerce website, I was building, my goal was to create a select form that held options for the quantity a customer wanted to purchase. The quantity was based on the stock amount of a specific product in which the data type is a number. Btw, I am using react, so the example, in the end, is in JSX.

Screenshot (3).png

What does the method keys() do?

"The keys() method returns a new Array Iterator object that contains the keys for each index in the array."

src: developer.mozilla.org/en-US/docs/Web/JavaSc..

In short, if you have an array, it returns an object which is iterated by the length of the array.

Sounds complicated? Let me just show you then.

How did I use it?

So let's focused on stockAmount for just one product. This example will have stockAmount hardcoded.

const stockAmount = 7 // we only have 7 items in stock for whatever item

Well to run the iterator, keys(), we need an array. So how do we possibly make the stockAmount an array?

simple use the Array() constructor

const stockAmount = 7

const stockInAnArray = [...Array(stockAmount)]
console.log(stockInAnArray)
/*Array [undefined, undefined, undefined, undefined, undefined, undefined, undefined] */

With that, I have an array with a length of 7, the same value as the stockAmount.

The only problem is that everything inside is undefined...

Thats why we call keys()

const stockAmount = 7
const stockInAnArray = [...Array(stockAmount).keys()] 
console.log(stockInAnArray)
/*Array [0, 1, 2, 3, 4, 5, 6] */

Nice! Keys pretty much return the keys for each index in the array. And for our case, it goes from index 0 to index 6, which are the indexes inside an array with a length of 7.

Lastly, map through the array we made.

carbon.png

In my example, I directly did it without defining stockInAnArray. As you can see, I am doing x+1. This is because I don't want to quantity selected to have a 0. That wouldn't make sense. Lastly, the max amount in stock is 7, not 6, therefore x + 1 is equal to 7.

Overall, I like the key() method, and if I have a lot of numbers to iterate through to create an options dropdown for numbers, keys() is the way to go.

Give this a try the next time you are making a select dropdown with options of numbers.

Final Attribution goes to Brad Traversy. I got to discover the keys method from his latest MERN stack course on Udemy.