Reputation: 135
I'm using Node.js, I've made a function that looks like this:
function makeTitleWith(name) {
if (name === null) {
return "Hello, welcome to my app!"
} else {
return "Hello, welcome " + name + "!"
}
}
And when I call it with a variable thats null, it returns "Hello, welcome null!"
. I'm new pretty new to JS, and this is driving me insane. I've also tried ==
instead of ===
but it makes no difference.
Upvotes: 0
Views: 500
Reputation: 657
I would recommend you can modify the above code like this (more like defensive coding) and expect/enforce the caller to send the string value as input param to the function.
if(typeof name == "string"){
return "Hello, welcome " + name + "!";
}
return "Hello, welcome to my app!";
Also note, if the caller is calling the function with null or empty object, in both the cases, typeof operator returns object. So based on your case I don't think that the method was called with null or empty object.
Upvotes: 0
Reputation: 1075249
when I call it with a variable thats null, it returns "Hello, welcome null!"
That means you're not calling it with name
set to null
, you're calling it with name
set to "null"
(or an unlikely second possibility I'll cover later). "null"
is not equal to null
(either ==
or ===
).
Example:
function makeTitleWith(name) {
if (name === null) {
return "Hello, welcome to my app!"
} else {
return "Hello, welcome " + name + "!"
}
}
console.log(makeTitleWith("null"));
// or more likely:
var n = String(null);
console.log(makeTitleWith(n));
You probably want to fix where you're calling it, since that "null"
is probably the result of converting null
to string.
The unlikely second possibility: You're calling it with name
set to an object that, when converted to string, converts to "null"
, like this:
function makeTitleWith(name) {
if (name === null) {
return "Hello, welcome to my app!"
} else {
return "Hello, welcome " + name + "!"
}
}
var n = {
toString() {
return "null";
}
};
console.log(makeTitleWith(n));
I very much doubt that's what's going on.
Upvotes: 2