Randy
Randy

Reputation: 329

Javascript return value position

I am learning javascript and I found this code sample

function validateForm() {
  var x = document.forms["myForm"]["fname"].value;
  if (x == null || x == "") {
    alert("Name must be filled out");
    return false;
  }
}

I would like to know if this is the same as the code below where I moved the return value below the if condition?

function validateForm() {
 var x = document.forms["myForm"]["fname"].value;
 if (x == null || x == "") {
    alert("Name must be filled out");        
 }
 return false;
}

Upvotes: 0

Views: 192

Answers (2)

Jeroen
Jeroen

Reputation: 63719

No, it's not. If a return statement is missing from a function, you should treat it as if the last line is:

return undefined;

So, version one:

function validateForm() {
  var x = document.forms["myForm"]["fname"].value;
  if (x == null || x == "") {
    alert("Name must be filled out");
    return false;
  }
  return undefined;
}

Version two:

function validateForm() {
  var x = document.forms["myForm"]["fname"].value;
  if (x == null || x == "") {
    alert("Name must be filled out");        
  }
  return false;
}

Upvotes: 2

Quentin
Quentin

Reputation: 943510

No.

Unsurprisingly, moving the return false outside the conditional block means you have changed it to always return false.

You haven't provided the context of how the function is called, but the most likely effect of this is to change the behaviour from:

If the field isn't filled out, show an alert and stop the form from submitting. Otherwise, submit the form.

to

If the field isn't filled out, show an alert and stop the form from submitting. Otherwise, still stop the form from submitting. Just never submit the form under any circumstances.

Upvotes: 2

Related Questions