Ravvy
Ravvy

Reputation: 199

Function returns undefined when it should return a boolean result

I am trying to have checkNull1 return true but it returns undefined. My understanding is that checkNull2 should work exactly the same way as checkNull1 but instead uses a variable to store the return result. What am I doing wrong?

Thanks.

function checkNull1(obj) {
    return
    (obj.a === null &&
    obj.b === null &&
    obj.c === null)
  ;
}

function checkNull2(obj) {
    var isNull =
    (obj.a === null &&
    obj.b === null &&
    obj.c === null)
  ;

  return isNull;
}

function checkNull3() {
  var nullObj = null;
  return nullObj === null;
}

var object1 = {};
object1.a = null;
object1.b = null;
object1.c = null;

console.log("checkNull1: " + checkNull1(object1));
console.log("checkNull2: " + checkNull2(object1));
console.log("checkNull3: " + checkNull3());

JSFiddle: http://jsfiddle.net/Ravvy/ah8hn2qy/

Upvotes: 1

Views: 140

Answers (2)

Henrik Andersson
Henrik Andersson

Reputation: 47222

You're getting caught in a lexing/parsing "quirk".

In JavaScript there is something called Automatic Semicolon Insertion or ASI for short. Basically what this means is that the JavaScript engine will try and fix your some parts code for you by inserting a ; for you, terminating statements where it can. Statements like return, break, throw and continue will always have a semi-colon inserted when a trailing newline is found by the parser.

Your function is getting caught in this. What the engine really does is this:

function checkNull1(obj) {
    return;
    // Code below will not be used. it's dead.
}

So the fix would be to move the condition up on to the same line as return and more long term fix, even though in this example is not in violation of this, but to remember to always end statements with a semi-colon even though it sometimes is optional.

function checkNull1(obj) {
    return (obj.a === null &&
       obj.b === null &&
       obj.c === null); 
}

Upvotes: 4

Mr_Pouet
Mr_Pouet

Reputation: 4290

Your indentation caused the wrong behavior. Something like this would work:

function checkNull1(obj) {
    return (obj.a === null &&
    obj.b === null &&
    obj.c === null);
}

Be careful with semicolons in Javascript: http://es5.github.io/#x7.9

Upvotes: 1

Related Questions