Javascript Function not defined error in code - javascript

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)

Related

Checking divisibility and converting digits into text

Check the divisibility of 2, 3, and both 2 and 3
Divisible by 2 - print x
Divisible by 3 - print y
Divisible by 2 and 3 - print xy
let num = prompt('1-1000');
if (num %2 == 0 )
{
console.log("X")
}
if (num %3 == 0 )
{
console.log("Y")
}
if (num %3 == 0 && num %2 ==0)
{
console.log("XY")
}
Example:
Input: 6
Output:
X
Y
XY
How to make it not print X, Y but XY?
What needs to be done so that several digits to be checked after the decimal point can be entered and then converted to the appropriate letters?
There are a couple of ways you could do this.
One way would be to use a ternary operator to output the values X and/or Y. This will have X logged only when divisible by 2, and Y only logged when divisible by 3. If it is divisible by both, both are shown but their conditions are independent of each other. And using template literals it is concatenated into 1 value.
let num = prompt('1-1000');
console.log(`${(num%2==0)?"X":""}${(num%3==0)?"Y":""}`);
Alternatively, you could use something like what was mentioned in the comments. If you convert the code to a function, you can move the final if statement to the top and use exit/return statements to return only 1 of the values (whichever applies).
const _Check = () => {
let num = prompt('1-1000');
if(num % 3 == 0 && num % 2 == 0) return "XY";
if(num % 2 == 0 ) return "X";
if(num % 3 == 0 ) return "Y";
return "";
}
console.log(_Check());
EDIT
In reponse to a comment by OP: checking for multiple numbers could be done by splitting the value input by the user and then looping through those values.
If the user will be inputting each number separated by a space, you can use the split() method with a space as the separator. And then use forEach() to loop through each number and apply the code/logic we have used earlier.
Example Using ternary operator and template literals:
let num = prompt('1-1000')
num.split(" ").forEach(n => {
console.log(`${(n%2==0)?"X":""}${(n%3==0)?"Y":""}`);
})
Example using a function and return statements:
let num = prompt('1-1000')
const _Check = n => {
if(n %3 == 0 && n %2 ==0) return "XY";
if(n %2 == 0 ) return "X";
if(n %3 == 0 ) return "Y";
return "";
}
num.split(" ").forEach(n => {
console.log(_Check(n));
})

javascript code, create a function that returns a boolean depending on whether or not a number is even or not?

var i = 1;
var numberCounter = 0
function isEven(num){
if (i % numberCounter === 0) {
console.log('true');
} else { console.log('false');
}
console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));
Im not exactly sure where i went wrong here, i am trying to create a function that returns a boolean depending on whether or not a number is even or not.
in order to check if a number is even or not you should check to see if the modulo of 2 with the number is 0. other then that in order to return a value from a function you should use the keyword return. therefor the isEven function should be:
function isEven(num){
return num % 2 === 0;
}
console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));
(even number) % 2 = 0 and with ! you will the 0 as 1 in boolean.
% => module
/ => division
const isEven = number => !(number % 2)
isEven(2) // true
const isOdd = number => !!(number % 2)
isEven(3) // true
In your code :
var i = 1;
var numberCounter = 0
function isEven(num){
if (i % numberCounter === 0) {
console.log('true');
} else { console.log('false');
}
Note that i is equal to 0 and numberCounter is equal to 0. No matter which number is passed in your function, its value won't be considered.
You want to define if a number is odd or even. As a matter of fact the number you want to estimate is the parameter of the function.
A basic definition would be that an odd number can be divided by 2. It means that the remainder of the division is equal to 0.
the if statement concerns the num (passed as parameter) and the remainder.
I took your code and modified it. Saar Davidson answer is much more better and effective (in a single line).
function isEven(num){
if (num % 2 === 0) {
console.log('true');
return true;
} else {
console.log('false');
return false;
}
}

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

How to increment a conditional statement based on the five times table?

I am trying to achieve the following within my conditional statement:
if (changeCount == 5 || changeCount == 10 || changeCount == 15 || changeCount == 20) {
Do Something
}
I want to let the conditional statement pass if the value of the changeCount is any number in the five times table.
At the moment I have used the || however this is no good because I need it to be infinite.
I feel like a noob asking this question but any help would be great.
Thanks
Use the remainder operator (also known as the mod operator)
if (changeCount % 5 === 0) {
// do something
}
It works by dividing arg1 by arg2, and returning the remainder. If the remainder is 0, then it divides evenly.
If you wanted to limit the range of changeCount and still ensure that it is divisible by 5, you could do something like this:
if (changeCount >= lowerBound
&& changeCount <= upperBound
&& changeCount % 5 === 0) {

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

Categories

Resources