How do i do something if its dividable by 40 [duplicate] - javascript

How do I figure out if a variable is divisible by 2? Furthermore I need do a function if it is and do a different function if it is not.

Use modulus:
// Will evaluate to true if the variable is divisible by 2
variable % 2 === 0

Seriously, there's no jQuery plugin for odd/even checks?
Well, not anymore - releasing "Oven" a jQuery plugin under the MIT license to test if a given number is Odd/Even.
Source code is also available at http://jsfiddle.net/7HQNG/
Test-suites are available at http://jsfiddle.net/zeuRV/
(function() {
/*
* isEven(n)
* #args number n
* #return boolean returns whether the given number is even
*/
jQuery.isEven = function(number) {
return number % 2 == 0;
};
/* isOdd(n)
* #args number n
* #return boolean returns whether the given number is odd
*/
jQuery.isOdd = function(number) {
return !jQuery.isEven(number);
};
})();​

You don't need jQuery. Just use JavaScript's Modulo operator.

You can use the modulus operator like this, no need for jQuery. Just replace the alerts with your code.
var x = 2;
if (x % 2 == 0)
{
alert('even');
}
else
{
alert('odd')
}

You can do it in a better way (up to 50 % faster than modulo operator):
odd: x & 1
even: !(x & 1)
Reference: High Performance JavaScript, 8. ->Bitwise Operators

You can also:
if (x & 1)
itsOdd();
else
itsEven();

if (x & 1)
itIsOddNumber();
else
itIsEvenNumber();

Hope this helps.
let number = 7;
if(number%2 == 0){
//do something;
console.log('number is Even');
}else{
//do otherwise;
console.log('number is Odd');
}
Here is a complete function that will log to the console the parity of your input.
const checkNumber = (x) => {
if(number%2 == 0){
//do something;
console.log('number is Even');
}else{
//do otherwise;
console.log('number is Odd');
}
}

var x = 2;
x % 2 ? oddFunction() : evenFunction();

Please write the following code in your console:
var isEven = function(deep) {
if (deep % 2 === 0) {
return true;
}
else {
return false;
}
};
isEven(44);
Please Note: It will return true, if the entered number is even otherwise false.

Use Modulus, but.. The above accepted answer is slightly inaccurate. I believe because x is a Number type in JavaScript that the operator should be a double assignment instead of a triple assignment, like so:
x % 2 == 0
Remember to declare your variables too, so obviously that line couldn't be written standalone. :-) Usually used as an if statement. Hope this helps.

array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
array.each { |x| puts x if x % 2 == 0 }
ruby :D
2
4
6
8
10

Related

How do multiple else if statements work in Javascript? [duplicate]

I want to check if a value is in an accepted range. If yes, to do something; otherwise, something else.
The range is 0.001-0.009. I know how to use multiple if to check this, but I want to know if there is any way to check it in a single if statement.
You're asking a question about numeric comparisons, so regular expressions really have nothing to do with the issue. You don't need "multiple if" statements to do it, either:
if (x >= 0.001 && x <= 0.009) {
// something
}
You could write yourself a "between()" function:
function between(x, min, max) {
return x >= min && x <= max;
}
// ...
if (between(x, 0.001, 0.009)) {
// something
}
Here is an option with only a single comparison.
// return true if in range, otherwise false
function inRange(x, min, max) {
return ((x-min)*(x-max) <= 0);
}
console.log(inRange(5, 1, 10)); // true
console.log(inRange(-5, 1, 10)); // false
console.log(inRange(20, 1, 10)); // false
If you must use a regexp (and really, you shouldn't!) this will work:
/^0\.00([1-8]\d*|90*)$/
should work, i.e.
^ nothing before,
followed by 0.00 (nb: backslash escape for the . character)
followed by 1 through 8, and any number of additional digits
or 9, followed by any number of zeroes
$: followed by nothing else
If you're already using lodash, you could use the inRange() function:
https://lodash.com/docs/4.17.15#inRange
_.inRange(3, 2, 4);
// => true
_.inRange(4, 8);
// => true
_.inRange(4, 2);
// => false
_.inRange(2, 2);
// => false
_.inRange(1.2, 2);
// => true
_.inRange(5.2, 4);
// => false
_.inRange(-3, -2, -6);
// => true
I like Pointy's between function so I wrote a similar one that worked well for my scenario.
/**
* Checks if an integer is within ±x another integer.
* #param {int} op - The integer in question
* #param {int} target - The integer to compare to
* #param {int} range - the range ±
*/
function nearInt(op, target, range) {
return op < target + range && op > target - range;
}
so if you wanted to see if x was within ±10 of y:
var x = 100;
var y = 115;
nearInt(x,y,10) = false
I'm using it for detecting a long-press on mobile:
//make sure they haven't moved too much during long press.
if (!nearInt(Last.x,Start.x,5) || !nearInt(Last.y, Start.y,5)) clearTimeout(t);
If you want your code to pick a specific range of digits, be sure to use the && operator instead of the ||.
if (x >= 4 && x <= 9) {
// do something
} else {
// do something else
}
// be sure not to do this
if (x >= 4 || x <= 9) {
// do something
} else {
// do something else
}
You must want to determine the lower and upper bound before writing the condition
function between(value,first,last) {
let lower = Math.min(first,last) , upper = Math.max(first,last);
return value >= lower && value <= upper ;
}
const inRange = (num, num1, num2) => Math.min(num1, num2) <= num && Math.max(num1, num2) >= num;
Could be like this if you want to make inRange inclusive and not depend on order of range numbers (num1, num2).

Check Odd numbers without modulo operator

I am creating a function that returns whether the passed in number is odd Without the modulo operator. The tricky part is that it should work for NEGATIVE numbers and ZERO.
here's my codes so far:
function testodd(num) {
return (num/2)*2==num;
}
var output = testodd(17);
console.log(output); // --> true
Am I making some mistakes here? Or is there a better way to do this?
you can use Bitwise operator and get same result. does this help.
<script type="text/javascript">
function oddOrEven(x) {
return ( x & 1 ) ? "odd" : "even";
}
console.log(oddOrEven(10));
</script>
For more detail about bitwise operator
Hi you can do it with bitwise AND (&) operator to check if a number is even or odd.
function testodd(num) {
if((num & 1) == 0){
return true
}
return false;
}
var output = testodd(17);
console.log(output); // --> false
var output = testodd(-16);
console.log(output); // --> true
var output = testodd(0);
console.log(output); // --> true
Try a bit-wise operation
function testodd(num) {
return num & 1; // num AND 0x1 checks for the least significant bit, indicating true or falsey
}
Remove the decimal part after division using Math.floor.
Math.floor(num / 2) * 2 === num;
For even numbers, there is no loss in decimal value. For odd numbers, decimal point value will be lost and comparison will falsy.
Here is a horribly inefficient method using recursion:
function checkOdd(num)
{
num = Math.abs(num);
if(num==0)
return false;
else if(num==1)
return true;
else
return checkOdd(num-2);
}
Of course you should never use it.
Since there's already an answer I will show you an alternative away of doing it with regex
function checkOdd(num){
console.log(/^\d*[13579]$/.test(num));
}
checkOdd(105);
Would only work with reasonably sized integers
Try
function testodd(num){
if num < 0{
var number = -num
}
int i = 1;
int product = 0;
while (product <= num)
{
product = divisor * i;
i++;
}
// return remainder
return num - (product - divisor);
}
Use this function to check if a number is odd or even, without using the modulo operator %. This should work for negative numbers and zero.
function checkOdd(num) {
// your code here
if(num<0){ //Check if number is negative
num=-num; //Convert it into positive number
}
let b=Math.floor(num/2) //Taking value for loop iteration
for(var i=1;i<=b;i++){
num=num-2; //Will check the number is odd if it subtraction end to 1 by decrementing -2 to the number
if(num==1){
return true; //return true if number is odd
}
}
return false; //return false if number is even
}
You can use isInteger method
function isEven(n){
return Number.isInteger(n / 2);
}
function odd(num) {
if (num === 0) {
return false;
}
num = Math.abs(num);
while (num >= 2) {
num = num - 2;
}
if (num === 1) {
return true;
} else {
return false;
}
}
Even number
lets take an even number say 6;
6 divided by 2 is 3;
Math.round(3) is 3;
Math.floor(3) is 3;
3===3 eveluates to true so 6 is an even number;
Odd number
lets take an odd number say 9;
9 divided by 2 is 4.5;
Math.round(4.5) is 5;
Math.floor(4.5) is 4;
5===4 evaluates to false so 9 is an odd number;
function evenChecked(num) {
if (Math.round(num / 2) === Math.floor(num / 2)) {
return `${num} is even`;
} else {
return `${num} is odd`;
}
}
console.log(evenChecked(23));
console.log(evenChecked(90));
console.log(evenChecked(56));
console.log(evenChecked(49));

Javascript: not grokking modulo in action

I understand the basic concept of modulo: It give you the remainder with division. I don't seem to be able to grasp how to use it correctly in practice. For instance, the following code takes a number and if it divides evenly by 2 it will return true, otherwise it returns false:
if(number % 2){
return false;
}
else{
return true;
}
It seems to me intuitively (and wrongly) that the way you would code it would be to set it so the modulo works out to 0:
if (number/2 %0) {
return true
Can anyone explain how and why the first one is correct? Keep in mind that I am obviously extremely dense ...
To check if a number divides without leaving a remainder you need to check if the result of the modulo devision is equal to zero.
if ((number % 2) == 0){
return true; // number was even
} else {
return false; // number was odd
}
From mdn % remainder documentation:
The remainder operator returns the first operand modulo the second operand, that is, var1 modulo var2, in the preceding statement, where var1 and var2 are variables. The modulo function is the integer remainder of dividing var1 by var2.
Taking that in mind, here are the results of using % with a few values:
59 % 2
> 1
60 % 2
> 0
0 is a falsey value in javascript, so the the result of 60 %2 is never going to pass your if test. To make a proper comparison you'll need to directly check if you have a value of 0:
if (number % 2 === 0)
return true
When you use the modulo (%) operator, you are basically saying:
number % x:
Divide number by x. Round the result down to nearest integer. Multiply that integer by x. Give me the distance (absolute value) of this number to the original number.
This might not be the exact mathematical definition of modulo, but I would like to believe it is pretty close for our needs.
To give a few examples...
2 % 2 = 0 (2 / 2 = 1, 1 * 2 = 2, abs(2 - 2) = 0)
3 % 2 = 1 (3 / 2 ≐ 1, 1 * 2 = 2, abs(2 - 3) = 1)
4 % 2 = 0 (4 / 2 = 2, 2 * 2 = 4, abs(4 - 4) = 0)
The problem with your notation is that it is one extra operation that needs to be performed by the programmer. Since the current way we express the modulo operation is quite concise and does not require us to do any divisions ourselves, there is potential for performance optimisations to be done under the hood.
To express what I believe is your intent, you basically calculate the modulo with the current syntax and compare it to a particular value:
if (number % 2 === 0)
return true // Yup, its divisible by 2
Building on top of the other answers, I'd like to mention that using an if / else to explicitly return a boolean value, when you've already evaluated a boolean value, is overly verbose.
If all you are doing in the if / else is returning a boolean on either side, then your return expression can be reduced.
Good:
function isEven(num) {
return (num % 2 === 0);
}
function isOdd(num) {
return (num % 2 !== 0);
}
Bad:
function badIsEven(num) {
if (number % 2 === 0) {
return true;
} else {
return false;
}
}

Javascript return and ternary operator with var, possible?

I'm sorry if this question is a duplicate, but I really don't know how to search for it. This question may sound "odd" for an expert JavaScript programmer, but I'm not.
I'm basically trying to do a "one line return", without wasting another line of code. I know that it's not good, and the following it's not code for production:
var _ = require('underscore');
module.exports = function (digits) {
if (!/^\d+$/.test(digits)) return undefined;
var precomp = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9];
var sum = _.reduce(digits.toString(), function (mem, dgt, idx) {
return mem + (idx % 2 == 0 ? parseInt(dgt) : precomp[dgt]);
}, 0);
return (var mod = sum % 10 == 0) ? 0 : 10 - mod; // Error
};
The last line throws an error because the var keyword. I remember doing sometimes the same in PHP.
EDIT: I don't think so "hard" to read the question before answer... I'm asking if it's possible, I'm not saying it's right, good looking, or whatever.
(By the way this is the luhn check calculation)
VariableDeclaration are not expressions. Just declare it before.
module.exports = function (digits) {
var mod;
// ...
return (mod = sum % 10 ...
}
I think you're trying too hard here. Just move var mod before the return statement. You're NOT going to be struck dead by the software gods for having one more line of code here. Clarity over conciseness.
JavaScript is not PHP
var mod = sum % 10;
return (mod === 0) ? 0 : 10 - mod;
I think the only way for you to do this is:
var mod = sum % 10;
return (mod == 0) ? 0 : 10 - mod;
Who cares about one extra line of code? Why does that matter?
I see you don't like any of the answers so far. One way to avoid declaring the variable first is this, which you probably won't like either:
return (sum % 10 == 0) ? 0 : 10 - (sum % 10);
This doesn't require an extra line, but it does require an extra mod.
Another option, which might make the code extemely confusing, is to add a dummy argument to the function:
module.exports = function (digits, mod) {
/* code */
return (mod = sum % 10) == 0 ? 0 : 10 - mod; // Error
};
Since you don't use sum for any other purpose, you could move the % operator up, doing:
var _ = require('underscore');
module.exports = function (digits) {
if (!/^\d+$/.test(digits)) return undefined;
var precomp = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9];
var sum = _.reduce(digits.toString(), function (mem, dgt, idx) {
return mem + (idx % 2 == 0 ? parseInt(dgt) : precomp[dgt]);
}, 0) % 10;
return (sum == 0) ? 0 : 10 - sum; // Error
};

Find if variable is divisible by 2

How do I figure out if a variable is divisible by 2? Furthermore I need do a function if it is and do a different function if it is not.
Use modulus:
// Will evaluate to true if the variable is divisible by 2
variable % 2 === 0
Seriously, there's no jQuery plugin for odd/even checks?
Well, not anymore - releasing "Oven" a jQuery plugin under the MIT license to test if a given number is Odd/Even.
Source code is also available at http://jsfiddle.net/7HQNG/
Test-suites are available at http://jsfiddle.net/zeuRV/
(function() {
/*
* isEven(n)
* #args number n
* #return boolean returns whether the given number is even
*/
jQuery.isEven = function(number) {
return number % 2 == 0;
};
/* isOdd(n)
* #args number n
* #return boolean returns whether the given number is odd
*/
jQuery.isOdd = function(number) {
return !jQuery.isEven(number);
};
})();​
You don't need jQuery. Just use JavaScript's Modulo operator.
You can use the modulus operator like this, no need for jQuery. Just replace the alerts with your code.
var x = 2;
if (x % 2 == 0)
{
alert('even');
}
else
{
alert('odd')
}
You can do it in a better way (up to 50 % faster than modulo operator):
odd: x & 1
even: !(x & 1)
Reference: High Performance JavaScript, 8. ->Bitwise Operators
You can also:
if (x & 1)
itsOdd();
else
itsEven();
if (x & 1)
itIsOddNumber();
else
itIsEvenNumber();
Hope this helps.
let number = 7;
if(number%2 == 0){
//do something;
console.log('number is Even');
}else{
//do otherwise;
console.log('number is Odd');
}
Here is a complete function that will log to the console the parity of your input.
const checkNumber = (x) => {
if(number%2 == 0){
//do something;
console.log('number is Even');
}else{
//do otherwise;
console.log('number is Odd');
}
}
var x = 2;
x % 2 ? oddFunction() : evenFunction();
Please write the following code in your console:
var isEven = function(deep) {
if (deep % 2 === 0) {
return true;
}
else {
return false;
}
};
isEven(44);
Please Note: It will return true, if the entered number is even otherwise false.
Use Modulus, but.. The above accepted answer is slightly inaccurate. I believe because x is a Number type in JavaScript that the operator should be a double assignment instead of a triple assignment, like so:
x % 2 == 0
Remember to declare your variables too, so obviously that line couldn't be written standalone. :-) Usually used as an if statement. Hope this helps.
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
array.each { |x| puts x if x % 2 == 0 }
ruby :D
2
4
6
8
10

Categories