What is this "()" for?

What is this "()" for?
0
#1

Have been through documentation but still cannot work out what the parantheses at the end of this statement are for. Can anyone help or point me to an article? Thanks.

Default Parameters for Your Functions
#2

Seems that the function (anonymous) is being declared using IIFE so as to keep scope constant within context. Those parenthesis are what allow the function to be seen once the line of code is executed through.

#3

The parenthesis is this context is meant for anonymous function call. If you intend to call a function that you don’t intend to save to memory, You can use anonymous function calls to declare the function - by enclosing the function declaration in a parenthesis - and cause it to be executed immediately - by following it with a parenthesis.
Usually you would declare a function as:
var fxn = function(){ //do something... }
then execute it as:
fxn()

But desiring not to save this function to memory- and probably i may not reuse it- I will call it like this:
( function(){ //do something } )();

the last ‘()’ will cause my function to execute immediately. so that’s in-short declaring and executing together.

2 Likes
#4

I think I get it. Testing the code out on plunkr.co (full code from the exercise is below) I can see that without that final () it shows only the text of the function in the console, and with the () it executes it. So without the () it retrieves what is stored in memory and with it, it executes what stored in memory. Thanks for your reply!

#5

I can see that without that final () it shows only the text of the function in the console, and with the () it executes it. So without the () it retrieves what is stored in memory and with it, it executes what stored in memory

I think you’re might be overcomplicating things in your head from the way you’re describing this:

This is how you declare a function:

function example() {
  // Some code
}

This is just the name of the function, it doesn’t execute it:

example

And this is how you execute the function:

example()

Note the ().

1 Like