Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda function syntax in JavaScript without curly braces

I just found out that the following (awesome) syntax is accepted by Firefox

f = function(x) x+1;
f(17) //gives 18

Does anyone know what the hell is going on here? Is this in any standard? Do other browsers also accept it? (I tested IE 8 and it gave me syntax error)

like image 593
hugomg Avatar asked May 07 '11 05:05

hugomg


People also ask

Does JavaScript need curly braces?

Curly braces { } are special syntax in JSX. It is used to evaluate a JavaScript expression during compilation. A JavaScript expression can be a variable, function, an object, or any code that resolves into a value.

When an arrow function's body is left without curly braces What changes in its functionality?

Without curly braces {} . With this syntax, the arrow function has an implicit return. For example, the below arrow function returns 42, even though there's no return .

Can we use if statement without curly braces?

Yes it is not necessary to use curly braces after conditions and loops (functions always need them) IF and only if there is just one statement following. In this case it automatically uses the next statement.

Which loops require curly braces?

In a do-while loop, the do keyword is followed by curly braces { } containing the code statements.


2 Answers

This isn't part of a standard. The documentation is at https://developer.mozilla.org/en/New_in_JavaScript_1.8#Expression_closures_%28Merge_into_own_page.2fsection%29

There's discussion about adding some syntax along these lines or even shorter to the standard. See http://wiki.ecmascript.org/doku.php?id=strawman:shorter_function_syntax

like image 115
Boris Zbarsky Avatar answered Oct 03 '22 22:10

Boris Zbarsky


The braces are being omitted, just as you can for other control structures that take a block (if,for). It's part of standard syntax for those, perhaps not for functions. One could check the spec I guess.

The convention is that if braces are omitted, the block is the following single statement (only one statement).

For example

if(x) g=1;

is equivalent to

if(x){ g=1; }

However, note that

if(x) g=1; f=2;

is NOT equivalent to

if(x){ g=1; f=2; }

it is actually

if(x){ g=1; } f=2;

I avoid the braceless construct, personally, since it can lead to maintainability problems when the code is modified by people who don't know how this works.

like image 22
Cole Avatar answered Oct 03 '22 23:10

Cole