Reputation: 135
I'm getting two different results depending on if I log the results inside the function vs returning it and logging the variable and I don't understand why. Shouldn't they be the same?
const collectionMap = {
'615679ba94212894224f547c': 'Value One',
'615679ba94212894224f5480': 'Value Two',
'615679ba94212894224f5482': 'Value Three',
'615679ba94212894224f5486': 'Value Four',
'615679ba94212894224f548a': 'Value Five',
'615679bb94212894224f548e': 'Value Six',
}
let id = '615679bb94212894224f548e'
// this will log the key
const collection = Object.keys(collectionMap).find((key) => {
if (key === id) return collectionMap[key];
});
console.log(collection);
// this will log the value
const collection2 = Object.keys(collectionMap).find((key) => {
if (key === id) console.log(collectionMap[key]);
});
Upvotes: 0
Views: 988
Reputation: 176
in the 1st statement, the function saved the key to "collection" but in the 2nd statement the function didn't save the value, instead of this it logged it's value
if you write this in console:
const collection3 = Object.keys(collectionMap).find((key) => {
console.log(key);
});
JS will loop on collectionMap Keys and log it
but to make it clear, if wrote this in console:
console.log(collectionMap["615679bb94212894224f548e"])
JS will log "Value Six", that's because JS Searched on "615679bb94212894224f548e" in collectionMap to fined its value
so if you write this code:
const collection4 = Object.keys(collectionMap).find((key) => {
console.log(collectionMap[key]);
});
this what will happened behide the scenes:
Upvotes: 1
Reputation: 13245
.find
will return the element in the array (the array of keys) where the value of the callback function is truthy. So it really returns the key
.
The value you're console.log
ging is the value
.
Upvotes: 0
Reputation: 21354
The Array method find
returns the first element for which the iterator returns a truthy value. For the first five values the return value is undefined and for the sixth it return 'Value Six'
(a non-empty string). That non-empty string is coerced into a boolean (try !!'Value Six'
) and the result is true
. Hence that key is returned and that's what you print.
In the second case you are just abusing find
to do what forEach
is meant for.
Upvotes: 3