This question already has answers here:
What does the comma operator do in JavaScript?
(5 answers)
Closed 4 years ago.
var a =(3,4,7);
console.log(a); // Output is 7
Can you please explain how we are getting output 7?
It's called comma operator. By wrapping the right hand expression in parentheses we create a group and it is evaluated each of its operands and returns the last value.
From MDN
The comma operator evaluates each of its operands (from left to right)
and returns the value of the last operand.
The comma operator is useful when you want to write a minifier and need to shrink the code.
For instance,
print = () => console.log('add')
add_proc = (a,b) => a + b
function add(a, b){
if(a && b){
print();
return add_proc(a,b)
}
else
{
return 0
}
}
console.log(add(1,2));
could be minified using comma operator as below:
print = () => console.log('add')
add_proc = (a,b) => a + b
add = (a, b)=> a && b ?(print(),add_proc(a, b)):0
console.log(add(1,2));
The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.
Here , Seprates each Digits Ans As it is a Variable So it stores 3 then overlapped by 4 and finally 7
So final output is 7
Related
This question already has answers here:
What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?
(14 answers)
Closed 3 years ago.
I have a function that takes an input (n) and puts it in the parameters of another function. (n) represents in the second equation the number to what (m) is being compared to (in this case 10). I understand how this function is structured, just don't understand what this means:
return m => m > n;
function greaterThan(n) {
return m => m > n;
}
let greaterThan10 = greaterThan(10);
console.log(greaterThan10(9)); //should output false
m => m > n is an arrow function in javascript. almost same as,
function(m){
return m>n
}
Read more here http://2ality.com/2012/04/arrow-functions.html
This is an example of currying. The function greaterThan is returning a new anonymous function. It's probably easier to understand written like this:
function greaterThan(n) {
return function (m) {
return m > n
}
}
Calling greaterThan(10) returns a new function that will compare its argument to 10. In your example you give it the name greaterThan10 so now you can call greaterThan10(9). This is all because the other function returns another function to use.
You can rewrite your example:
function greaterThan(n) {
return function(m) { return m > n }
}
which uses the same function syntax for both of them.
Otherwise I found your explanation to be let much what anyone would write to explain it. m is simply the parameter to the function returned.
This question already has answers here:
Why does `{} + []` return a different result from `a = {} + []` in Javascript?
(2 answers)
Why {} != ( {} ) in JavaScript?
(2 answers)
Closed 4 years ago.
{} + 5 === 5
5 + {} === '5[object Object]'
How is the first expression {} + 5 === 5 calculated?
The second expression 5 + {} === '5[object Object]' is expected result.
===== Edit ====
({}) + 5 === '[object Object]5'
Which might be to say: {} in first expression was ignored as the question comment says.
The {} at the beginning of a line is considered a code block rather than an object literal. Thus {} + 5 is not considered a binary addition between two values and evaluates to +5, unary + operator applied to 5.
When {} is placed inside round brackets it turns into object literal and the entire expression evaluates to '[object Object]5'
More details on this gotcha can be found here
In the following snippet, both expressions are converted to strings, so you get the following results, which is expected:
[object Object]5
5[object Object]
The reason this is happening is because + can't be addition between numbers since {} can't be cast to a number. Instead + is considered string concatenation here and both operands get converted to strings.
console.log({} + 5 === '[object Object]5')
console.log(5 + {} === '5[object Object]')
This question already has answers here:
Question mark and colon in JavaScript
(8 answers)
How do you use the ? : (conditional) operator in JavaScript?
(20 answers)
Closed 9 years ago.
a = (a == b) ? c: b;
I don't understand. All of them {a, b, c} are variables set with certain value by the programmer.
That is called the ternary operator: that is the same as doing:
if(a == b)
a = c;
else
a = b;
If a equals b then a = c otherwise a = b.
This is a short form for an if and an assignment.
q = x ? y : z
q is the variable you assign to
x is a boolean expression which will be true or false.
If it is true y will be assigned to your variable q
else z will be assigned to q.
This is the ternary operator, which is equivalent to:
if (a == b) {
a = c;
} else {
a = b;
}
The main difference is that if/else consists of conditional statements, while the ternary operator is a conditional expression. In other words, the ternary operator works as if the if/else were returning a value. In some other languages, if/else are expressions as well, so the following would be valid, and indeed equivalent to ?: :
a = (if (a == b) { c; } else { b; }) // not valid javascript
Be sure to check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
The Mozilla Developer Network is a fantastic reference for JavaScript.
if a equal to b then assign c to a , otherwise assign b to a
In english -
If a is equal to b, then a = c. otherwise, a = b
The ?: syntax is a ternary operator. Essentially it means that if a is equal to b than a equals c otherwise a equals b
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript syntax: what comma means?
I came across the code while reading this article (do a Ctrl+F search for Andre Breton):
//function returning array of `umbrella` fibonacci numbers
function Colette(umbrella) {
var staircase = 0, galleons = 0, brigantines = 1, armada = [galleons, brigantines], bassoon;
Array.prototype.embrace = [].push;
while(2 + staircase++ < umbrella) {
bassoon = galleons + brigantines;
armada.embrace(brigantines = (galleons = brigantines, bassoon));
}
return armada;
}
What does the x = (y = x, z) construct mean? Or more specifically, what does the y = x, z mean? I'm calling it comma assignment because it looks like assignment and has a comma.
In Python, it meant tuple unpacking (or packing in this case). Is it the same case here?
This is the comma operator.
The comma operator evaluates both of its operands (from left to right)
and returns the value of the second operand.
The resultant value when a,b,c,...,n is evaluated will always be the
value of the rightmost expression, however all expressions in the
chain are still evaluated (from left to right).
So in your case, the assignations would still be evaluated, but the final value would be bassoon.
Result:
galleons = brigantines
brigantines = bassoon
armada.embrace(basson)
More information: Javascript "tuple" notation: what is its point?
var syntax allows multiple assignment, so when you see the following, you're declaring multiple variables using one var statement.
var a, b, c;
Note that this syntax is not the comma operator.
The , can be used as the comma operator. It simply evaluates a series of expressions. So when you see the following syntax, you are seeing a series of expressions being evaluated, and the return value of the last one being returned.
x = (y = x, z)
Within the parens, x is assigned to y, then z is evaluated and returned from the () and assigned to x.
I'd suggest that this syntax is unclear and offers little benefit.
The comma operand evaluates all of its operands and returns the last one. It makes no difference in this case if we had used
x = (y = x, z);
or
y = x;
x = z;
It's there to take away that line of code.
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;
}