What does the zero refer to in the code below - javascript

I know this is a very basic question but what does the 0 refer to in the code below
var even = arr.filter(function(val) {
return 0 == val % 2;
});

what does the 0 refer to
Here 0 refers to the Number 0.
0 == val % 2
will evaluate to true or false which you are returning.

0 is the tested value of val modulus (%) 2. When there is no "remainder", as with even numbers, it will return the number 0. For odd numbers it will have a remainder of 1 and the function will return false to filter().

The % is the modulus operator, it works like this
The remainder operator (modulus) returns the first operand modulo the
second operand, that is, var1 modulo var2. The modulo function
is the integer remainder of dividing var1 by var2
MDN
In other words, if val can be divided by 2, the modulus operator returns 0 as there is no remainder, that's why it checks for a zero
Turning the yoda condition around, it makes more sense
val % 2 === 0; // can be divided by 2, so it's even, returns boolean
For instance if val was 4, 16, 200 etc, it would be true, as 4 can be evenly divided by 2.
If val was 3, 9, 201 etc. it would be false, as 3 can not be evenly divided by 2.

0 is just a number which is compared to right hand side expression val % 2
statement 0 == val % 2; returns true if val % 2 is 0 (value of val is even), or returns false is val % 2 is 1 (value of val is odd)
Just for information: Modulo operator returns the remainder(a number) when val is divided by any number

Related

Why do both these two solutions for printing all numbers divisible by 3 AND 5 between 5 and 50 work?

This was my solution to the problem:
var count = 5;
while (count <= 50) {
if ((count % 3 || count % 5) === 0) {
console.log(count);
}
count++;
}
This was my the instructors solution:
var count = 5;
while (count <= 50) {
if (count % 3 === 0 && count % 5 === 0) {
console.log(count);
}
count++;
}
Both of these solutions gave the proper answer, but I question why || worked in my problem, rather than &&, I tried both. && means both need to be true for it to properly run, right? So wouldn't that have been the proper use?
var count = 5;
while(count <= 50) {
console.log(`count = ${count} | (count % 3 || count % 5) = ${(count % 3 || count % 5)}`);
if((count % 3 || count % 5) === 0) {
console.log(count);
}
count++;
}
This happens because in all cases where count % 3 === 0 and count % 5 does not, the number takes precedence in the or (||) statement since it's "truthy".
eg.
count = 6, 0 || 1 // 1, since 0 is "falsy"
count = 8, 2 || 3 // 2
count = 15, 0 || 0 // 0
Therefore, it seems you stumbled on the correct solution.
It is a javascript peculiarity you encounter. If count % 3 is 0 it is considered "falsy" and the other calculation will be used. So if either modulus has a remains, that value is used in the final test against 0.
So while both works, your teachers code is more readable; thus better.
The following code
(count % 3 || count % 5) === 0
evaluates first the % operations and then the or to end with ===. If both modulo operations return 0, the or condition also evaluates as 0, that compared with 0 equals true and print the numbers. Otherwise, if any of the modulo values isn't 0, the or operation will result in these numbers, hence it won't be printed.
This is because Javascript evaluates numeric values as boolean being 0 False, and any other value True.
In your case it's a question of parenthesis
1st case of || with parenthesis like this ((count % 3 || count % 5) === 0) it like you say count has to be % by 3 and 5 so it's like &&
2nd case (count % 3 === 0 && count % 5 === 0) you've changed the parenthesis to regroup all
with && in the middle
so as i said it's question of parenthesis that makes both solution give the same result
Every value except 0 is evaluated as true. If there is a number divisible by 3 AND 5 both, then 0 || 0 is 0, which makes your if condition to run. If there is a number that is only divisible by 3 OR 5, lets say 10, then 10%3 is equal to 10 and 10%5 is equal 0. 10 || 0 will be evaluated as true (non-zero). Since non-zero value is not equal to 0 therefore if condition will not execute.
I am not sure but your instructors expression can be said as created from your expression by using Demorgans law.
The second solution is more useful than the first.
Because always "%" operator is computational, not logical

What is the best way to determine if a given number is a power of two?

Is there a more effective way to return true if n is a power of two or false if not?
function isPowerOfTwo(n) {
return Math.pow(2, Math.round(Math.log(n) / Math.log(2)));
}
You can actually use ECMAScript5 Math.log:
function powerOfTwo(x) {
return (Math.log(x)/Math.log(2)) % 1 === 0;
}
Remember, in math, to get a logarithm with an arbitrary base, you can just divide log10 of the operand (x in this case) by log10 of the base. And then to see if the number is a regular integer (and not a floating point), just check if the remainder is 0 by using the modulus % operator.
In ECMAScript6 you can do something like this:
function powerOfTwo(x) {
return Math.log2(x) % 1 === 0;
}
See the MDN docs for Math.log2.
Source: Bit twiddling Hacks,
function powerOf2(v) {
return v && !(v & (v - 1));
}
You just bitwise AND the previous number with the current number. If the result is falsy, then it is a power of 2.
The explanation is in this answer.
Note:
This will not be 100% true for programming, mathematical, [also read 'interviewing']. Some edge cases not handled by this are decimals (0.1, 0.2, 0.8…) or zero values (0, 0.0, …)
Using bitwise operators, this is by far the best way in terms of efficiency and cleanliness of your code:
function PowerofTwo(n){
return ((x != 0) && !(x & (x - 1)));
}
what it does is checks the bits that make up the number, i.e. 8 looks like this:
1 0 0 0
x-1 or 7 in this case looks like this
0 1 1 1
when the bitwise operator & is used it invokes an && on each bit of the number (thus 1 & 1 = 1, 1 & 0 = 0, 0 & 1 = 0, 0 & 0 = 1):
1 0 0 0
-0 1 1 1
=========
0 0 0 0
since the number turns into an exact 0 (or false when evaluted as a boolean) using the ! flag will return the correct answer
if you were to do this with a number like 7 it would look like this:
0 1 1 1
-0 1 1 0
=========
1 1 1 0
returning a number greater than zero causing the ! flag to take over and give the correct answer.
A number is a power of 2 if and only if log base 2 of that number is whole. The function below computes whether or not that is true:
function powerOfTwo(n){
// Compute log base 2 of n using a quotient of natural logs
var log_n = Math.log(n)/Math.log(2);
// Round off any decimal component
var log_n_floor = Math.floor(log_n);
// The function returns true if and only if log_n is a whole number
return log_n - log_n_floor == 0;
}
Making use of ES6's Math.clz32(n) to count leading zeros of a 32-bit integer from 1 to 2³² - 1:
function isPowerOf2(n) {
return Math.clz32(n) < Math.clz32(n - 1);
}
/**
* #param {number} n
* #return {boolean}
*/
const isPowerOfTwo = function(n) {
if(n == 0) return false;
while(n % 2 == 0){
n = n/2
}
return n === 1
};
function PowerOfTwo(n){
// Exercise for reader: confirm that n is an integer
return (n !== 0) && (n & (n - 1)) === 0;
}
console.log(PowerOfTwo(3))
console.log(PowerOfTwo(4))
This is for a specific online course that requires an answer in a specific way.
Without using libraries and other methods just loops and .push.
you need to create an inner loop using while
it should start with 1
keep multiplying it with 2 until i,j,k or whatever is greater than the current number(array) so it will have to do 2 4 6 8 10 12 14 16 18 until it is greater than the number
then it will go to the outer loop then repeat again until
const numbers = [5, 3, 9, 30];
const smallestPowerOfTwo = arr => {
let results = new Array;
// The 'outer' for loop -
for (let i = 0; i < arr.length; i++) {
number = arr[i];
// The 'inner' while loop
j = 1;
while (j < number) { //starting from 1 then multiplied by 2 then by 2 again untill it is more than the number
j = j * 2;
}
results.push(j);
}
return results
}
console.log(smallestPowerOfTwo(numbers))

Understanding this Javascript code using % modulus

Im currently in process of learning Javascript. And I have seen the following code, which confuses me.
Description of code:
Starting on line 1, the function isOdd takes a number n and returns a boolean (true or false) stating whether the number is odd or not.
Code
var isOdd = function (n) {
if (n % 2 === 0) {
return false;
} else {
return true;
}
};
var isEven = function(n) {
if(n % 2 === 0) {
return true;
} else {
return false;
}
};
Where I am confused.
The code:
n % 2 === 0
I have always taken the following to be the description for %:
% Is the modulus operator. It returns the remainder of dividing number1 by number2.
Which would mean that the if statement in the function isOdd returns false is the difference between n and 2 is 0. But its meant to mean if n is divisible by 2 (even) return false.
I just dont see how its doing that.
In my mind, if we take the even number 30. Apply it to n % 2. We get 15, which is remainder of dividing 30 by 2. 15 does not equal 0, but 30 is an even number, and with this code it would be seen as odd.
Can someone explain this?
The line in question:
if (n % 2 === 0) {
return false;
}
Means "if when you divide n by 2 the remainder is zero, then return false (i.e. n is not odd)".
The "remainder" is whatever is left over when you subtract the nearest multiple, so for example "64 % 10" is 4, since the nearest multiple of 10 is 60, leaving 4.
Taking your example and putting it another way, 30/2 is 15, 30%2 is zero (i.e. whatever is left over after 30/2). Here's more info on the remainder after division.
You're confusing Quotient and Remainder.
When you divide 30 by 2, integer quotient is 15, and remainder is 0. You can also calculate remainder by multiplying integer quotient by divisor and subtracting it from dividend. So for this division remainder is 30 (dividend) - 15 (quotient) * 2 (divisor) = 0.
If n can be divided by 2 it means it's even ->
which means it's not odd ->
isOdd is false

What does % do in JavaScript?

What does the % do in JavaScript?
A definition of what it is and what it does would be much appreciated.
It's a modulo operator. See this documentation or the specification for more information on JavaScript arithmetic operators.
% (Modulus)
The modulus operator is used as follows:
var1 % var2
The modulus 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. For example, 12 % 5 returns 2. The
result will have the same sign as var1; that is, −1 % 2 returns −1.
ES6 Update:
As explained in other answers, it returns the remainder after dividing the dividend by divisor, however this is no longer modulo operator, this is remainder operator. the difference being that the modulo operator result would take the sign of the divisor, not the dividend.Quoted from MDN
The remainder operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend, not the divisor. It uses a built-in modulo function to produce the result, which is the integer remainder of dividing var1 by var2 — for example — var1 modulo var2. There is a proposal to get an actual modulo operator in a future version of ECMAScript, the difference being that the modulo operator result would take the sign of the divisor, not the dividend.
Example:
-10 % 3 // -1
10 % -3 // 1
It returns the remainder of a division operation. 5%2 returns 1
It is a modulo operator.
It calculates the remainder.
If we do 23 % 10,
first, we divide 23 by 10 which equals 2.3
then take .3 * (the divisor) 10
= 3
That would be the modulo operator.
It returns the remainder of a division operation:
var remainder = 3 % 2; // equals 1
In JavaScript, % is a remainder operator (Not a modulo operator).
remainder operator % (uses Math.truc()):
remainder = -5 % 3 = -2
How is it calculated ?
quotient = Math.trunc(dividend / divisor) = Math.trunc(-5 / 3) = -1;
remainder = dividend - divisor * quotient = -5 - (3 * -1) = -2
modulo function (uses Math.floor()):
modulo(-5,3) = 1
How is it calculated ?
quotient = Math.floor(dividend / divisor) = Math.floor(-5 / 3) = -2;
remainder = dividend - divisor * quotient = -5 - (3 * -2) = 1
For positive numbers, both remainder operator and modulo gives the same result.
5 % 3 = 2
modulo(5,3) = 2
In JavaScript, there is no build-in function for doing modulo operation, so you need to write on your own by using Math.floor() as above. Alternatively even you could easily write using the remainder operator as shown below.
function modulo(n, m) {
return ((n % m) + m) % m;
}
Just in case, if someone is looking for a real modulo function (which would always get the sign of the divisor), you can use this:
function Modulo(num, denom)
{
if (num%denom >= 0)
{
return Math.abs(num%denom);
}
else
{
return num%denom + denom;
}
}
The Math.abs is to prevent the case -12%12 → -0, which is considered equal to 0 but displayed as -0.
Modulus (%) operator returns the remainder.
If either value is a string, an attempt is made to convert the string to a number.
alert(5%3) will alert 2
% performs as the modulo operator, return division reminder. Example:
<script>
var x = 5;
var y = 2;
var z = x % y;
alert(z);
</script>
This will alert 1.
This is what I would do to getModulus, given k > 0. I find it more intuitive as Math.floor(num / k ) in js is exactly num // k in python.
function getModulus(num, k) {
return num - Math.floor(num / k ) * k
}

how to convert -1 to 1 with javascript?

how to convert -1 to 1 with javascript ?
var count = -1; //or any other number -2 -3 -4 -5 ...
or
var count = 1; //or any other number 2 3 4 5 ...
result should be
var count = 1; //or any other number 2 3 4 5 ...
count = Math.abs(count)
// will give you the positive value of any negative number
The abs function turns all numbers positive: i.e Math.abs( -1 ) = 1
Alternative approach (might be faster then Math.abs, untested):
count = -5;
alert((count ^ (count >> 31)) - (count >> 31));
Note that bitwise operations in javascript are always in 32-bit.
If the number of interest is input... In addition to Math.abs(input)....
var count = (input < 0 ? -input : input);
jsFiddle example
(edit: as Some pointed out -input is faster than -1 * input)
The above makes use of the Javascript conditional operator. This is the only ternary (taking three operands) Javascript operator.
The syntax is:
condition ? expr1 : expr2
If the condition is true, expr1 is evaluated, if it's fales expr2 is evaluated.

Categories

Resources