'if'-'else' in JavaScript - javascript

I have a simple if - else construct that operates with data grid filterind. Like this:
if (_r1 <= _r3 && _r3 <= _r2) {
return true;
}
else {
return false;
}
where _r1, _r2, _r3 and numbers. It has both true and false. Is it possible to rewrite this construction that it will has only for example true branch and will go to the else branch by default?
P.S. (if ... ? ... : ...) is not what I want.

Use:
return _r1 <= _r3 && _r3 <= _r2;

if (_r1 <= _r3 && _r3 <= _r2) {
return true;
}
return false;

Related

What is the best way to avoid many if statements?

What is the best and ellegant way for refactoring the following if statements?
if (!this.props.isRequired) {
return false
}
if (items.length < 1) {
return false
}
if (items.length === 1) {
return true
}
Use || to alternate between all conditions that will return the same value:
if (!this.props.isRequired || items.length < 1) {
return false
}
if (items.length === 1) {
return true
}
I think you should handle the case where items.length is > 1, too:
return (this.props.isRequired && items.length === 1);
You can omit the if and just return the boolean true/false value directly.
if (!this.props.isRequired || items.length < 1) {
return false
}
else if (items.length === 1) {
return true
}
You could use a ternary operator:
return !this.props.isRequired ? false : (items.length === 1)
Try using a ternary
this.props.isRequired || items.length < 1 ? return false: null;
items.length === 1 ? return true: null;
It depends how you write business logic !!!
Now in above code you can merge first two if statements in one as both returns same value.
if (!this.props.isRequired || items.length < 1) {
return false
}
if (items.length === 1) {
return true
}
If I were to come across these exact lines during refactoring (or review), I'd immediately look for the next/last return statement, as these lines appear to indicate the function has multiple output types.
Having different return types is something I try to avoid in general.
As for the reduction in if statements; my first step would be to make the if statements conclusive, which seems to come down to answering the question whether items.length would be valid if it's greater than 1.
If so, you can turn it into a single statement.
return this.props.isRequired && items.length >= 1;
If not, you can use the non-conclusive part (> 1) condition (or the inverse, to make it more concise)
if (items.length <= 1) {
return this.props.isRequired && items.length === 1;
}
// the alternative flow (not in your example)

JavaScript Recursion exercise: Unexpected token else

I have read about this error on other threads that mostly ask the user to remove semicolons. This seems to have no effect on my code.
function isEven(number){
if (number > 1)
return isEven(number-2);
else if (number == 1)
return false;
else if (number == 0)
return true;
else if (number < 0)
number *= -1
return isEven(number);
else
return "Error";
}
It seems that this line [number *= -1] is causing the error as if I remove it the code runs with no error except for negative numbers where the stack runs out of memory. What I'm trying to do is to make all numbers positive.
Anyone that would like to help me out?
Solution
function isEven(number){
if (number < 0){
number *= -1
return isEven(number);}
else if (number > 1){
return isEven(number-2);}
else if (number == 1){
return false;}
else if (number == 0){
return true;}
else
return "Error";
}
Short answer: Wrap your codes with {}
if (){
..
..
}else {
..
..
}
Long answer :
else if (number < 0)
number *= -1
return isEven(number);
You are not using {} hence the very next line of the condition only considered as a statement belong to the else if and the later will be treated as general statements.
Since you have 2 lines of code in else if, the link broken there and your else became an orphan. That is the reason you seeing the error. Please wrap up your conditions in {}
function isEven(number){
if (number > 1){
return isEven(number-2);
}
else if (number == 1){
return false;
}
else if (number == 0){
return true;
}
else if (number < 0){
number *= -1
return isEven(number);
}
else{
return "Error";
}
}
Note: Not only to avoid this specific error but to avoid many other weird things always try to use {}. That makes everyones life easy.
Problem is without curly brackets {}
Better you could add {}(curly brackets) on each if and else statement
function isEven(number) {
if (number > 1) {
return isEven(number - 2);
} else if (number == 1) {
return false;
} else if (number == 0) {
return true;
} else if (number < 0) {
number *= -1
return isEven(number);
} else {
return "Error";
}
}
console.log(isEven(-2))
The problem is that you are trying to execute 2 lines of code in the 3rd else if without wrapping it up in curly braces.
By default only single line gets executed when you don't wrap up the block in curly braces.
function isEven(number){
if (number > 1){
return isEven(number-2);
}
else if (number == 1){
return false;
}
else if (number == 0){
return true;
}
else if (number < 0){
number *= -1;
return isEven(number);
}
else{
return "Error";
}
}

If Else Statement Disaster [duplicate]

This question already has answers here:
How does (A == B == C) comparison work in JavaScript?
(6 answers)
Closed 6 years ago.
today I decided I wanted to make a simple js code that would accept a number (in meters), and decide what the appropriate metric unit to use would be. The code turned out to be a little more complicated than I had expected, but I was able to figure out most of the bugs as I found them (even if it meant rearranging all of my code). However, when it came to my if/else statement I could not figure it out. If I put in a number that is less than 1 nothing happens. If I put in a number more than 9 it logs the same thing every time. The structure itself may need some work, but if someone could help me with the if/else statement I would be very thankful. Here is the code (init is called when the body loads):
function init() {
var x = prompt("How many meters?");
convertMetricMeters(x);
function convertDown(x) {
if (0.1 >= x >= 0.99) {
console.log("deci");
}
else if (0.100 >= x >= 0.999) {
console.log("centi");
}
else if (0.1000 >= x) {
console.log("milli");
}
else {
console.log("error");
}
}
function convertUp(x) {
if (1 <= x <= 99) {
console.log("deca");
}
else if (100 <= x <= 999) {
console.log("hecto");
}
else if (1000 <= x) {
console.log("kilo");
}
else {
console.log("error");
}
}
function convertMetricMeters(x) {
if (x < 1) {
convertDown(x);
}
else if (x > 9) {
convertUp(x);
}
else {
console.log("Appropriate Metric Unit");
}
}
}
Use && as AND operator in javascript
Convert these 100 <= x <= 999 to 100 <= x && x <= 999
You could simplify the check a bit and return if a condition is true.
function convertDown(x) {
if (x < 0.01) {
console.log("milli");
return;
}
if (x < 0.1) {
console.log("centi");
return;
}
if (x < 1) {
console.log("deci");
return;
}
console.log("error");
}
Your code has 2 sort of errors. One was simple to fix, that you have to add && between two conditions in if statement.
Now coming to the other part, the less than 1 items. It needed a different logic. Well, your maths seems to be needing bit attention. 0.1 is same as 0.100 and is same as 0.1000
I have updated the code to look for the number of digits after the decimal point and then console.log accordingly.
The updated code will be:
function init() {
var x = prompt("How many meters?");
convertMetricMeters(x);
function convertDown(x) {
// checks the number of digits after decimal point
decimals = (x.split('.')[1] || []).length
if (decimals == 1 || decimals == 2) {
console.log("deci");
}
else if (decimals == 3) {
console.log("centi");
}
else if (decimals == 4) {
console.log("milli");
}
else {
console.log("error");
}
}
function convertUp(x) {
if (1 <= x && x <= 99) {
console.log("deca");
}
else if (100 <= x && x <= 999) {
console.log("hecto");
}
else if (1000 <= x) {
console.log("kilo");
}
else {
console.log("error");
}
}
function convertMetricMeters(x) {
if (x < 1) {
convertDown(x);
}
else if (x > 9) {
convertUp(x);
}
else {
console.log("Appropriate Metric Unit");
}
}
}
Working jsfiddle example: https://jsfiddle.net/w7pf3moL/
A simplified version with only 1 method convert(float x):
function init() {
var x = prompt("How many meters?");
convertMetricMeters(x);
function convert(x) {
if (x < 0.01) console.log("milli");
else if (x < 0.1) console.log("centi");
else if (x < 1) console.log("deci");
else if (x < 10) console.log("meter");
else if (x < 100) console.log("deca");
else if (x < 1000) console.log("hecto");
else console.log("kilo");
}
function convertMetricMeters(x) {
if (x > 0) {
convert(x);
} else {
console.log("Appropriate Metric Unit");
}
}
}
init();

Dynamic condition in IF statement

I want to make condition of if statement dynamically in javascript,
check my code
var t = ['b','a']
if(t[0] !== 'a' && t[1] !== 'a'){console.log('remaining element')}
here t might be vary at any time say t = ['b','a','c'] then I need to write if condition like this
if(t[0] !== 'a' && t[1] !== 'a' && t[2] !== 'a'){console.log('remaining element')}
How can I rewirte this code efficiently?
You can use Array.prototype.every like this
if (t.every(function(currentElement) { return currentElement !== "a"; })) {
console.log('remaining element');
}
This works with arbitrary number of elements.
On older environments which do not support Array.prototype.every, you can use the plain for loop version
var flag = true;
for (var i = 0 ; i < t.length; i += 1) {
if (t[i] === "a") {
flag = false;
break;
}
}
if (flag) {
console.log('remaining element');
}

IsNan() function considers certain kind of strings as number - node js

I'm checking for integer values in node.js using IsNaN function.
Unexpectedly, this function validates the strings like 1E267146, 1E656716 , 914E6583 to be numbers, as these strings are exponential values. Any way to work around this? In actual scenario i wont get any exponential values.
ECMA6 defines Number.isInteger as follows:
Javascript
function isInteger(nVal) {
return typeof nVal === "number" && isFinite(nVal) && nVal > -9007199254740992 && nVal < 9007199254740992 && Math.floor(nVal) === nVal;
}
but this will also accept scientific notation
console.log(isInteger(1e6));
console.log(isInteger(+"1e6"));
jsfiddle
You need to be clear as to what your definitions/expectations are.
My guess is that you may want something like this, if you are testing strings and have no limits on the max or min integer.
Javascript
function isStringNumericalInteger(testValue) {
return typeof testValue === "string" && /^[\-+]?[1-9]{1}\d+$|^[\-+]?0$/.test(testValue);
}
console.log(isStringNumericalInteger("9007199254740991"));
console.log(isStringNumericalInteger("-123216848516878975616587987846516879844651654847"));
console.log(isStringNumericalInteger("1.1"));
console.log(isStringNumericalInteger("-1.1"));
console.log(isStringNumericalInteger("1e10"));
console.log(isStringNumericalInteger("010"));
console.log(isStringNumericalInteger("0x9"));
console.log(isStringNumericalInteger(""));
console.log(isStringNumericalInteger(" "));
console.log(isStringNumericalInteger());
console.log(isStringNumericalInteger(null));
console.log(isStringNumericalInteger([]));
console.log(isStringNumericalInteger({}));
Output
true
true
false
false
false
false
false
false
false
false
false
false
false
jsfiddle
If you want to bound the range to what javascript can represent numerically as an integer then you will need to add a test for && +testValue > -9007199254740992 && +testValue < 9007199254740992
If you don't like using RegExs, you can also accomplish this with a parser. Something like this:
Javascript
function isCharacterDigit(testCharacter) {
var charCode = testCharacter.charCodeAt(0);
return charCode >= 48 && testCharacter <= 57;
}
function isStringNumericalInteger(testValue) {
var start = 0,
character,
index,
length;
if (typeof testValue !== "string") {
return false;
}
character = testValue.charAt(start);
if (character === "+" || character === "-") {
start += 1;
character = testValue.charAt(start);
}
start += 1;
length = testValue.length;
if ((length > start && character === "0") || !isCharacterDigit(character)) {
return false;
}
for (index = start; index < length; index += 1) {
if (!isCharacterDigit(testValue.charAt(index))) {
return false;
}
}
return true;
}
jsfiddle
I would use something like below code to validate number input. First I parse the given value to float and then check isNaN().
var isNumber = function (obj) {
return !isNaN(parseFloat(obj)) && isFinite(obj);
};
I think this is what you need in your case (i hate regex because this is not very good for the performance but..)
http://jsbin.com/EQiBada/1/
var NMAX = Math.pow(2, 53);
function isNumeric(n) {
n = n < 0 ? n * -1 : n;
var r = /^\d+$/.test(n);
if (r === true)
{
return parseInt(n, 10) >= (NMAX * -1) + 1 && parseInt(n, 10) <= NMAX;
}
return false;
}
Minified
var NMAX = Math.pow(2, 53);
function isNumericMin(n) {
n = n < 0 ? n * -1 : n;
return /^\d+$/.test(n) === true ? parseInt(n, 10) >= (NMAX * -1) + 1 && parseInt(n, 10) <= NMAX : false;
}
var i = '1E267146'
if(isNaN(i) || !isFinite(i) !! i=="")
{
// do stuff
}
else
{
// do stuff
}

Categories

Resources