DEV Community

Ngan Kim Khong
Ngan Kim Khong

Posted on

2 1

Javascript function scoping basic: The expression and the invoke...

The image above shows the two ways of writing a function and invoke it immediately.
You will wrap a parentheses outside of the function, and then another parentheses after it.

for (var i = 0; i< 5; i++){
  function anyName(){
    var j = i;
    console.log(j)
  }
  anyName();
}
Enter fullscreen mode Exit fullscreen mode
for (var i = 0; i< 5; i++){
  (function anyName(){
    var j = i;
    console.log(j);
  })()
}
Enter fullscreen mode Exit fullscreen mode

Both of these will immediately print

0 1 2 3 4

My eyes weren't used to the syntax, I got confused every time I saw it, hence I write it down as a blog to remember and understand Javascript better the next time I see this. <3

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more