The Student Room Group


Hi Guys,

I am quite new to JavaScript and I am watching some youtube videos to learn web automation with JavaScript.

I wanted to ask, why do we need (); at the end of the file in JavaScript? I realised that the code does not run if (); is not placed at the end of the file.

e.g. below:

const puppeteer = require('puppeteer');

(async () => {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
await page.goto('');
await page.screenshot({path: 'example.png'});

await browser.close();
})(); <--- Why do we need (); at the end?

Can you please help me answer this question?
The (); at the end of the JavaScript file you provided is actually invoking the immediately-invoked function expression (IIFE) that wraps the entire code block.

An IIFE is a function that is executed as soon as it's defined, and it's commonly used to create a private scope for your code, preventing it from interfering with other code that may be running on the same page. Wrapping your code in an IIFE also helps to ensure that any variables or functions defined within it don't pollute the global namespace.

In your example code, the IIFE is defined using the syntax (function() { /* code goes here */ })();. The final () at the end of the IIFE is what actually invokes it and causes the code within to be executed.

So to answer your question, the (); at the end of your code is necessary to actually invoke the IIFE and execute your code. If you were to remove it, your code would not be executed, since the IIFE would not be invoked.

Quick Reply