-3

I’m trying to write a ‘welcome’ function that takes a parameter (‘language’) and returns a greeting in that language from the database. For example, if the user types ‘Spanish’,“Bienvenido” is returned. If the language is not in the database, ‘Welcome’ is returned.

I have done a for-in loop with an if condition of ‘greetings == language’ which produces the desired result for those languages in the database.

The problem is when I add an else condition for the ‘undefined’ languages, my else condition ends up overwriting everything.

Can anyone please tell me where I’m going wrong?

const greet = language => {
Languages = {
    english: 'Welcome',
    irish: 'Failte',
    italian: 'Benvenuto',
    latvian: 'Gaidits',
    lithuanian: 'Laukiamas',
    polish: 'Witamy',
    spanish: 'Bienvenido',         
    swedish: 'Valkommen',
    welsh: 'Croeso'    
}



for (let greetings in Languages) {
    if (greetings == language) {
     return Languages[greetings]
    }
    else {
      return 'Welcome'
    }
}
}

What I want to produce is this

console.log(greet('swedish')) // Output: 'Valkommen'
console.log(greet('welsh')) //  Output: 'Croeso'
console.log(greet('chinese')) // Output: 'Welcome' (not in the database)

But instead, I get this

console.log(greet('swedish')) // Output: 'Welcome'
console.log(greet('welsh')) //  Output: 'Welcome'
console.log(greet('chinese')) // Output: 'Welcome' 

Hovercraft Full Of Eels
  • 280,125
  • 25
  • 247
  • 360
TrainXIII
  • 1
  • 1
  • 1
    You're unconditionally returning in one of the branches on the first iteration. Return outside of the loop - or even better, remove the loop entirely and just check if the property exists – CertainPerformance May 20 '22 at 00:57
  • I have removed the [tag:java] question tag from this question -- The Java programming language does not appear to be relevant to this question. – Hovercraft Full Of Eels May 20 '22 at 00:58
  • 1
    Code should just be `const Languages = { .... }; const greet = language => Languages[language] || Languages['english'];` There is no reason to Loop, you just look it up by the key. – epascarello May 20 '22 at 01:03

0 Answers0