3

Could someone help me with this code, I'm trying to write a function that takes in a name from an object and returns a name tag : "Hi! I'm [name], and I'm from [country]."

I've tried this code

const GUEST_LIST = {
    Randy: "Germany",
    Karla: "France",
    Wendy: "Japan",
    Norman: "England",
    Sam: "Argentina"
}

function greeting(name) {
  var x = Object.keys(GUEST_LIST);
  const array = Object.keys(GUEST_LIST)
    .map(function(key) {
        return GUEST_LIST[key];
    });
  
  
  var txt ="";
  for (let i in x)
    {
      if (name === x[i])
        {
          txt = "Hi I'm "+x[i] +", and I'm from " +array[i];  
        }
      else
        {
          txt = "Hi! I'm a guest";
        }
      
    }
     return txt;
}
console.log(greeting("Randy"))

but it always returns "Hi! I'm a guest" except when I type Sam,

  • `name === x[i]` why not use `name === i` instead? – evolutionxbox Jun 20 '21 at 00:00
  • I'm using a *for...in* and not *for...of* – Houssem Salem Jun 20 '21 at 00:02
  • When you loop the GUEST_LIST and find Randy, on first iteration the condition is true, then on the other iterations overwrite the txt variable to default value. You have to break the loop inside the name === x[I] condition when you find a match. – cbrr09 Jun 20 '21 at 00:22

4 Answers4

5

Your issue is that your for loop will continue to loop over the other names in your x array even after you have found a name from your array that matches the name you passed into your function. That means on further iterations of your for loop, your else block of your code will run and overwrite the value of txt previously set. That's why "Sam" works, as that's the last name in your x array, and so txt doesn't get overwritten by further iterations of your for loop.

Another thing to note about your code, a for...in loop shouldn't be used to iterate over an array. It can lead to unwanted values being accessed, as it doesn't just loop over the indices of your array, but rather other properties.

With that being said, you're over-engineering your code. Currently, your object stores key-value pairs. The key is the name and the value is the country. For each key in your object, you can access it using bracket-notation:

console.log(GUEST_LIST["Randy"]); // Germany

With that idea in mind, your name variable can be used as the key for your object, which can then be used to obtain the country. If the GUEST_LIST object doesn't contain your key (ie: the value returned by trying to access the key from your object is falsy), then you can return your default "Hi! I'm a guest" text:

const GUEST_LIST = {
  Randy: "Germany",
  Karla: "France",
  Wendy: "Japan",
  Norman: "England",
  Sam: "Argentina"
};

function greeting(name) {
  const country = GUEST_LIST[name];
  if(country)
    return "Hi I'm "+name +", and I'm from " +country; 
  else
    return "Hi! I'm a guest";
}
console.log(greeting("Randy"));
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • if no key found here GUEST_LIST[name] it throw an error undefined. – cbrr09 Jun 20 '21 at 00:34
  • 1
    @cbrr09 If no key is found, then `GUEST_LIST[name]` will not throw an error, it will just evaluate to the value `undefined`, making `country` hold `undefined` (which is treated as a falsy value, making the else part of the block run) – Nick Parsons Jun 20 '21 at 00:39
  • 1
    Yeh I understand, but when I run you code it gives me undefined dunno why. LOL ![Screenshot](https://s2.im.ge/2021/06/20/XSnOp.png) well I'm agree with you mate! cheersss. – cbrr09 Jun 20 '21 at 00:53
  • @cbrr09 Hm, interesting. I'm curious as to what browser you're using and how you're running the code. The browser will output the last result of the code (more info here [Chrome/Firefox console.log always appends a line saying 'undefined'](https://stackoverflow.com/q/14633968)). In this case, the `console.log()` results in `undefined`, so your browser may be showing undefined because of that. However, the console.log() used in the code should output the correct text value. – Nick Parsons Jun 20 '21 at 01:06
1

Since there are no specifications, why there should a for loop, why not make it a bit more simple?

const GUEST_LIST = {
  Randy: 'Germany',
  Karla: 'France',
  Wendy: 'Japan',
  Norman: 'England',
  Sam: 'Argentina'
}

function greeting (name) {
  if (GUEST_LIST[name]) {
    return "Hi I'm " + name + ", and I'm from " + GUEST_LIST[name]
  } else {
    return "Hi! I'm a guest"
  }
}
console.log(greeting('Randy'))
console.log(greeting('The guy from the bus stop'))
ethergeist
  • 599
  • 4
  • 14
0

To appreciate what I mean here is the working version of your code.

for (let i in x)
{
    if (name === x[i])
      {
        txt = "Hi I'm "+x[i] +", and I'm from " +array[i];
        break; // <---- stop the loop here when you find a match
      }
    else
      {
        txt = "Hi! I'm a guest";
      }

  }
   return txt;
}
cbrr09
  • 189
  • 8
0

Simple to read and short:

const GUEST_LIST = {
    Randy: "Germany",
    Karla: "France",
    Wendy: "Japan",
    Norman: "England",
    Sam: "Argentina"
}


function greeting(name){
    return (GUEST_LIST[name]) ? 
     `Hi, I'm ${name} and I'm from ${GUEST_LIST[name]}` : 
     `Hi! I'm a guest`
}


console.log(greeting("Randy"))
aldison
  • 57
  • 3