Profile Lookup: Switch solution

Hello FreeCodeCamp community,

I was wondering whether anyone of you resolved the Profile Lookup challenge using the SWITCH function.

For the past three days I tried to come up with an alternative solution for the IF/ELSE approach, but cannot wrap my head around it.

  var result = "";
  
  for (i = 0; i < contacts.length; i++) {
  
switch (firstName) {
  
  case contacts[i].firstName:    
    switch (prop) {   
      case contacts[i].prop:
        result = contacts[i].prop;
        return result;      
      default:
        result = "No such property";
        return result;
        }
    
  default:
    result = "No such contact";
    return result;
}  
  }

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36.

Link to the challenge:
https://www.freecodecamp.org/challenges/profile-lookup

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

markdown_Forums

1 Like

For me, it’s a matter of convention and readability. When you have a true/false type choice, then if/else is more “logical”. The switch is for when there are multiple possibilities. Does that mean that you can’t use switch here? No, not really. But it is unexpected. If it created a boost in performance or readability or something, then I think you could build and argument. But I don’t see any advantage of nested switch statements over nested if/else statements. To me it has the slight disadvantage of that you are using a tool that we assume would be used for different types of problems, slightly reducing the ability of the coder to read it.

But I understand the desire to try to solve problems in different ways. I just think this isn’t a measurably better solution.

1 Like

Thank you very much for the help and explanation, @kevinSmith!