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.)
Related
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
This question already has answers here:
What's the reason to use === instead of == with typeof in Javascript?
(5 answers)
Closed 6 years ago.
In Javascript === compares type as well as value, where as == just compares value. In the following example, is there any advantage of using === over ==?
function roll( sides ){
if ( typeof sides === "undefined" ) {
sides = 6;
}
var result = Math.random() ;
result = result * sides ;
result = Math.floor(result) ;
return result ;
};
According to the typeof documentation it will only ever return a string. This leads me to believe utilizing === doesn't offer any advantages in this situation.
I imagine whoever wrote the tutorial I am following used === out of habit?
In some cases, === might give you a tiny (usually negligible) performance benefit over ==.
It's also safer to use ===, precisely because it also tests if type is identical.
For example, consider this :
TRUE === 1 and FALSE === 0 both are FALSE
TRUE == 1 and FALSE == 0 both are TRUE.
In most cases, you want the former and not the latter behavior.
This question already has answers here:
What does the || operator do?
(4 answers)
What does "options = options || {}" mean in Javascript? [duplicate]
(5 answers)
Closed 8 years ago.
I have a piece of JavaScript code that shows:
function(next, feather) {
var l = Number(171) + (next || 0);
var m = Math.max(1, l - 9);
return {
lc: 300 * (l + 1) * m + (5 * feather || 0)
}
}
Now I've simplified it a little bit. But can anyone explain what the "|| 0" does? As far as I can tell it does nothing.
(Notice I replaced a function with Number(171), as that function effectively returns a number, feather is also supposed to be a number, 0 most of the time, 1 sometimes).
If next is falsy, 0 will be used in its place. JavaScript has no default value operator, so users have leveraged this approach, even though the language's creator has called it an abusage.
Well if you know next and feather are numbers, then yes, it has no function. However, if you were to pass in a value like undefined, which is effectively what will happen if you call the function without specifying any parameters, you'll see some difference:
var next = undefined;
console.log(171 + next); // NaN
console.log(171 + (next || 0)); // 171
Of course, this isn't a foolproof method. Passing in null has no effect on the computation, and passing a non-empty string (e.g. "1"), will result in something very different.
variable || 0 looks up the variable, and if it is undefined, null, or empty (i.e. zero), it will use the number 0 instead. This actually makes sense because if it was anything other than zero itself, it would return NaN.
If that didn't make any sense, this should:
undefined * 1 == NaN;
(undefined || 0) * 1 == 0;
If the next is falsy (false-like value) zero is used instead.
E.g.
next || 0
equals something like
if(!next) { return 0 } else { return next; }
It forces false-like values to be an actual zero number.
If the context before the logical or || is falsy (this includes nulls and undefineds), then it will take the value after it. So in your case, if next or feather is not defined or 0, then the value of 0 will be used in those calculations within the parenthesis, essentially the code will read as the following if both are 0 or undefined:
function(next, feather) {
var l = Number(171) + 0;
var m = Math.max(1, l - 9);
return {
lc: 300 * (l + 1) * m + 0
}
}
Using the OR operator || in this scenario is basically short hand for checking weather or not next was included. If it were coming from some sort of number calculation, perhaps it was possible that next was NaN at times (which is always falsy) and so this was the workaround to make it 0.
var l = Number(171) + (next || 0);
A more readable approach would be to test for that case at the inset of the function
if( isNaN(next) )next = 0;
Or to also include other tests as well
if( isNaN(next) || next === null || typeof(next) === "undefined" )next = 0;
The && and || operators in JavaScript will shortcut evaluation. The way it's set up in the example you gave, if 'next' evaluates to a boolean TRUE then that will be added to 'l', otherwise '0' will be added.
Other than using a switch statement (or writing if(x === 2 || x === 3 || x === 4) etc), is there any way to implement multiple "or" (||) operators?
E.g.:
if(x === 2 || 3)
alert("Yes");
This alerts for every value of x
The closest you can probably come is to do something like this:
if ([2,3].indexOf(x) > -1){
}
DOCS
Of course that will require a shim for IE 8 and below, if that's an issue for you.
Standard approach for large number of choices is to use dictionary/hash set/hash table depending on language.
For JavaScript both array and object would work:
var isPresent = [];
isPresent[2] = true;
isPresent[43] = true;
if (isPresent[x])...
For small number of items Adam Rackis' answer with linear search is much more readable
[2,3].indexOf(x)
This question already has answers here:
Is there a JavaScript strcmp()?
(7 answers)
Closed 9 years ago.
The community reviewed whether to reopen this question last month and left it closed:
Original close reason(s) were not resolved
I am trying to optimize a function which does binary search of strings in JavaScript.
Binary search requires you to know whether the key is == the pivot or < the pivot.
But this requires two string comparisons in JavaScript, unlike in C like languages which have the strcmp() function that returns three values (-1, 0, +1) for (less than, equal, greater than).
Is there such a native function in JavaScript, that can return a ternary value so that just one comparison is required in each iteration of the binary search?
You can use the localeCompare() method.
string_a.localeCompare(string_b);
/* Expected Returns:
0: exact match
-1: string_a < string_b
1: string_a > string_b
*/
Further Reading:
MDN: String.prototype.localeCompare
Stack Overflow - Is there a JavaScript strcmp()?
Tutorials Point: JavaScript String - localeCompare() Method
Well in JavaScript you can check two strings for values same as integers so yo can do this:
"A" < "B"
"A" == "B"
"A" > "B"
And therefore you can make your own function that checks strings the same way as the strcmp().
So this would be the function that does the same:
function strcmp(a, b)
{
return (a<b?-1:(a>b?1:0));
}
You can use the comparison operators to compare strings. A strcmp function could be defined like this:
function strcmp(a, b) {
if (a.toString() < b.toString()) return -1;
if (a.toString() > b.toString()) return 1;
return 0;
}
Edit Here’s a string comparison function that takes at most min { length(a), length(b) } comparisons to tell how two strings relate to each other:
function strcmp(a, b) {
a = a.toString(), b = b.toString();
for (var i=0,n=Math.max(a.length, b.length); i<n && a.charAt(i) === b.charAt(i); ++i);
if (i === n) return 0;
return a.charAt(i) > b.charAt(i) ? -1 : 1;
}