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.

phuzi
  • 12,078
  • 3
  • 26
  • 50
cxFaust
  • 55
  • 4
  • `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) – Doug Mar 20 '18 at 12:59
  • To test if a variable is undefined: `if(typeof form === "undefined")` – Damien Mar 20 '18 at 13:02
  • Possible duplicate of [Detecting an undefined object property](https://stackoverflow.com/questions/27509/detecting-an-undefined-object-property) – madhead Mar 20 '18 at 14:21

2 Answers2

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) {
Jeff Clayton
  • 7,053
  • 1
  • 31
  • 36
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"
});
phuzi
  • 12,078
  • 3
  • 26
  • 50