1

I'm trying to create a ternary expression that decides what to do if the user enters a name or not. If the user enters a name — like 'Jane' — use string interpolation to log Hello, Jane! to the console. Otherwise, simply log Hello!. I don't want to hard code Jane to check for truthiness, rather be able to input any name and be able to print out the same. Any input is much appreciated.

    let userName = '';

    userName === true ? console.log(`Hello, ${userName}!`) : console.log('Hello!');
  • `userName.length > 0` ? – David Jul 30 '21 at 12:17
  • 2
    What do you mean with `I don't want to hard code Jane to check for truthiness`? And why don't you use `userName ? console.log(\`Hello, ${userName}!\`) : console.log('Hello!');`? – t.niese Jul 30 '21 at 12:20
  • Btw. what is the reason that you want to use a _ternary expression_? There are only rare occasions when ternary expressions should be used, in most cases they make the code hard to read and understand. – t.niese Jul 30 '21 at 12:21
  • That worked! Got what you meant @Yoshi thanks a ton. – helloworldio Jul 30 '21 at 12:23
  • @t.niese Gotcha. Been doing a course on Codecademy and this one was one of the problem sets. – helloworldio Jul 30 '21 at 12:25
  • @helloworldio I don't know Codecademy but if it teaches you things like `userName ? console.log(\`Hello, ${userName}!\`) : console.log('Hello!');` without mentioning that this is a really bad coding style, then I would be concerned that it is not a good site, for learining. – t.niese Jul 30 '21 at 12:29
  • As soon as you start to have other operators or many tokens in between the `?` and then `:` like `(`, `)`, `.`, … and the expression between `?` and `:` or after the `:` get really long it is hard to see what belongs to the ternary, and what isn't. And that is horrible for code reviews and maintainability. – t.niese Jul 30 '21 at 12:33
  • @t.niese Codecademy seems very legit. They seem to explain the concepts well. However, I'll keep what you said in mind. Thanks for your input. – helloworldio Jul 30 '21 at 12:37
  • @helloworldio There are always some smaller parts that can become pitfalls are make code inconsistent. E.g. they show this [Truthy and Falsy Assignment](https://www.codecademy.com/courses/introduction-to-javascript/lessons/control-flow/exercises/truthy-falsy-operators), with this example `let defaultName = username || 'Stranger';`. This is a pattern that widely used, but still problematic and can fail horribly in certain use-cases. If you e.g. have something like `let count = inCount || 1;` and you want to allow also having a count of `0`. Whenever you see _short-hand_ you should be carefull. – t.niese Jul 30 '21 at 12:50

0 Answers0