Checking remainder in Javascript - javascript

I am super new at Javascript. I'm trying to write a script that logs numbers in order, and then at the end tells me if the final number is even or odd.
What I have is:
var i = 0;
do {
i++;
console.log(i)
}
while (i <= 9);
if(i % 2 = 1) {
console.log("odd")
}
else {
console.log("even")
}
Before I added the if/else, it worked. Now I keep getting the error: invalid left-hand side in assignment
What am I doing wrong? And to really display my ignorance, what is the left-hand side in the assignment?
Thanks!

Firstly, you will want to use the double equal (==) or the triple equal (===), when checking your remainder, since the single equal (=) is used to assign values to variables.
Difference between == and ===:
=== is more strict than == since === checks the value AND type whereas the == only checks the values.
Example:
if(1 == '1') // true
if(1 === '1') //false : their types are different.
Secondly, you will likely want to wrap your if statement inside of your do-while loop to get an output of even or odd after logging each number.
Here is the final result:
var i = 0;
do {
i++;
console.log(i);
if(i % 2 === 1) {
console.log("odd");
} else {
console.log("even");
}
} while (i <= 9);

When it says invalid left-hand side, it means that you are trying to assign a value to something on the left side. You have used -
if(i % 2 = 1)
However, = is an assignment operator, which basically assigns a value to a variable on the left. What you need is == which is a comparison operator since you are trying to compare two values.
This should be your code -
if(i % 2 == 1)

Instead of = it should be == in the if condition.

you need to change if condition from if(i % 2 = 1)
to
if(i % 2 ==1)

if(i % 2 == 1) {
console.log("odd")
}else {
console.log("even")
}
Because == is for equality comparison while = is for assigning of value.

So the problem in you code is , you are using an assignment operator "=" in your if condition, instead use "==" (comparision operator).
You can find more information on comparision operators in Javascript here :
https://www.w3schools.com/js/js_comparisons.asp

Related

Compering undefined, null and values

I want to run this in my code: if(a > b){ do something} where a and b can be sometimes undefined or null and sometimes comparable(e.g. both a number).
Is it ok in javascript to do this?
I only want the if to be true if they are comparable.
In general, you should never attempt to compare things of different types without defining your rules for how you want them to be compared. While there's actually a very strict set of rules defined in JS standard for comparing values of different types, you're opening the big can of worms if you try to design your code around this set.
What you might consider doing instead is separating type casting operation from comparison operation. For example:
function firstIsGreater(numA, numB) {
if (typeof numA !== 'number') return false;
if (typeof numB !== 'number') return false;
return numA > numB;
}
Strictly speaking, those checks are not required here. For example, when you compare with undefined, that gets cast to NaN, and any comparison involving NaN results in false.
The problem is that usually mixture of types is a sign of much bigger problems in your outlying code - and instead of returning false you might consider throwing errors, or at least triggering some warnings.
In general you should validate the values and cast them to the types you're completely aware of at the very moment those values arrive into your system from some external components - server-side calls, user input etc.
if(typeof a == 'number' && typeof b == 'number' && a > b){ do something}
This will only run "do something" if a and b are both numbers and a is greater than b.
Any undefined value in combination with a comparison of less than <, greater than > or less than or equal or graater than or equal yields false.
Any null value is converted to zero in an number like environment.
Maybe this table helps: Loose equality using ==
if (undefined < 3) console.log('undefined < 3');
if (undefined > 3) console.log('undefined > 3');
if (undefined <= 3) console.log('undefined <= 3');
if (undefined >= 3) console.log('undefined >= 3');
if (null < 3) console.log('null < 3');
if (null > 3) console.log('null > 3');
if (null <= 3) console.log('null <= 3');
if (null >= 3) console.log('null >= 3');

Dynamically constructed if statement in one string variable

I am blacking out over issue and I am convinced I am thinking too complex about this, but summarized, my issue is about this:
// imagine this variable is dynamically filled by a loop with conditions inside
var condition = varA + " == " + varB + " && " + varC + " == " + varD;
if (condition) {
// something
}
So it doesn't check whether varA equals varB and varC equals varD as what I intended, but instead it just sees it as a string and that appears to be always true anyway. I don't want, I want to see it actually checking whether varA equals varB etc.
Is there a way to parse this statement into something that actually can be a 'legit' if condition?
Thanks!
I think I understand what your trying to do. You are trying to look at a number of comparisons and determine, in the end, if all comparisons were truly true.
In this case you can actually just keep building your condition out as in the following:
var a = 1, b = 1, c = 3, d = 3, e = 5, f = 6;
var condition = a === b; // condition is true
condition = condition && c === d; // condition is still true
condition = condition && e === f; // condition is now and forever false
why not just do
if(varA == varB && varC ==varD){
//do something
}
edit
maybe try using safe-eval. its a third party package but APPEARS to be an improvement on eval.
The issue with your condition variable is that it's not checking for equality between your variables. The whole condition variable is being read as a string because it sees the == and && as strings and ends up concatenating them together.
I suggest writing your if statement like so:
if (varA === varB && varB === varC && varC === varD) {
// do something
}
That way, you're checking if varA is equal to varB and varB is equal to varC, etc. Using the triple equals also ensures that the variables are of the type value type (i.e. string, boolean, number). Hope this helps.

Write shorthand for val++ and if()

I do a val++ at the end of each txt file is loaded and then run doSome() when val is equal to num.
$('#holder').load('item[i].txt',function(){
val++;
if(val==num){
doSome();
}
}
How to I write this shorthand?
val++;
if(val==num){
doSome();
}
val++ already is (basically) shorthand for val = val + 1;
You can use && to replace the if:
val == num && doSome();
(MDN: && Shortcut operation)
Resulting in:
$('#holder').load('item[i].txt',function(){
val++;
val == num && doSome();
}
Personally, I prefer having the increment and the condition on separate lines, for readability purposes.
Another suggestion: The brackets for an if statement ({}) are optional, if the if statement is only used for 1 line of code:
if(condition) {
doSomething();
}
Can be shortened a bit like:
if(condition)
doSomething();
Use pre-increment operator
if (++val === num) {
//code here
}
This will first increment val by one and then compare the updated value with num variable.
Pre-increment could be used where value of variable is incremented first and then returned whereas in Post-increment, value of variable is returned first and then incremented.
if (++val == num) {
doSome();
}
So... maybe this? :) ++val ^ num || doSome();
^ (XOR) is a bitwise operator. It returns 0 if two operands are the same number. For example 2^2 = 0.
So you can firstly pre-increment val this way: ++val. Then you can do XOR operation on num, and when they are equal - it will return 0, which is considered as false in logic statements in js. And then, when left side of || operator is false, it will execute right part of this statement - doSome().
Btw, one interesting thing: for example, if disable code optimisation, in C++ it is much efficient to assign 0 to variable in this way: a ^= a rather than a = 0.

Why is the javascript if else statement only register reading last else statement?

The javascript if else statement I am using in LiveCycle is only reading the last else statement and won’t read or recognize the statements that come before it. If you can see what I am missing please help. Here is the code:
if (annualUsage.rawValue < 1,000,000)
{
this.rawValue = annualUsage.rawValue * 0.1;
}
else if (annualUsage.rawValue >= 1,000,000 && annualUsage.rawValue < 10,000,000)
{
this.rawValue = annualUsage.rawValue * 0.2;
}
else (annualUsage.rawValue >= 10,000,000)
{
this.rawValue = annualUsage.rawValue * 0.05;
}
Take the commas out of your numbers? So like
if (annualUsage.rawValue < 1000000)
etc...
Also the last else statement doesn't get a condition so you can
either remove the condition
else{
or turn it into an else if statement
else if(annualUsage.rawValue >= 10000000){
You're unintentionally misusing the the comma operator.
a, b will execute both a and b and evaluate to b.
Therefore, the value you're actually passing to the ifs is 000, which is falsy.
In addition, the parenthesized expression after the else becomes a statement (through ASI) which is the body of the else clause.
The { after it starts a normal code block which always executes.
Remove the comma from the numbers :
if (annualUsage.rawValue < 1000000)
Otherwise it evaluates to an expression with comma operator.
Even the last else needs to be corrected.
else if(annualUsage.rawValue >= 10000000)

Shorten JS if or statement [duplicate]

This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
Is there anyway to shorten something like this in Javascript: if (x == 1 || x == 2 || x == 3 || x == 4) to something like if (x == (1 || 2 || 3 || 4)) ?
You can use use Array.indexOf
[1,2,3,4].indexOf(x) !== -1
You can also use objects as some kind of hash map:
//Note: Keys will be coerced to strings so
// don't use this method if you are looking for an object or if you need
// to distinguish the number 1 from the string "1"
my_values = {1:true, 2:true, 3:true, 'foo':true}
my_values.hasOwnProperty('foo')
By the way, in most cases you should usi the "===" strict equality operator instead of the == operator. Comparison using "==" may do lots of complicated type coercion and you can get surprising results sometimes.
If your cases are not that simple to be expressed by this:
if (1 <= x && x <= 4)
You could use an array and indexOf:
if ([1,2,3,4].indexOf(x) > -1)
Note that indexOf might need to be re-implemented.
Not without writing a function that takes an array as an input and returns true/false, or some sort of array search. It would be hard to maintain/other devs to read. And it would be significantly slower. So just stick with the semantically correct longer version.
Also a good way to see if anything can be shortened significantly is to run it through the close compiler and see what it comes out with.
How about:
if (x > 0 && x < 5) {
}
You could write a function:
function isAny(x) {
for (var i = 1; i < arguments.length; ++i)
if (arguments[i] === x) return true;
return false;
}
Then you can say:
if (isAny(x, 1, 2, 3, 4)) { /* ... */ }
(Whether to use "===" or "==" would depend on the exact semantics you want.)

Categories

Resources