Skip to content

Instantly share code, notes, and snippets.

@fakefarm
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fakefarm/e689825d0ce851df7ec2 to your computer and use it in GitHub Desktop.
Save fakefarm/e689825d0ce851df7ec2 to your computer and use it in GitHub Desktop.
JS Parens

The moment (function(){})() made sense.

Let's start with a simple concept.

1 + 1
=> 2

Adding parens clarifies order of operations.

1 + 2 * 2
=> 5
(1 + 2) * 2
=> 6

Using parens when it's not necessary is harmless.

(1 + 1)
=> 2

Parens with functions

Javascript is syntax heavy so it can be difficult to know which parts are required vs. optional.

Anonymous functions

What happens when you want to create an free standing anonymous function?

function(){ } 
=> SyntaxError: Unexpected token (

To prevent syntax error, wrap the function with parens

( function(){ } )
=> function (){ }

If you want to define it, then run it, you'll need to wrap the definition in parens to separate definition from execution.

(function(){})()
=> undefined

The function body does nothing. So, here we expect the function to simple return undefined

It's a syntax error if you try to define and invoke the anonymous founction.

function(){}()
=> SyntaxError: Unexpected token (
Using a variable assignment
var a = function(){}
=> function (){}

Calling the variable will return the function itself, which is different than invoking the function.

a
=> function (){}

Add the parens if you want the function to execute.

a()
=> undefined

undefinded is the function body.

Again, wrapping the whole assignment in parens does nothing.

(a = function(){})
=> function (){}

The a = is unecessary if you're calling it immediately But, you will need to wrap the declaration in parens to define it and run it at the same time.

(a = function(){})()
=> undefined

Since we are defining then immediately calling the function assigning to a isn't neccssary.

Which was the moment I realized the following line was productive!

(function(){})()
=> undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment