Magic 8 Ball help

Working on the magic 8 ball problem. The question goes like;

Below this userName variable, 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’ve found a working answer by accident, but I don’t understand why this works and my first attempt didn’t. Can someone explain please?

var userName = '';
userName != false ? console.log(`Hello, ${userName}!`) : console.log('Hello!');

This works to output the username. However, this does not:

var userName = '';
userName = true ? console.log(`Hello, ${userName}!`) : console.log('Hello!');

Are these not the same? I’m confused on the truthy falsy concept, I think. Could someone explain what’s going on?

Thanks!
Trent

Alright so I think I found the issue.

It should be

var userName = '';
userName ? console.log(`Hello, ${userName}!`) : console.log('Hello!');

Here’s my guess. userName isn’t a boolean, it’s a string. So if I put a value in, it can’t equal false. But it will also never equal true because it’s a string if something’s inside those quotes. I think. Still some confusion, but getting there lol.

Hi there,

var userName = 'name';
userName != false ? console.log(`Hello, ${userName}`);

This evaluates to true because != checks if the value is not equal to. Save for the boolean false and an empty variable, all other values will evaluate truthy.

The problem with this is that the single = is checking if userName is set to true.

var userName = true;
userName = true ? console.log(`Hello, ${userName}!`) : console.log('Hello!');

This would log true to the console.

Simply having userName ? is checking if userName is truthy. This works–but if you wanted to make sure that the user is putting in an actual name, use typeof and the == operator. (== checking for equality between the two statements)

var userName = 10;
typeof userName == 'string' ? console.log(`Hello, ${userName}!`) : console.log('Hello!');
//this evaluates as false as typeof userName is 'number'

var userName = 'name';
typeof userName == 'string' ? console.log(`Hello, ${userName}!`) : console.log('Hello!');
//this evaluates as true as typeof userName is now 'string'

There’s a lot going on, but does this make sense?

1 Like

Holy cow dude. Yeah, that makes a ton of sense. I’m new to this whole thing, I played with Python for a while, but I’m having a bunch more fun with JS.

Thank you so much lol

1 Like