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)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay