Home > JavaScript > JavaScript 1.8 Expression Closures

JavaScript 1.8 Expression Closures

The new expression closures introduced in JavaScript 1.8 based on Lambda notation looks bit weird. In JavaScript 1.8 the developer will be able to write single line functions based on this notation differently compared to the method that we’ve been following for years. Lets jump into an example:

function foo() alert("hello world");

The first thing that the developer will notice is the absence of the curly bracket that we’ve been using during most of our programming. I don’t know what is going to achieve by excluding the curly brackets at this point. Even though the developer can avoid curly brackets while using any looping, conditional constructs, etc the wise developer never avoids those. I think {} used to group things neatly.

Lets see another example

function foo() true;

This looks more confusing than the first one. This is a function whose name is foo that returns true to the caller :(. In other words these single line creature will return whatever comes in the single line function body.

function foo() "Hello world";
var strMsg = foo();
alert(strMsg); //Will output Hello World

Another simple function that finds the largest of 3 provided numbers. I haven’t done any input validation here.

function foo(a, b, c) (a > b ? (a > c? a : c):(b > c? b:c));
alert(foo(8, 4, 1));

Though this is not a compulsory rule to write the single line functions using this new notation. Developers can use the old method

Advertisements
Categories: JavaScript Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: