Question about code Syntax why does it have a empt ()

Question about code Syntax why does it have a empt ()
0

#1

So I am working on my wikipedia project and had an idea where I want the text to draw itself on the page and found this code on the internet to achieve this. So i have been trying to understand exactly what it does line by line but am stuck on why it surrounds the function call with a ( and calls an empty () after it. If anyone could explain the reasoning behind this that would be awesome here is the code… Also I put comments on the sections that confuse me.

var ctx = document.querySelector("canvas").getContext("2d"),
dashLen = 220, dashOffset = dashLen, speed = 5,
txt = "STROKE-ON CANVAS", x = 30, i = 0;

ctx.font = "50px Comic Sans MS, cursive, TSCu_Comic, sans-serif"; 
ctx.lineWidth = 5; ctx.lineJoin = "round"; ctx.globalAlpha = 2/3;
ctx.strokeStyle = ctx.fillStyle = "#1f2f90";

(function loop() {   // WHY DOES THIS HAVE A ( BEFORE FUNCTION//
  ctx.clearRect(x, 0, 60, 150);
  ctx.setLineDash([dashLen - dashOffset, dashOffset - speed]); // create a long dash mask
  dashOffset -= speed;                                         // reduce dash length
  ctx.strokeText(txt[i], x, 90);                               // stroke letter

  if (dashOffset > 0) requestAnimationFrame(loop);             // animate
  else {
    ctx.fillText(txt[i], x, 90);                               // fill final letter
    dashOffset = dashLen;                                      // prep next char
    x += ctx.measureText(txt[i++]).width + ctx.lineWidth * Math.random();
    ctx.setTransform(1, 0, 0, 1, 0, 3 * Math.random());        // random y-delta
    ctx.rotate(Math.random() * 0.005);                         // random rotation
    if (i < txt.length) requestAnimationFrame(loop);
  }
})(); // WHY IS THERE A EMPTY () HERE?

#2

This is what you call an immediately-invoked function expression, or IIFE. Basically, you’re writing a function, then invoke it immediately.


#3

Ah i see, so this is just a quicker way then stroing a function in a variable and calling it later then, is that right?


#4

You can think of it that way.


#5

thanks again btw, im reading up on this now so I can fully understand it now that I know what to look for!