Javascript check if a decimal is negative - javascript

How would i check if a decimal is negative? Because the if statement automatically turns it into a number...
Example:
var x = -0.24324;
how would i parse it so it tells me x is negative/positive?
Thanks
Edit: Maybe i phrased it badly, the variable changes so something it will be positive like 0.00000001, sometimes -0.0003423423, sometimes 0.0000000234
If i put it in a if statement everything is automatically turned into 0 right? And i can't use a parseFloat in the if statement?

Just check if x less than zero since it's a number:
if (x < 0) {
// it's negative
}

You can use isNaN() function to check whether it is valid number or not.
If it is, then you can check for positive or negative value.
Something like this:
var x = "-123"
var y = -456;
var z = '-123a';
if(!isNaN(x) && x < 0) {
console.log(x + ' is negative');
}
if(!isNaN(y) && y < 0) {
console.log(y + ' is negative');
}
if(!isNaN(z) && z < 0) {
console.log(z + ' is negative');
}

const num = -8;
// Old Way
num === 0 ? num : (num > 0 ? 1 : -1); // -1
// ✅ ES6 Way
Math.sign(num); // -1

Related

Bitwise - Why 0 & 1 !== 1 & 1 return false in VSCode/Leetcode?

I was writing an algorithm to compare how many bits are different between 2 numbers using this function
var hammingDistance = function(x, y) {
let result = 0;
while (x !== 0 || y !== 0) {
// This line is incorrect
if (x & 1 !== y & 1) result++;
x = x >> 1;
y = y >> 1;
}
return result;
};
But my result is always 1 less than the correct answer, and it turns our my function is wrong when comparing the left most digit, such as 0011 and 0100. It returns 2 instead of 3.
https://i.imgur.com/P46RyZr.png
I can use XOR instead of !== to get the correct answer. But I'm wondering why?
Your problem is that !== has a higher precedence than &. So your condition is actually (x & (1 !== y)) & 1. Use explicit grouping instead:
if ((x & 1) !== (y & 1)) result++;
It works with ^ because that has a lower precedence than &.

Why can't I assign and then check a variable in the same if statement in Javascript?

In other words, why doesn't this show an alert?
var x;
if (x = 1 && x > 0) {
alert(x);
}
As far as I understand, x = 1 should assign 1 to x and also return 1. The x > 0 check is failing. Why?
Actually, the && operation will have precedence over the assignment.
In you case, x will be the result of 1 && x > 0 which is false.
var x;
if (x = 1 && x > 0) {
alert(x);
}
console.log(x); // false
You can enforce the order of operations using parentheses, as shown by Nina Scholz.
You need some parens to separate the assignment from the ongoing expression.
var x;
if ((x = 1) && x > 0) {
alert(x);
}

Boolean expressions - getting mixed up with AND, OR logical operators and how they work

I have to convert a number to comma format. E.g 12345 => 12,345.
I have my solution :
function convert(n) {
n = n.toString();
var result = '';
var count = 0,
var idx = n.length - 1;
while (r = n[idx]) {
count++;
result = ((count % 3 == 0 && count != n.length) ? ',' : '') + r + result;
idx--;
}
return result;
}
But someone else used :
result = ((count % 3 != 0 || count == n.length) ? '' : ',') + r + result;
They both work but now I am confused about my own solution and just lost why they both work. Ah not sure if my question is clear.
!(x AND y) is equal to !x OR !y
(and you can pull a NOT out of a boolean x by double negation, for example:
x == !!x
so
x AND !y (your original expression) is equivalent to !(!x OR y)
if you remove the negation (!) from the beginning, then you actually get the Negated form and that is why the second and third values of the ternary operator are reversed in your second example.
The two expressions are equivalent, the second one is just the negated version of yours. The opposite (more or less) of == is !=, the opposite of && is ||, and the opposite of true is false.
You are placing a comma whenever the count is divisible by 3 and you aren't at the start of the number. They are not placing a comma anytime the count is not divisible by 3 or they are at the start of the number.
Assume that, count % 3 = 0 and count > n.length
Now your logic:
((count % 3 == 0 && count != n.length) ? ',' : '')
which means True && True which results in True hence the first condition after ? which is "," is selected.
Someone else logic:
((count % 3 != 0 || count == n.length) ? '' : ',')
which means 'False || False' which results in 'False' hence second condition after ? which is "," is selected.
P.S: Both are using similar logic

Understanding custom abs function in JavaScript

I hope my logic isn't flawed but I'm reading the Definitive Guide to JavaScript and I don't understand how this custom abs function works...
function abs(x) {
if (x >= 0) {
return x;
} else {
return -x;
}
}
I recrafted it using a ternary operator in an attempt to understand it...
var res = (x >= 0) ? x : -x;
return res;
... but I still don't get how it works.
Say I use -10 as x, how does it return +10? How does the sign reverse?
function abs(x) {
if (x >= 0) {
//If the number passed is greater than or equal to zero (positive)
//return it back as is
return x;
} else {
//If less than zero (negative)
//return the negative of it (which makes it positive)
// -(-10) === 10
return -x;
}
}
Negative 10 is not greater than or equal to 0, so its opposite is returned.
Placing a negative sign in front of a variable is the same thing as multiplying it by negative 1.
it look as
var res = (x >= 0) ? 1 * x : -1 * x;
Say I use -10 as x, how does it return +10? How does the sign reverse?
That's because of this check:
x >= 0
If number is 0 or greater it returns it else returns negative version which becomes positive because of - sign before it.

Multiple Logical Operators in javascript

I want to check the following
1: Is x a number
2. If x is less that 5 or greater than 15, sound alert
3. If all is ok, callMe()
var x = 10;
if (isNaN(x) && ((x < 5) || (x > 15))) {
alert('not allowed')
}
else
{
callMe();
}
What am I doing wrong?
var x = 10;
if (isNaN(x) || (x < 5) || (x > 15)) {
alert('not allowed')
}
else
{
callMe();
}
This way, if x is not a number you go directly to the alert. If it is a number, you go to the next check (is x < 5), and so on.
All the other answers about the && vs || are correct, I just wanted to add another thing:
The isNaN() function only checks whether the parameter is the constant NaN or not. It doesn't check whether the parameter is actually number or not. So:
isNaN(10) == false
isNaN('stackoverflow') == false
isNaN([1,2,3]) == false
isNaN({ 'prop' : 'value'}) == false
isNaN(NaN) == true
In other words, you cannot use it to check whether a given variable contains a number or not. To do that I'd suggest first running the variable through parseInt() or parseFloat() depending on what values you expect there. After that check for isNaN(), because these functions return only numbers or NaN. Also this will make sure that if you have a numeric string then it is also treated like a number.
var x = 10;
if (isNaN(x) || (x < 5) || (x > 15)) {
alert('not allowed')
}
else
{
callMe();
}

Categories

Resources