0
// 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.

6
  • I think mytextbox.val(proc || '') would do it. Commented Nov 29, 2012 at 17:06
  • @jAndy if didn't work. It mathes always as undefined Commented Nov 29, 2012 at 17:06
  • @a_maar: if( mystring && mystring.length ) { // all the rest } Commented Nov 29, 2012 at 17:08
  • 1
    @Jack: that would fail because you cannot call split on mystring when mystring is undefined Commented Nov 29, 2012 at 17:10
  • Is mystring really null? I think you mean the empty string. Commented Nov 29, 2012 at 17:10

2 Answers 2

2

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 = "";
}
Sign up to request clarification or add additional context in comments.

1 Comment

not a good usecase for a logical OR here imho. It shouldn't do all the logic if mystring is undef or empty.
2
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".

2 Comments

why negating the logic ? Reads positive much clearer, no ? if( mystring && mystring.length)
@jAndy: You mean the null logic? I'm still not sure whether the OP really has null or just an empty string, so I wanted to make it explicit. Btw, mystring.length is not enought to check to prevent a[1] from being undefined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.