DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

Ngan Kim Khong
Ngan Kim Khong

Posted on

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)

๐ŸŒš Friends don't let friends browse without dark mode.

Good news! You can update to dark mode in your DEV settings.