DEV Community

loading...

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

Ngan Kim Khong
Hi! I'm currently a software engineer intern! I am looking to post some blogs about what I'm learning :)
・1 min read

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

Discussion (0)