Interesting javascript quirks - javascript

I have this following if statement:
RG is "100" and max is "85"
if (RG == "" | RG > max) {
//Doesn't execute
}
Since RG isn't "" and RG is larger than max why isn't the code executing? I believed the operator was short circuiting (hence only the one pipe |) but changing it didn't make any difference. My guess is that it is comparing literal strings - so how do I force javascript to treat them as floats?
Just to be clear I need both parts of the OR to be checked and only execute if either of them is true.

I believed the operator was short circuiting (hence only the one pipe |) but changing it didn't make any difference
I take it then it originally looked like this:
if (RG == "" || RG > max) {
//Doesn't execute
}
We can ignore the first part because it's false, so your question is why wasn't RG > max true? And the answer is that "100" comes before "85" in the string collation order. Strings are not numbers, you don't compare them numerically.
If you want them to be floats as you said, you can make them numbers via parseFloat (or parseInt as they look like integers, but you said floats, so...):
if (RG == "" || parseFloat(RG) > parseFloat(max)) {
//Doesn't execute
}
I've done it inline there, but the odds seem high you'll want to do it earlier and assign the result to variables, unless this really is the only place you'll use the values as numbers.

if (RG === "" || parseFloat(RG) > parseFloat(max)) {
// should execute
}

i prefer
if((!RG) || RG*1>max*1)
{
...
}

How do I force javascript to treat them as floats?
Like this:
var RG = "100",
max = "85";
if (RG === "" || Number(RG) > Number(max)) {
// Your code goes here.
// It will be executed if RG is the empty string OR if RG > max.
}
Number(foo) will coerce foo into a number. You could also use +foo but I think this is more readable.
You should use parseFloat instead if the string can contain text as well.
Note that you need a strict equality check (===) when checking for the empty string, since RG == "" will be true if RG is 0, '0', false, etc. as well.

well, parse the strings.
if (RG == "" | parseFloat(RG) > parseFloat(max)) {
//Do Something }

Related

getting wrong answer for finding largest of 2 numbers using readline-sync in js [duplicate]

I store some parameters client-side in HTML and then need to compare them as integers. Unfortunately I have come across a serious bug that I cannot explain. The bug seems to be that my JS reads parameters as strings rather than integers, causing my integer comparisons to fail.
I have generated a small example of the error, which I also can't explain. The following returns 'true' when run:
console.log("2" > "10")
Parse the string into an integer using parseInt:
javascript:alert(parseInt("2", 10)>parseInt("10", 10))
Checking that strings are integers is separate to comparing if one is greater or lesser than another. You should always compare number with number and string with string as the algorithm for dealing with mixed types not easy to remember.
'00100' < '1' // true
as they are both strings so only the first zero of '00100' is compared to '1' and because it's charCode is lower, it evaluates as lower.
However:
'00100' < 1 // false
as the RHS is a number, the LHS is converted to number before the comparision.
A simple integer check is:
function isInt(n) {
return /^[+-]?\d+$/.test(n);
}
It doesn't matter if n is a number or integer, it will be converted to a string before the test.
If you really care about performance, then:
var isInt = (function() {
var re = /^[+-]?\d+$/;
return function(n) {
return re.test(n);
}
}());
Noting that numbers like 1.0 will return false. If you want to count such numbers as integers too, then:
var isInt = (function() {
var re = /^[+-]?\d+$/;
var re2 = /\.0+$/;
return function(n) {
return re.test((''+ n).replace(re2,''));
}
}());
Once that test is passed, converting to number for comparison can use a number of methods. I don't like parseInt() because it will truncate floats to make them look like ints, so all the following will be "equal":
parseInt(2.9) == parseInt('002',10) == parseInt('2wewe')
and so on.
Once numbers are tested as integers, you can use the unary + operator to convert them to numbers in the comparision:
if (isInt(a) && isInt(b)) {
if (+a < +b) {
// a and b are integers and a is less than b
}
}
Other methods are:
Number(a); // liked by some because it's clear what is happening
a * 1 // Not really obvious but it works, I don't like it
Comparing Numbers to String Equivalents Without Using parseInt
console.log(Number('2') > Number('10'));
console.log( ('2'/1) > ('10'/1) );
var item = { id: 998 }, id = '998';
var isEqual = (item.id.toString() === id.toString());
isEqual;
use parseInt and compare like below:
javascript:alert(parseInt("2")>parseInt("10"))
Always remember when we compare two strings.
the comparison happens on chacracter basis.
so '2' > '12' is true because the comparison will happen as
'2' > '1' and in alphabetical way '2' is always greater than '1' as unicode.
SO it will comeout true.
I hope this helps.
You can use Number() function also since it converts the object argument to a number that represents the object's value.
Eg: javascript:alert( Number("2") > Number("10"))
+ operator will coerce the string to a number.
console.log( +"2" > +"10" )
The answer is simple. Just divide string by 1.
Examples:
"2" > "10" - true
but
"2"/1 > "10"/1 - false
Also you can check if string value really is number:
!isNaN("1"/1) - true (number)
!isNaN("1a"/1) - false (string)
!isNaN("01"/1) - true (number)
!isNaN(" 1"/1) - true (number)
!isNaN(" 1abc"/1) - false (string)
But
!isNaN(""/1) - true (but string)
Solution
number !== "" && !isNaN(number/1)
The alert() wants to display a string, so it will interpret "2">"10" as a string.
Use the following:
var greater = parseInt("2") > parseInt("10");
alert("Is greater than? " + greater);
var less = parseInt("2") < parseInt("10");
alert("Is less than? " + less);

JavaScript: eliminate number with decimal .0

I need your advice (I'm a beginner in JS).This is my code:
function fn(pin) {
if (pin.length === 4 && !isNaN(pin) && pin % parseInt(pin) === 0 && Number(pin) > 0) {
return true;
}
return false
}
console.log(fn("123a.78")) // false
So i check the length, that it is a number, that it is integer and that it is bigger than 0.
But how should i write the condition to eliminate strings of this type: "12.0" (because it also has length of 4 and is also integer)? If i try conditions with pin.parseFloat or parseInt, it will affect strings like this type "1234" as well. Or maybe i write them in the wrong way...
I would go with a regular expression to validate the input.
The regular expression to validate 4 digits only would look like this: /^[0-9]{4}$/
Regular expressions have methods that allow them to test if variables are of their type.
For instance:
const pin = '1234';
const pin2 = '12.4'
const regExp = /^[0-9]{4}$/
regExp.test(pin) //returns true
whereas:
regExp.test(pin2) //returns false
You can use this validation as the condition in your if/else conditions to execute the code you need.
freecode tutorial on Regular Expressions
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/#es6
Regular expressions playground:
https://regex101.com/

JavaScript: Why []+(-~{}-~{}-~{}-~{})+(-~{}-~{}); returns "42"

Saw this in my newsletter. Tested on Chrome and Firefox. I still can't figured it out.
[]+(-~{}-~{}-~{}-~{})+(-~{}-~{}); //=> "42"
Evaluating:
~{}
is evaluated using the internal function:
~ToInt32({})
which gives -1.
Ref ECMA spec - http://www.ecma-international.org/ecma-262/5.1/#sec-9.5
and this explanation - http://jibbering.com/faq/notes/type-conversion/#tcToInt32
Therefore, in this case
(-~{}-~{}) == 2
(-~{}-~{}-~{}-~{}) == 4
As you have []+ in the start of expression, javascript use plus operands like string. So you have "" + "4" + "2" = "42"
The ~ operator is a Bitwise NOT operator. It returns the "1's complement" of a number. Because of that {} is converted into a number, resulting in NaN. The same would happen with +{} == NaN. The bitwise not of ~NaN == -1. So:
(-~{}-~{}-~{}-~{}) == 4 & (-~{}-~{}) == 2
The DefaultValue for an empty array is an empty string. For example []==[]+[] && []+[]==''
From that, the full parsing is:
[]+ /*converted to ''+*/ (-~{}-~{}-~{}-~{}) /*Equals numeric 4, but concatenated as a string to become '4'*/ + (-~{}-~{}) /*Equals numeric 2, but concatenated as a string to become '2'*/ and the end result is actually '42'.
You can validate this via typeof([]+(-~{}-~{}-~{}-~{})+(-~{}-~{})) === 'string'

Checking only the integer values through Regex

My Code:
I tried the following code
<SCRIPT type="text/javascript">
var num = "10";
var expRegex = /^\d+$/;
if(expRegex.test(num))
{
alert('Integer');
}
else
{
alert('Not an Integer');
}
</SCRIPT>
I am getting the result as Integer. Actually I declared the num varibale with double quotes. Obviously it is considered as a string. Actually I need to get the result as Not an Integer. How to change the RegEx so that I can get the expected result.
In this case, it should give the result as Not an Integer. But I am getting as Integer.
if(typeof num === "number" &&
Math.floor(num) === num)
alert('Integer');
else
alert('Not an Integer');
Regular expressions are there to work on strings. So if you tried it with something else than a string the string would either be converted or you would get an error. And yours returns true, because obviously the string only contains digit characters (and that is what you are checking for).
Use the typeof operator instead. But JavaScript doesn't have dedicated types for int and float. So you have to do the integer check yourself. If floor doesn't change the value, then you have an integer.
There is one more caveat. Infinity is a number and calling Math.floor() on it will result in Infinity again, so you get a false positive there. You can change that like this:
if(typeof num === "number" &&
isFinite(num) &&
Math.floor(num) === num)
...
Seeing your regex you might want to accept only positive integers:
if(typeof num === "number" &&
isFinite(num) &&
Math.floor(Math.abs(num)) === num)
...
RegExp is for strings. You can check for typeof num == 'number' but you will need to perform multiple checks for floats etc. You can also use a small bitwise operator to check for integers:
function isInt(num) {
num = Math.abs(num); // if you want to allow negative (thx buettner)
return num >>> 0 == num;
}
isInt(10.1) // false
isInt("10") // false
isInt(10) // true
I think it's easier to use isNaN().
if(!isNaN(num))
{
alert('Integer !');
}
else
{
alert('Not an Integer !');
}
Léon

Logical && operator

Having an unpredicted outcome using the && logical operator. If I link more than 2 expressions, the if clause fails. Is there some limit to the number of expressions that can be concatenated using &&?
if (tTellerProN.checked && tCareProN.checked && tSalesProN.checked) {
$(flListEmpty).empty();
$(flListEmpty).append($('<option></option>').val(0).html("Select Role"));
$('.fl_list1 .list4').each(function (index) {
$(flListEmpty).append($('<option> </option>').val(index).html($(this).text()));
})
}
&& is not a jQuery operator, it is Javascript. jQuery is a library that builds on Javascript.
I'm not sure what the ** is in your IF statment but this code works:
var x = true;
var y = true;
var z = true;
alert(x && y && z); // true
alert(x && y && !z); // false
I would alert the values of your 3 .checked parameters and make sure they are being set as you expected.
No, there is no limit. Your expression requires that all three checked values are true, otherwise it will return false. One of them must be false (or not true), that's why your if is failing.
For the record: && is part of the javascript language, not the jQuery library.
No, there is no limit.
However looking at your code (what little there is of it and with such descriptive variable names used), I would venture a guess that you actually mean ||, not &&.
i made a test case here with both && and ||: http://jsfiddle.net/VcmCM/

Categories