Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unusual javascript syntax

Tags:

javascript

could someone please explain to me what is going on in the second line here ? :

var foo = function(){alert("hello?")}; (0,foo)(); 
like image 599
Funky Oordvork Avatar asked Jan 09 '13 10:01

Funky Oordvork


People also ask

What does () => mean in Javascript?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

What is clean code Javascript?

First of all, what does clean coding mean? Clean coding means that in the first place you write code for your later self and for your co-workers and not for the machine. Your code must be easily understandable for humans.

What are algorithms in Javascript?

Applied to code, an algorithm is just a function that transforms a certain input data structure into a certain output data structure. The logic inside decides the transformation.

What are the three types of statements in Javascript?

The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins. The test statement which will test if the given condition is true or not.


2 Answers

The infamous comma expression a,b evaluates both arguments and returns the value of the right-hand expression.

Hence in this case it's exactly the same as foo();.

Here's a better example that will help you understand what's going on:

function foo() {     print("foo called");     return 123; } function bar() {     print("bar called");     return 456; } var result = (foo(), bar()); print("result:", result); 

Output:

foo called bar called result: 456 

Also the comma expression may be confused with the comma delimiting function arguments. Not the same! Notice the difference:

print("result:", foo(), bar() ); // 3 arguments, no comma operator print("result:", (foo(), bar()) ); // 2 arguments, comma operator 
like image 176
Kos Avatar answered Oct 02 '22 11:10

Kos


It's evaluating both expressions in the first parenthesis and executing the second one (in this case - a function).

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Comma_Operator

like image 21
Dziad Borowy Avatar answered Oct 02 '22 11:10

Dziad Borowy