I prefer B, if only because it is a one to one mapping of cases to output - when reading the function it says:
When function is called
If val is a string, then return 'A'
If val is null or undefined, then return 'B'
Return val otherwise
This is a much more human way of thinking about the possibilities. I don't tend to think in terms of if/else conditions in the real world and I don't feel like much business logic works that way either. Option B is also easier to extend - if later you need to add an "if val is a number, return val.toString" or the like, then that is easy and you can add it wherever it makes sense in your code.
Slightly unrelated, but I also really perfer this style to switch statements. They have a place, but most times they should probably be multiple if statements.
@wuz
Well said, and I totally agree on the switch statements piece. I'm not sure I've ever been satisfied with the look/readability of a switch statement in JS!
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I prefer B, if only because it is a one to one mapping of cases to output - when reading the function it says:
This is a much more human way of thinking about the possibilities. I don't tend to think in terms of
if/else
conditions in the real world and I don't feel like much business logic works that way either. Option B is also easier to extend - if later you need to add an "if val is a number, returnval.toString
" or the like, then that is easy and you can add it wherever it makes sense in your code.Slightly unrelated, but I also really perfer this style to switch statements. They have a place, but most times they should probably be multiple if statements.
@wuz Well said, and I totally agree on the switch statements piece. I'm not sure I've ever been satisfied with the look/readability of a switch statement in JS!