kman
kman

Reputation: 2257

Javascript returning string on what should be a shorthand boolean test

Can someone explain to me why this returns an empty string ("") instead of a boolean (false)?

var x = "";
alert(x && x.length > 0);

...While this works as expected, returning true:

var y = "abc";
alert(y && y.length > 0);

I am basically just trying to do a simple shorthand check to see if a value exists in a variable (ensuring it's not undefined, null, or empty string).

I know I can do each test individually (x == null, typeof x == 'undefined', x == '') - I'm just trying to understand why Javascript returns a string on what looks to be a boolean test.

Upvotes: 7

Views: 1197

Answers (3)

ajax333221
ajax333221

Reputation: 11764

The conditional operations using the && (AND operator) will stop when:

  • One of the conditions evaluated to false
  • It successfully made it to the end by evaluating everything to true

The result of the conditional operations will be the last evaluated before stopping (not necessarily a boolean)

To force returning a real boolean, you can wrap everything around !!(...), example:

alert(typeof !!(...) === "boolean"); //will always be true no matter what conditions are inside

Upvotes: 0

jcreamer898
jcreamer898

Reputation: 8189

It is returning and empty string because x is already defined, just empty.

This causes the first part of your expression alert(x) to show an empty string.

If you need to check for a null/empty string, try something like this.

String.isNullOrWhiteSpace = function (str) {
    if (typeof str === "string") {
        var isNullOrWhiteSpace = false;

        // Check for null string
        if (str == null || typeof str === "undefined") isNullOrWhiteSpace = true;

        // Check for string with whitespace
        if (str.replace(/\s/g, '').length < 1) isNullOrWhiteSpace = true;

        return isNullOrWhiteSpace;
    }

    if (typeof str === "undefined" || str == null) {
        return true;
    }
};

Upvotes: 0

alex
alex

Reputation: 490263

When a conditional operator in JavaScript is satisfied, it returns the last value evaluated.

var x = "";
alert(x && x.length > 0);

An empty string is falsey, so when you use just x in a condition, it will be false. Because you are using &&, if the LHS is false, then there is no reason to bother checking the RHS. This is short circuit evaluation. Therefore, the last evaluated part, the empty string, is returned to alert().

var y = "abc";
alert(y && y.length > 0);

A non empty string is truthy. So the LHS is true, and because it's an &&, the RHS is evaluated (it needs to be to know if the entire condition is true). The return value of y.length > 0 is true, so that is passed to your alert().

Upvotes: 7

Related Questions