anmarti
anmarti

Reputation: 5143

How to detect if a JS variable is undefined?

// mystring contains dynamic text. Sometimes can be
// null
var a = mystring.split(" ");
var proc = a[0] + " " + a[1];

If a does not contain text, after split proc is undefined. If I try to assing its value to a textbox the result is "undefined":

mytextbox.val(proc);

enter image description here

So I need a way to make that proc has always a value, at least an empty string.

Upvotes: 0

Views: 92

Answers (2)

Bergi
Bergi

Reputation: 664494

var proc = "";
if (mystring !== null) { // omit this if you're sure it's a string
    var a = mystring.split(" ");
    if (a.length > 1) {
        proc = a[0] + " " + a[1];
    }
}

I'm quite sure your proc is not undefined, but the string " undefined".

Upvotes: 2

Xymostech
Xymostech

Reputation: 9850

You can just use

(mystring || " ")

which will evaluate to mystring if it is not null, or " " if it is.

Or, you can just put an if statement around the whole thing:

if (mystring != null) {
    // stuff
} else {
    var proc = "";
}

Upvotes: 2

Related Questions