Multiple Logical Operators in javascript - 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();
}

Related

Javascript check if a decimal is negative

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

If/Else Statement

Hi what am I doing wrong with this if statement? Ive tried making the second one and else if and the last one an else as well but cant get the alerts to respond properly.
prompt("Please enter a number");
if(x < 100) {
alert("variable is less 100")
}
if(x == 100) {
alert("variable is equal to 100!")
}
if(x > 100) {
alert("variable was greater than 100")
}
thanks!
You are missing an assignment to variable x.
var x = prompt("Please enter a number");
//^^^^^
Then you could use parseInt to get a integer number from the string
x = parseInt(x, 10);

Javascript Function not defined error in code

I am new to Javascript and I don't understand why I am getting an error for this piece of code. Please help me understand what syntax I am got wrong.
var isEven = function(number){
if(number % 2 = 0){
return true;
} else {
return false;
};
};
isEven(5);
Change
if(number % 2 = 0)
to
if(number % 2 === 0)
because you want to test if the modulo 2 of number has no remainder. What you wrote was an illegal assignment operation.
(number % 2 = 0)
should be
(number % 2 == 0)
or
(number % 2 === 0)
One equal sign is assignment, the double equal sign is "equal to."
More info:
Triple equal sign matches type and value. (This is a good habit to get into using when possible.) Types are like "number", "object", "string" etc.
(number % 2 == 0) // true
(number % 2 == "0") // true
(number % 2 === 0) // true
(number % 2 === "0") // false
Otherwise, == might work with other things the computer considers zero, maybe null, maybe empty quotes, or maybe not, there's so many caveats in JS typing, === prevents most of those type headaches.
You are using the assignment operator instead of the equality operator in your if statement. This causes a JavaScript error because the value on the lefthand side of the operator isn't a variable, it's an expression.
What you want to do is check for equality. To do this, change = to === in your if statement.
if (number % 2 === 0)

What should be the value of x?

what value should X have so this condition would work?
// insert code here
if (x == 1 && x === 2) {
console.log('Succes!');
}
X should be defined like so:
Object.defineProperty(window,'x',{
get: function() {
this.__tmp = this.__tmp || 2;
this.__tmp = 3-this.__tmp;
return this.__tmp;
}
});
Then:
if( x == 1 && x === 2)
MIGHT work. Demonstration
The following code should do the trick (Demo here):
x = {};
x.valueOf = function (){
x = 2; // this is important
return 1;
};
if (x == 1 && x === 2) {
console.log('Success !!!');
}
Explanation:
The statements are executed from left to right (so first x == 1, then x === 2). When checking x == 1, it will go to the valueOf function, which returns 1, so it will be true. But at the same time, x is changed to be 2, thus the next statement that will be checked (x === 2) will also be true.
PS: As far as I know, this has no practical application. However, it can lead to better understanding of how javascript works - which is the point of such questions :)
X can't hold a value equals to 1 and identical to 2 at the same time, this expression is logically incorrect.
There is no such value.
x === 2 checks if x equals exactly to 2, while 2 cannot be 1 at the same time.
Only the following would make sense:
if (x && x === 2) { ... }
(or getter overloading, as demonstrated in #Niet the Dark Absol's answer, which is not a pure case)
Using === (identity) operator it will never work, but it's possible to construct an object that will be "equal" (==) to 1 and 2 at the same time:
x = { valueOf: function() { return this.foo ? 2 : this.foo = 1 } }
console.log(x == 1 && x == 2) // true
"valueOf" is the method JS implicitly calls when you convert or compare an object to a number.
Needless to say, this exercise doesn't have any practical sense.

Testing whether a value is odd or even

I decided to create simple isEven and isOdd function with a very simple algorithm:
function isEven(n) {
n = Number(n);
return n === 0 || !!(n && !(n%2));
}
function isOdd(n) {
return isEven(Number(n) + 1);
}
That is OK if n is with certain parameters, but fails for many scenarios. So I set out to create robust functions that deliver correct results for as many scenarios as I could, so that only integers within the limits of javascript numbers are tested, everything else returns false (including + and - infinity). Note that zero is even.
// Returns true if:
//
// n is an integer that is evenly divisible by 2
//
// Zero (+/-0) is even
// Returns false if n is not an integer, not even or NaN
// Guard against empty string
(function (global) {
function basicTests(n) {
// Deal with empty string
if (n === '')
return false;
// Convert n to Number (may set to NaN)
n = Number(n);
// Deal with NaN
if (isNaN(n))
return false;
// Deal with infinity -
if (n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY)
return false;
// Return n as a number
return n;
}
function isEven(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Convert to Number and proceed
n = Number(n);
// Return true/false
return n === 0 || !!(n && !(n%2));
}
global.isEven = isEven;
// Returns true if n is an integer and (n+1) is even
// Returns false if n is not an integer or (n+1) is not even
// Empty string evaluates to zero so returns false (zero is even)
function isOdd(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Return true/false
return n === 0 || !!(n && (n%2));
}
global.isOdd = isOdd;
}(this));
Can anyone see any issues with the above? Is there a better (i.e. more accurate, faster or more concise without being obfuscated) version?
There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript.
Use modulus:
function isEven(n) {
return n % 2 == 0;
}
function isOdd(n) {
return Math.abs(n % 2) == 1;
}
You can check that any value in Javascript can be coerced to a number with:
Number.isFinite(parseFloat(n))
This check should preferably be done outside the isEven and isOdd functions, so you don't have to duplicate error handling in both functions.
I prefer using a bit test:
if(i & 1)
{
// ODD
}
else
{
// EVEN
}
This tests whether the first bit is on which signifies an odd number.
How about the following? I only tested this in IE, but it was quite happy to handle strings representing numbers of any length, actual numbers that were integers or floats, and both functions returned false when passed a boolean, undefined, null, an array or an object. (Up to you whether you want to ignore leading or trailing blanks when a string is passed in - I've assumed they are not ignored and cause both functions to return false.)
function isEven(n) {
return /^-?\d*[02468]$/.test(n);
}
function isOdd(n) {
return /^-?\d*[13579]$/.test(n);
}
Note: there are also negative numbers.
function isOddInteger(n)
{
return isInteger(n) && (n % 2 !== 0);
}
where
function isInteger(n)
{
return n === parseInt(n, 10);
}
Why not just do this:
function oddOrEven(num){
if(num % 2 == 0)
return "even";
return "odd";
}
oddOrEven(num);
To complete Robert Brisita's bit test .
if ( ~i & 1 ) {
// Even
}
var isOdd = x => Boolean(x % 2);
var isEven = x => !isOdd(x);
var isEven = function(number) {
// Your code goes here!
if (number % 2 == 0){
return(true);
}
else{
return(false);
}
};
A few
x % 2 == 0; // Check if even
!(x & 1); // bitmask the value with 1 then invert.
((x >> 1) << 1) == x; // divide value by 2 then multiply again and check against original value
~x&1; // flip the bits and bitmask
We just need one line of code for this!
Here a newer and alternative way to do this, using the new ES6 syntax for JS functions, and the one-line syntax for the if-else statement call:
const isEven = num => ((num % 2) == 0);
alert(isEven(8)); //true
alert(isEven(9)); //false
alert(isEven(-8)); //true
A simple modification/improvement of Steve Mayne answer!
function isEvenOrOdd(n){
if(n === parseFloat(n)){
return isNumber(n) && (n % 2 == 0);
}
return false;
}
Note: Returns false if invalid!
Different way:
var isEven = function(number) {
// Your code goes here!
if (((number/2) - Math.floor(number/2)) === 0) {return true;} else {return false;};
};
isEven(69)
Otherway using strings because why not
function isEven(__num){
return String(__num/2).indexOf('.') === -1;
}
if (testNum == 0);
else if (testNum % 2 == 0);
else if ((testNum % 2) != 0 );
Maybe this?
if(ourNumber % 2 !== 0)
var num = someNumber
isEven;
parseInt(num/2) === num/2 ? isEven = true : isEven = false;
for(var a=0; a<=20;a++){
if(a%2!==0){
console.log("Odd number "+a);
}
}
for(var b=0; b<=20;a++){
if(b%2===0){
console.log("Even number "+b);
}
}
Check if number is even in a line of code:
var iseven=(_)=>_%2==0
This one is more simple!
var num = 3 //instead get your value here
var aa = ["Even", "Odd"];
alert(aa[num % 2]);
To test whether or not you have a odd or even number, this also works.
const comapare = x => integer(checkNumber(x));
function checkNumber (x) {
if (x % 2 == 0) {
return true;
}
else if (x % 2 != 0) {
return false;
}
}
function integer (x) {
if (x) {
console.log('even');
}
else {
console.log('odd');
}
}
Using modern javascript style:
const NUMBERS = "nul one two three four five six seven ocho nueve".split(" ")
const isOdd = n=> NUMBERS[n % 10].indexOf("e")!=-1
const isEven = n=> isOdd(+n+1)
function isEven(n) {return parseInt(n)%2===0?true:parseInt(n)===0?true:false}
when 0/even wanted but
isEven(0) //true
isEven(1) //false
isEven(2) //true
isEven(142856) //true
isEven(142856.142857)//true
isEven(142857.1457)//false
​
if (i % 2) {
return odd numbers
}
if (i % 2 - 1) {
return even numbers
}

Categories

Resources