This question already has answers here:
Why does javascript accept commas in if statements?
(5 answers)
Closed 8 years ago.
I've searched in SO but I didn't find something similar. Maybe I am using wrong search keys.
I was editing a javascript library when I found this if statment
var a = location.hash.replace(/^#/, "");
if (container = $("#content"), a) {
..content
} else {
...other code
}
the first part container = $("#content") is assigning the value of $("#content") to container but I don't understand why there is a comma inside the If. Is it like an AND operator?
Something like if (container = $("#content") && a) ?
What is it evaluating?
The comma operator in JavaScript is pretty similar to the concept in other C-like languages. It's a way of stringing multiple expressions together into one (syntactic) expression. The value of the whole thing is the value of the last expression in the list.
Thus in this case, container = $("#content") is evaluated, and then a is evaluated. The value of the whole thing is the value of a.
A good question is why that code was written that way. There are times when the comma operator is useful, but usually it's just a way to save some typing and make code a little more concise.
It is comma operator.
Basically its doing two things. First there is assignment and then the , just evaluates a and validates against it in the if condition.
Related
This question already has answers here:
java-script arrow function returns (x++,x) [duplicate]
(3 answers)
What does the comma operator do in JavaScript?
(5 answers)
When is the comma operator useful?
(15 answers)
Closed 9 months ago.
I tried looking at MDN on arrow functions, that links to an article ES6 In Depth: Arrow functions and the ECMAScript grammar. I didn't find an example of this style of function body.
See takeStockForBowl in example code below.
Question, what would this style of function definition be called?
Maybe it's a repurposing of a more basic JavaScript syntax and I just don't see it. Apologies if it's obvious.
const takeStockForBowl = bowl => ( // open paren
takeForBowl('protein', bowl), // side effect 1
takeForBowl('grain', bowl), // side effect 2
takeForBowl('veg', bowl), // ...
bowl.supplied = true, // side effect n
bowl // result
) // close paren
First of all, takeStockForBowl is really hard to read.
To understand what's happening here, we need to understand two things:
Arrow functions
Comma operator
Basically what the author has done here is avoided writing the following:
Explicit return statement
Curly braces for the function body
by taking advantage (or abusing) of implicit return in arrow function and the comma operator.
What comma operator does is it evaluates each of its operands from left to right and returns the value of the last operand which in this case is bowl.
More readable version of this function is:
const takeStockForBowl = bowl => {
takeForBowl('protein', bowl);
takeForBowl('grain', bowl);
takeForBowl('veg', bowl);
bowl.supplied = true;
return bowl;
}
This question already has answers here:
What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?
(14 answers)
Closed 4 years ago.
I was doing a question on codesignal and when I couldn't get the answer myself for all tests, revealed the answers and saw this one; while I understand what it's trying to do (make sure positions are not divisible by n, and if it is increment n by one) I'm having trouble understanding the arrow function syntax and, rewriting it myself from their code.
function obst(inputArray) {
for (var n=1;;n+=1) if(inputArray.every(x=>x%n)) return n;}
In Javascript, every function written like this:
function(args) {
// DO SOME STUFF
}
can be written like this:
(args) => {// DO SOME STUFF}
In your case, the method .every() expects a function, and
function(x) {
return x%n;
}
is written as
x => x%n
inputArray.every(x=>x%n)
is the same as
inputArray.every(function (x){
return x%n
}))
( except for the way the 'this' keyword works )
For any doubt about Javascript language, i recommend the You Dont Know Js series
written by Kyle Simpson.
It's a very enlightening book.
Tip: When you write a code, ask question to youself like:
what i'm doing?
assigment means equality?
what are the methods that can i use in string variables?
And something like that.
Stimulate yourself to know what in the actual fudge, you are doing.
Cheers!.
This question already has answers here:
Concise way to compare against multiple values [duplicate]
(8 answers)
Closed 4 years ago.
I want to check if a variable (in this case sampleVariable) is equal to THIS or THAT:
if(sampleVariable == "THIS" || chosenVerb == "THAT")
The above code should work fine, but I was wondering if there was a way to simplify and compact it - for example, something like this (this probably isn't how you do it, just an example):
if(sampleVariable == "THIS" || "THAT")
I'm fairly certain the above doesn't work since it will check for the two statements being true separately.
I found this website, which seems to be what I'm looking for. They say that this code is the best way to go around it:
if (fruit.match(/^(banana|lemon|mango|pineapple)$/)) {
handleYellowFruit();
}
Is this still the way that this is supposed to be done (since the blog post I linked above was published over half a decade ago)? If so, what are these characters in the parentheses: / ^ $ ?
Thanks for the help!
Depending on browser support and ability to polyfill, I'd try array.includes:
if ((["THIS", "THAT"]).includes(sampleVariable)) {
This question already has answers here:
What is "?:" notation in JavaScript?
(5 answers)
Closed 6 years ago.
Can someone interpret this javascript line for me?
mouseWheelEventName = $.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel',
Need to know what "?" does, and what 'DOMMouseScroll' : 'mousewheel', is saying particularly the "," at the end of the line... why isn't it a ";"
Thank you.
This is a ternary operator, used as a shorthand conditional statement:
it's the same as saying:
if ($.browser.mozilla) {
mouseWheelEventName = 'DOMMouseScroll';
} else {
mouseWheelEventName = 'mousewheel';
}
The first piece before the = is declaring a variable (mouseWheelEventName) dependent on the following condition.
The next piece between = the ? is the condition (is $.browser.mozilla true?).
Immediately after the ? is the then portion (if the condition is true, set the variable mouseWheelEventName to the string DOMMouseScroll).
After the : is the else (if the condition is NOT true, set the variable mouseWheelEventName to the string mousewheel).
Further reading:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
As for why there is a comma at the end of it, we'd need to see a more complete code sample including what follows that to say for certain. If I had to guess, I would say the author of the code was chaining variable statements. This answer may shed some light for you: Javascript best practices, why to use comma to chain function/variable declarations? (see chosen answer)
This question already has answers here:
Why Constant first in an if condition [duplicate]
(2 answers)
Checking for null - what order? [duplicate]
(8 answers)
Closed 8 years ago.
I saw many times in open source projects that folks write something like that:
if("" !== foo) {
// ...
}
Why on earth do they do that? I mean you are checking if foo's value is empty string or not. I understand that "" !== foo and foo !== "" means exactly the same. But what's the reason to write tricky and less obvious code?
I'm personally not a fan of this style, either; however, the style stems from this:
if (x = "") { // **oops**, meant to do "==" but ended up assigning to "x"
// ...
}
The "if" statement here will cause an unintended side-effect. There are a number of languages in which side effects and implicit conversions to boolean make it easy to shoot oneself in the foot this way (JavaScript and C++ come to mind). To avoid this, some have the convention of inverting the ordering, since assigning to a constant will produce a more immediate and obvious error. I'm personally not a fan of this, because it makes the code read less like English ("if x equals the empty string" reads more naturally than "if empty string equals x"), and better tooling (linters, source code analyzers, etc.) can catch these just as effectively.