Javascript Odd or even Algorithm question? - javascript

I already know this wouldn't work If I passed something like 0 or 1, but why wouldn't it work If it managed to work with 2 and 7.
I'm still new to Javascript programming so I'm just trying to figure out why adding
if(number = number % 2 == 0) or the other wouldn't work.
Here's the code:
function even_or_odd(number) {
if(number = number % 2 == 0) {
return "Even"
}else if(number = number % 2 !== 0) {
return "Odd"
}
};

= is an assignment operator. It assigns the value of the expression on the right-hand side to a variable on the left-hand side.
== is an equality operator. It tests the equality of the result of both the left and right-hand-side expression.
Since you're using = and inadvertently assigning number to the value of your expression on the right, it will always evaluate to a truthy value and return "Even". To fix, remove the number = from each of the expressions:
function even_or_odd(number) {
if(number % 2 == 0) {
return "Even"
}else if(number % 2 !== 0) {
return "Odd"
}
};
console.log(even_or_odd(0));
console.log(even_or_odd(1));
MDN has a great section on this in their if...else page:
It is advisable to not use simple assignments in a conditional expression, because the assignment can be confused with equality when glancing over the code. For example, do not use the following code:
if (x = y) {
/* do something */
}
If you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment. For example:
if ((x = y)) {
/* do something */
}

Related

Why is my variable returning 'false' when using an && operator

I am learning basic conditionals and i'm not 100% sure on why the && in this case is returning 'false' in console.
Is it because the variable is not both 0 and 1.
Thank you in advance,
let i = 1;
if (i == 0 && i == 1) {
console.log('true');
} else {
console.log('false');
}
I was expecting true.
Even if I set var i = 01; it still shows false.
I just need a simple explanation why to get it clear in my head :)
i is not equal to 0, therefore the logical AND expression immediately fails; the else block is then evaluated, printing false.
If you change AND to OR, the code will work as you probably expect.
let i = 1;
if (i == 0 || i == 1) {
console.log('true');
} else {
console.log('false');
}
For an AND (&&) expression to evaluate to true, both sides of the expression need to be true.
For an OR (||) expression to evaluate to true, one or both side(s) of the expression need(s) to be true.
For an XOR (JS does not have a logical XOR operator) expression to evaluate to true, one and only one side of the expression needs to be true.
Note: in JS, never attempt to write a number literal with a leading zero. This is because in non-strict mode environments such numbers are interpreted as octal numbers; in strict-mode environments you'll get an error.
How would i be able to be two values at once? Even if you did something like const i = [0, 1] it would still return false.
i = 01
Why would this work? The only way this would work is if you made it a string, split it, assigned it to two different variables, and then ran the check against those two variables.
Perhaps you are thinking of the OR operator ||.
let i = 1;
if (1 === 0 || i === 1) {
return true;
} else {
return false;
}
Or even use ternaries, which are, from looking at this question, way beyond your skill:
let i = 1;
const j = i === 0 || i === 1 ? true : false;
console.log(j);

Using conditional operator to run more than one statement will not work

function isPrime(num) {
//TODO
let primeNum = false;
let prime = (num == 0 || num == 1) ? primeNum = false : (num == 2) ? console.log("2 is prime") :
(num % 2 == 0) ? console.log("num is divisable by 2 therefore is not prime") : {
console.log("number may be prime");
primeNum = true;
}
return primeNum;
}
Im attempting a challenge off of codewars to test if a num is prime. On my final conditional I want to print to console and set a value to primeNum. It seems to work fine if i do one or the other but not both.
I know its possible to do by writing a separate function containing both statements and having it be called instead or that I could use if and else statements but I'm trying to follow best practices here.
If you have to execute multiple things inside a single expression (such as inside one of the parts of the conditional operator), you may use the comma operator inside of parentheses. For example:
const condition = false;
const result = condition ? 'foo' : (
console.log('falsey!'),
'bar'
);
console.log(result);
Or, for your code:
function isPrime(num) {
const primeNum = (num == 0 || num == 1)
? false
: (
num == 2
? ( console.log("2 is prime"), true)
: (
num % 2 == 0
? (console.log("num is divisable by 2 therefore is not prime"), false)
: (console.log("number may be prime"), null)
)
);
return primeNum;
}
const result = isPrime(4);
console.log('4:', result)
But this is not a good idea - it's hard to read, and is not best practice. Better to use standard if/else statements instead.
Adding some brackets should to the trick, or your interpreter doesn't know what belongs to which expression.
Nested ternaries is not exactly best practices. Consider multiple if() return x;

How can a "return" know to give me true or false?

How the 'return' to give me true or false without an 'if' statment like in the first example?
Example'1':
function isEven(){
if(num % 2 === 0){
return true;
} else {
return false;
}
}
And it works, but then my teacher shorten it up like this (ex-'2'):
function isEven(){
return num % 2 === 0
}
You can return anything from the function. Please refer to the Example below to understand it.
function myFunction(val) {
console.log(test(val))
}
function test(val){
if(val==1) return 'testing';
if(val == 2) return true;
if(val == 3) return 1>2;
if(val == 4) return 2%3 == 0;
}
<button onclick="myFunction(1)">Test1</button>
<button onclick="myFunction(2)">Test2</button>
<button onclick="myFunction(3)">Test3</button>
<button onclick="myFunction(4)">Test4</button>
not a real answer, just trying to help, so don't upvote please!
I think the easiest way of understanding the basics of programming is to go back to daily life examples, so here is one:
You are talking to a friend, lets call him Bob. Bob owns an ice cream shop. It's summer. You want ice cream, so you ask him if you can get one. Bob tells you:
If there is Ice left, i can give you some, otherwise i can't.
function canIGetIceCream() {
if(isIceCreamLeft) {
return true;
} else {
return false;
}
}
However, Bob could also shorten his answer without changing the meaning:
Depends on the ice left
function canIGetIceCream() {
return isIceCreamLeft;
}
Booelans are just values, just like numbers or strings. In the first example if isIceCreamLeft is true, it will enter the first if branch and then return true, otherwise if it is false it will return false. Instead you could just return the value the boolean is holding like in the second example.
You don't really ask it by using an if statement. An if statement just checks if what's between the brackets ( ) is either true or false. Like how an addition 1 + 2 results in 3, something like 3 === 2 results in false. You can view it as a normal mathematical problem which has an answer. When your computer evaluates:
num % 2 === 0
It calculates num % 2 and checks if that's equal to 0. This can be either true or false. These are both boolean values, and are the same as in your first example. So what your first example is really doing is checking if the expression is either true or false and then returning that exact value, like so:
var num = 2;
if(num % 2 === 0){
return true;
}
After evaluation, this will basically result in:
if(true){
return true;
}
See how it's easier to just leave out the if statement and return the result of num % 2 === 0?
The thing you need to understand here is how operators work.
Operators operate on operands. An operator and one or more operands form an expression. Expressions are evaluated.
The return statement takes an expression and returns the value that the expression evaluates to. For example, 1 + 2 evaluates to 3.
Comparison and logical operators, like ==, <, and &&, generally evaluates to true or false. These work similarly: true && false evaluates to false, 1 == 1 evaluates to true.
Therefore, return num % 2 == 0 is completely valid because when the code is executed, num % 2 will be evaluated, then the whole expression will be evaluated to either true or false. You can think of the whole statement becoming
return true;
or
return false;
after the expression is evaluated.
You have an evaluation here of
num % 2 === 0
The code will check if the remainder of num divided by 2 (num % 2) is equal to 0. This can be true or false, hence it will return true of false.

Null and Booleans operator

I'm really new at programming and although I understand the concepts I have some trouble putting them in practice. For example I understood the concept of null and undefined values... and booleans operators.. all good!!! but when it comes to simple exercise I get stuck.
For example I got this :
Write an expression that evaluates x, so long as x is not null; if x is null, the expression should evaluate to 100. x is equal to null when no value has been assigned to it (e.g. var x;), but you could also assign it the value of null (var x = null;). Test your expression for several different values of x, including null - does it behave like you expect?
This is what I did:
var x ;
myExpression = (x - 50 + 20 + 30);
if (x === null) {
myExpression === true;
}
else if (x !== null) {
myExpression === 50;
}
It doesn't look right to me at all , and I know it's not. I think my real problem is understanding the problem itself. Can you please try to help me understanding it?
Thank you very much!
You are making this too hard. The expression:
((x == null) ? 100 : x)
A sample use:
y = ((x == null) ? 100 : x);
Your assignment said:
Write an expression that evaluates x, so long as x is not null; if x is null, the expression should evaluate to 100.
An expression is something which evaluates to a value. The number 6 is an expression. A variable, like x is an expression. More complicated expressions can be built using mathematical operators, for example 6 + x and so on.
The ternary (or "question mark") operator is a very powerful tool for building expressions.
condition ? value1 : value2
this works like something like a "mini-function":
function questionmark ( condition ) {
if ((condition) != 0) {
return value1;
} else {
return value2;
}
}
So:
(x == null) ? 100 : x
evaluates to 100 if x is null and the value of x otherwise.
Think of this expression as using 100 as the default value for something -- for example, we are going to do something x times, but if they haven't told us x we'll do it 100 times.
You should see that
(x != null) ? x : 100
is an equivalent expression.
In JavaScript there are more compact ("trickier") ways to write this kind of expression. I include them here just so you might recognize them if you see them in code:
(x ? x : 100)
(x || 100)

Why won't my if/else statement work? (JavaScript)

I'm trying to code a script to test whether a user-inputted number is prime or not. I'm coding several different primality tests, but one in particular is giving me a hard time.
function isPrimeSix() {
var numberPrimeSix = document.getElementById("primeSixInput").value;
var loopCount = 0;
for (var i = 1; i < Math.floor((numberPrimeSix / 6) + 1) + 1; i++)
{
if (numberPrimeSix === (6 * i) + 1)
{
//Irrelevant code here//
}
else if (numberPrimeSix === (6 * i) - 1)
{
//More irrelevant code//
}
else
{
loopCount++
}
};
if (numberPrimeSix === 2 || numberPrimeSix === 3 || numberPrimeSix === 5 || numberPrimeSix === 7)
{
alert(numberPrimeSix + " is prime.");
}
else if (prime === false || loopCount === Math.floor((numberPrimeSix / 6) + 1))
{
alert(numberPrimeSix + " is not prime.");
}
else if (prime === true)
{
alert(numberPrimeSix + " is prime.");
}
else
{
alert("Error");
};
}
Every time the for loop goes around, the embedded if statement will not evaluate, even if for that particular value of i one of the statements is true. Regardless of what number is assigned to numberPrimeSix, the script will always go to the else section of the loop, meaning that an alert will pop up telling me that the number is not prime (because the value of loopCount is equal to the value defined by the last if statement).
Can anyone tell me why this is? I hope this makes sense, and if the 'irrelevant code' is needed I'll provide it. Thanks!
A string will never be exactly equal (===) to a number. In JavaScript, if you use ==, the operands will be converted to be the same type before comparing. If you instead use ===, that step will be skipped and instead they will be tested for strict equality, meaning same type and value, not just same value.
You have two options. Replace === with ==, or, convert the value before the loop and continue using strict equal. It will be much faster to convert the value before the loop so that you're not converting it over and over with each iteration.
var numberPrimeSix = parseInt(document.getElementById("primeSixInput").value, 10);
more reading: Which equals operator (== vs ===) should be used in JavaScript comparisons?

Categories