I am having a problem with my code.
I am trying to get console.log to print name of person when the name is entered or to print “Anonymous” when the name is not entered. I can get the console to log Hello “Name” or Hello Anonymous, but I cannot get the if… else statement to work with the second line and it only prints “Anonymous asked” regardless of whether or not a name is entered. Probably something silly that I am missing but I can’t find it. Any suggestions would be appreciated. Below is my code
Hi, regarding this section (I made it a bit more readable):
if(userName = 'true') {
console.log(`Anonymous asked: ${userQuestion}`);
}
else {
console.log(`${userName} asked: ${userQuestion}`);
}
In your if
condition, you have only one equal sign, which is used for assigning values to a variable, not testing equality in a condition. When you want to test equality you should use double equals (value comparison) or triple equals (value and type comparison). But in your case, I would omit the comparison entirely and just write: if (userName)
, which checks if the item is truthy and has a value. more info here.
Even if the condition is fixed, it seems like you’re logging “Anonymous” when the condition is true (when userName
has a value) instead of logging “${userName}”. The block of code inside the if
should be in the else
section and vice versa.
Thanks for the reply… my code works now! I now understand better, the difference between = & ===