If statement is acting weird for some reason - javascript

So I have an if statement that is checking the values of a drop down. The user has to select at least one of them to continue. The values are just numbers. My if statement checks to see that, basically, the values are equal to zero:
if (numChildren === 0 && numAdults === 0){
Than do this
}
But for some reason it keep returning false. I have console logged the numChildren and adults to see what there values are and they are zero I have no idea why it isn't working I have put a "!" before it to cause it to be true but then it remains false. It is a very weird error.
$("#Discounts").on("click", function () {
let numChildren = $("#children").val();
let numAdults = $("#adults").val();
console.log("Adults: " + numAdults + "\nChildren: " + numChildren);
console.log(numChildren === 0 && numAdults === 0);
if (numChildren === 0 && numAdults === 0) {
alert("You must select");
$("#children").val(1);
}
});

When you use 3 equals in a if statement the numChildren must be the same type and value as 0 (integer), not just equal to 0.
Try changing to 2 equals:
if (numChildren == 0 && numAdults == 0) {
alert("You must select");
$("#children").val(1);
}
Reference

It's not weird.
You are using the triple equal comparison and, probably, the numChildren contains a number in string form (like "0") which you are comparing to zero as an actual number.
It should work with:
numChildren == 0 && numAdults == 0
or
Number(numChildren) === 0 && Number(numAdults) === 0
This is the official reference: https://tc39.github.io/ecma262/#sec-strict-equality-comparison

You can try this:
if (Number(numChildren) === 0 && Number(numAdults) === 0) {
alert("You must select");
$("#children").val(1);
}

Related

JavaScript Weird behavior in a condition

there's something that i just solved but I don't understand why i got that kind of behavior, here's my js code
function fibonacci () {
let fibonacciNumber = document.getElementById("my-input").value;
let numberInitialize = 0;
let numberNext = 1;
let sum = numberInitialize + numberNext;
if (fibonacciNumber === "" || fibonacciNumber === 0) {
return (0);
}
for (index = 1; index < fibonacciNumber; index++)
{
numberInitialize = numberNext;
numberNext = sum;
sum = numberInitialize + numberNext;
console.log(sum);
console.log("premier tour");
}
console.log(sum);
document.getElementById("fibo-result").innerHTML = `${sum}`;
}
So on the html side I just have an input and im writing down number, my questions concerned this line of code
if (fibonacciNumber === "" || fibonacciNumber === 0) {
return (0);
}
when im writing down 0, its still printing one but i write the condition like that
if (fibonacciNumber === "" || fibonacciNumber <= 0) {
return (0);
}
its working and when I got 0 as an input nothing is printed like i wanted, my question is: Why when im putting fibonacciNumber === 0 return (0) its not working properly its 0, the condition match no ?
Thanks guys
The reason is because your field actually has the string "0". The identity operator (===) will not do any type coercion before comparing the values, so "0" === 0 is false.
Numeric comparison operators like <= will do type coercion, so "0" <= 0 will evaluate to true.
You can see this all in action below.
console.log("0" === 0);
console.log("0" <= 0);
You will need to use parseInt() and then treat the input as integer.
let fibonacciNumber = parseInt(document.getElementById("my-input").value);

Javascript number comparison with negative value doesn't work

I try to compare a negative value with "0" and that doesn't seem to work.
var number = Number.parseInt($(this).val());
var min = Number.parseInt($(this).attr('min'));
var max = Number.parseInt($(this).attr('max'));
Here's my condition :
if (min && $(this).prop('required')) {
if (number < min) {
alert('ok');
fail = true;
}
}
My min value is 0 and my number is -1.
It never enters the condition. Why?
0 is a falsy value. It will never enter the if condition if min is 0 .
All the following conditions will be sent to else blocks
if (false)
if (null)
if (undefined)
if (0)
if (NaN)
if ('')
if ("")
if (``)
Since the return value of parseInt is either a number or NaN, you can use isNaN instead:
if(!isNaN(min) && $(this).prop('required')) {
// your code
}
Since min is 0, your condition evaluates to false. You have two options, one is to check the string value before parsing it:
if($(this).attr('min').trim() && $( this ).prop('required')) {
if (number < min) {
alert('ok');
fail = true;
}
}
The other is to check for NaN after parsing the number since parsing an empty string will return NaN:
if(!isNaN(min) && $( this ).prop('required')) {
if (number < min) {
alert('ok');
fail = true;
}
}
console.log(' '.trim() == false);
console.log(!isNaN(Number.parseInt('')) == false);
Your condition:
if(min && $( this ).prop('required'))
Would evaluate to false since min has a value of 0 and 0 && anything would be false
(0 && true ) return zero in JavaScript.
see first comment for more details

Else block not fulfilling my condition

if(a == 1 || b == 0) {
document.getElementById("div").style.display = "none";
}
else {
document.getElementById("div").style.display = "block";
}
When I select a value 1 or b value 0 my div style set to none because condition is true, but when I select a value 2 or b value 3 means anything except 1 or 0 my div is not showing it's in display: none, it needs to display block.
Can you guyz know what I am doing wrong here?
Where do you get your a and b from?
Are you sure they are integers and not string?
You could try
if(parseInt(a) == 1 || parseInt(b) == 0) {

A quick way to test equality of more than 2 values at once?

I was wondering if there was a quick way to test the equality of more than two values in js. Something similar to (= 6 6 6).
In the console, I tried things like...
1 == 1 == 1 == 1
true
2 == 2 == 2 == 2
false
0 == 0 == 0
false
0 == 0 == 0 == 0
true
...which was amusing, but also puzzling.
Is there a quick way of doing this in js?
Thanks.
The reason you got unexpected behavior is because we need to adjust your expectations in js a bit ;) 2 == 2 == 2 == 2 does 3 comparisons, all from left to right. The first comparison is the leftmost 2 == 2, which evaluates to true. After that we get the result of the first comparison being compared to (what is in this case) the 3rd 2. Ie, true === 2, which is false. And finally, we get false === 2, which is also false.
It might help to visualize it as such:
(((2 == 2) == 2) == 2)
I think in general a === b && b === c might be what you're looking for.
EDIT: Ah, and sorry I keep switching out the == for ===. It's just habit. And it's a habit I'd recommend. the === operator doesn't do type casting, so it evaluates the value proper, not a casted version of the value.
It's because true == 1 but true != 2
You can try:
function isEquals() {
var flag = true;
for(var i=1; i<arguments.length; i++) flag = flag && (arguments[i] == arguments[0]);
return flag;
}
isEquals(2,2,2); // true
or:
function isEquals() {
var ar = arguments;
return Array.prototype.every.call(arguments, function(a){return a==ar[0];});
}
Yes you can, but you need to use the "Logical Operators" like the && or || to check more than 1 statement like (x<1 && y>0).
You can use this as a quick easy reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
If you have more than three values, it might be more convenient to create a function for use on an array:
function allEqual(arr) {
return arr.every(function (x, i) {
return i === 0 || x === arr[i - 1];
});
}
allEqual([1, 1, 1])
ES6:
function allEqual(...arr) {
return arr.every((x, i) => i === 0 || x === arr[i - 1]);
}
allEqual(1, 1, 1)
As an addition to #vp_arth's answer you could even add a method to the Array prototype
Array.prototype.isHomogeneous = function(){
return Array.prototype.every.call(this, function(c,i,a){ return c === a[0];})
}
So you could do
[1,2,3].isHomogeneous() = false
[1,1,1].isHomogeneous() = true

If variable matches 3 conditions

I need to have an if statement to check if a number is = 0, or between 5000 and 3600000. How can have it check all 3 conditions?
Number can be 0 or 5000 or above OR 3600000 or less. It can't be -1, 1.1 2.3 or anything between 0 and 5.
Here is what I have now and this work for checking if less than 5000 or greater than 3600000
var intervalCheck = interval * digit
if(isNaN(intervalCheck))
{
alert("Must be a number.");
}
else if((intervalCheck < 5000)||(intervalCheck>=3600000))
{
alert("Must be between 5 seconds and 1 hour.");
}
else
{
localStorage["interval_setting"] = interval * digit;
saveActions();
}
if ((intervalCheck == 0) || (intervalCheck >= 5000 && intervalCheck <= 3600000)) {
// put your code here
}
You can combine as many logic operations as you want into one if statement using any of the javascript logic and comparision operators.
You can see a demo work here: http://jsfiddle.net/jfriend00/y5tRK/
else if(intervalCheck === 0 || (intervalCheck >= 5000 && intervalCheck <= 3600000)) {
localStorage["interval_setting"] = interval * digit;
saveActions();
}
else {
alert('You broke something");
}
The === means to check both type and value. This makes sure that intervalCheck is both a number and equal to zero, instead of evaluating to true if intervalCheck is "" or false. Then we give our or condition. We wrap this in parenthesis becuase we need to ensure that the value falls between our two numbers. The parenthesis mean this will be evaluated as a whole with the or.
I need to have an if statement to check if a number is = 0, or between
5000 and 3600000.
if( intervalCheck == 0 || (intervalCheck >= 5000 && intervalCheck <= 3600000) ) {
//code here
}
if(intervalCheck == 0 || (intervalCheck >= 5000 && intervalCheck<=3600000))
if(!isNaN(intervalCheck) && (intervalCheck == 0 || (intervalCheck >= 5000 && intervalCheck <= 3600000)))

Categories