Reputation: 6770
Here's a sample code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button onclick="myFunction();">Click!</button>
<script type="text/javascript">
function myFunction() {
var text = "";
if (text)
{
alert(text);
}
else
{
alert("There's no text!");
}
}
</script>
</body>
</html>
I wonder is there's a difference between if (text) and if (text != "")?
Thanks in advance!
Mike
Upvotes: 0
Views: 54
Reputation: 53291
if(text)
will evaluate to false if text
is a null value, undefined value, 0, an empty string, or false. This is because the if
statement is checking to see if text
is a falsy value (e.g. null, undefined, 0, an empty string, or false).
if(text != "")
checks to see if text
does not equal an empty string. This means that the if statement will evaluate to true if text
is a falsy value other than an empty string.
Upvotes: 1