dustin
dustin

Reputation: 135

console log shows different value than returning the value

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

Answers (3)

HamzaElkotb
HamzaElkotb

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

enter image description here

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:

  1. collectionMap["615679ba94212894224f547c"] => Value One
  2. collectionMap["615679ba94212894224f5480"] => Value two
  3. collectionMap["615679ba94212894224f5482"] => Value three
  4. collectionMap["615679ba94212894224f5486"] => Value Four
  5. collectionMap["615679ba94212894224f548a"] => Value Five
  6. collectionMap["615679bb94212894224f548e"] => Value Six

Upvotes: 1

Samathingamajig
Samathingamajig

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.logging is the value.

Upvotes: 0

Christian Fritz
Christian Fritz

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

Related Questions