Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are the map's key value pairs being inverted when read into the forEach method?

I've only been learning javascript for a couple weeks and this is my first post so apologies if my question isn't very clear. I'm using the forEach method in Map's prototype to loop through a map of streets and their lengths. In the prototype of the Map the key value pairs are correct i.e.:

0: {"amesSt" => 500} key: "amesSt" value: 500)

However, the entries seem to flip when taken as arguments in forEach, meaning the key becomes the value and value becomes the key.

console.log('==============STREET REPORT==============')

// key = 'amesSt', value = 500
const streetLengths = new Map();
streetLengths.set('amesSt', 500);
streetLengths.set('bentonSt', 1200);
streetLengths.set('chaseSt', 750);
streetLengths.set('depewSt', 200);

console.log(streetLengths);

// classify streets
    function streetClass(key, value) {

    if (value < 250) {
        console.log(`${key} Street is classified as small`);
    } else if (value >= 250 && value < 600) {
        console.log(`${key} Street is classified as normal`);
    } else if (value >= 600 && value < 1000) {
        console.log(`${key} Street is classified as big`);
    } else if (value >= 1000){
        console.log(`${key} Street is classified as huge`);
    } else{
        console.log('Normal');
    };  
};

console.log('Size classification:');

//key = 500, value = 'amesSt'
streetLengths.forEach((key, value) => {

    streetClass(key, value);
});

I would like for the key value to be stored in the key variable in the forEach loop and value to be stored in the value variable. I'm currently using VS Code v1.34.0. Thanks in advance for the help!

like image 217
moreLosty Avatar asked Oct 29 '25 04:10

moreLosty


1 Answers

As you can see in the docs: Javascript forEach(), the forEach method receives a callback as first parameter, and this callback could receive three parameters: currentValue, index, array, in this order.

So you are inverting the parameters order. It should be:

streetLengths.forEach((value, key) => {

    streetClass(key, value);
});
like image 80
Pedro leal Avatar answered Oct 30 '25 19:10

Pedro leal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!