2

What is the most appropriate way to test if a variable is undefined in JavaScript?

$.ajax({
    type: method,
    url: url,
    success: function (data) {
        if (form != null || form != undefined){
            data = $(form).serialize();
        }
        var json =  JSON.parse(data),
            list = $(table).html(),
            compileTemplate = Handlebars.compile(list),
            result = compileTemplate(json),
            content = doc.getElementById(element);
        content.innerHTML = result;
    },
    dataType: "text"
});

I'm looking for a more beautiful way for this check.

3
  • if( form ) should check if the variable exists and is defined (but I'm sure there are a bunch of edge cases where this may break) Commented Mar 20, 2018 at 12:59
  • To test if a variable is undefined: if(typeof form === "undefined") Commented Mar 20, 2018 at 13:02
  • Possible duplicate of Detecting an undefined object property Commented Mar 20, 2018 at 14:21

2 Answers 2

2

First check if it is undefined before checking the value so it does not throw an error. Also it needs an AND (&&) not an OR (||).

The official way to do that is to check type.

Change the 'if' statement to say this:

if (typeof(form) !== "undefined" && form != null) {
Sign up to request clarification or add additional context in comments.

Comments

0

You could simply test form != null which will be true if form is neither null or undefined.

$.ajax({
    type: method,
    url: url,
    success: function (data) {
        if (form != null){
            data = $(form).serialize();
        }
        var json =  JSON.parse(data),
            list = $(table).html(),
            compileTemplate = Handlebars.compile(list),
            result = compileTemplate(json),
            content = doc.getElementById(element);
        content.innerHTML = result;
    },
    dataType: "text"
});

4 Comments

In this situation, I can not use this method without variable 'form'.
@cxFaust not quite sure what you mean.
If I could use this code, I would check the variable before the method. But I use this code with a variable "form" and without.
The test if (form != null){ will parse the serialised form data if it's not null or undefined. Is that not what you want?

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.