imjustaguy
imjustaguy

Reputation: 43

How to apply conditional return statement in JavaScript

I have this html input:

Rows: <input type="text" class="rows" onkeypress="return isNumber(event)"><br>

and this javascript function to validate only numbers

function isNumber(evt) {
  evt = (evt) ? evt : window.event;
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
      return false;
  }
  return true;
}

but i want to work with micro-branching to do something like this:

function isNumber(evt){
  evt = evt || window.event;
  var charCode = evt.which || evt.keyCode; 
  (charCode > 31 && (charCode < 48 || charCode > 57)) && return false;
  return true;
}

the thing is that the last 2 lines didnt work.

Upvotes: 1

Views: 5099

Answers (2)

Siguza
Siguza

Reputation: 23840

return is a statement rather than an expression, and thus cannot be used as argument to a logical operator.

In your case however, the last two lines can be rewritten into a single return statement, by simply inverting the condition to the if clause:

return !(charCode > 31 && (charCode < 48 || charCode > 57));

Or, as zerkms notes, you can lose the ! by flipping the operators (&& <=> || and < <=> >=), which, in my humble opinion, increases readability:

return charCode <= 31 || (charCode >= 48 && charCode <= 57);

Upvotes: 3

Ash
Ash

Reputation: 2585

According to your description, it looks like you are looking for conditional check and return :

function isNumber(evt){
  evt = evt || window.event;
  var charCode = evt.which || evt.keyCode; 
  return !(charCode > 31 && (charCode < 48 || charCode > 57));
}

Upvotes: 1

Related Questions