findWaldo using for in loop

I am trying to figure out on how to solve this problem while still going the same route. I have seen includes(), object.key(), etc used online, but I feel my solution gives me exactly what I want, but the ouput insists on adding undefined after in the console. Why is this? How can I fix it?

Challenge Description: Create a function findWaldo that accepts an object and returns the value associated with the key 'Waldo' . If the key 'Waldo' is not found, the function should return 'Where's Waldo?'

// ADD CODE HERE
const DC = {
  'Bruce': 'Wayne', 
  'Harley': 'Quinn'
}
const supernatural = {
  'Sam': 'Winchester',
  'Dean': 'Winchester', 
  'Waldo': 'unknown'
}

let str = ""

const findWaldo = (obj) => {
  for (let key in obj) {
		if (key !== 'Waldo') {
      str = 'Where\'s Waldo?'
    } else {
      str = 'unknown'
    }
  }
  console.log(str)
}

// Uncomment these to check your work!

console.log(findWaldo(DC)) // should log: 'Where's Waldo?'
console.log(findWaldo(supernatural)) // should log: 'unknown' 

I’m just guessing here, but didn’t you said the function should return something?

a console.log is not the same as a return statement

Oh my god, lol ya. That wouldn’t be the first time. Thanks Tez!

I still dont know why it would still add undefined at the end for a console log though. Ideally I want to always just have the value I want logged or returned. Any idea on why that may be?

the first console.log is from inside the function:
console.log(str)

The other log is from the one outside the function:
since the function itself doesn’t return anything then it returns undefined

Also notice that the function should return the value asociated with the key… If you return “unknown”, then you’re not returning the value associated with the key.

For instance if I pass {‘Waldo’: ‘not-unknown’} to your function, your function should return ‘not-unknown’

1 Like

ah right, ok thanks. I think i got it.

// ADD CODE HERE
const DC = {
  'Bruce': 'Wayne', 
  'Harley': 'Quinn'
}
const supernatural = {
  'Sam': 'Winchester',
  'Dean': 'Winchester', 
  'Waldo': 'unknown'
}

let str;

const findWaldo = (obj) => {
  for (let key in obj) {
		if (key !== 'Waldo') {
      str = 'Where\'s Waldo?'
    } else if (key === 'Waldo') {
			return obj[key]
    }
  }
	return str
}

// Uncomment these to check your work!

console.log(findWaldo(DC)) // should log: 'Where's Waldo?'
console.log(findWaldo(supernatural)) // should log: 'unknown' 

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.