Reputation: 53
So, I'm writing a code in JS that asks the user for their name and prints the greeting in the console. If a user clicks 'cancel' that is the value stored in the variable 'name' is null, the code should return "You didn't give a name". Instead, it prints "Hello, null" which is weird.
var name = prompt("what's your name?");
function hello(name) {
if ((name == null) || (name == "")) {
console.log('you didn\'t give me a name')
} else {
console.log(`Hello, ${name}!`);
}
}
hello(name);
expected: "you didn't give a name"
result : "Hello, null"
Upvotes: 1
Views: 133
Reputation: 21
var name = null;
function hello(name){
if ((name == 'null') ||( name == "")){
console.log('you didn\'t give me a name')
}
else {
console.log(`Hello, ${name}!`);
}
}
hello(name);
Upvotes: 2
Reputation: 3316
name is a string here, whose value is "null" and not null, If you fix the check to name == "null", you should get your desired result
Upvotes: 1