How to Write a Self-Executing JavaScript Function

By Birtchum Thompson | March 23, 2020

It is sometimes necessary to write self-executing (or self-invoking) anonymous functions in JavaScript. Variables within these special functions are limited to the code within the function only. This allows functions to be written with variable names that are used in other code blocks without effecting them.

Writing a self-executing function is very straight-forward. They are simply a normal JavaScript function wrapped in parentheses with a pair of parenthesis at the end. The ending parentheses can accept arguments for the self-executing function, but it is not necessary. Possible arguments to pass to the function may be ‘window’ or ‘document’. An example self-executing function is shown below.

Share this Content

Join the Discussion

Also Read

UFW, Ubuntu, and firewall logos on dark grey background
Allow SMB in UFW

Allow SMB traffic in UFW on Ubuntu & Debian.

White Bash Logo
Check Exit Status of Bash Command in a Script

Check a Bash command exit status in a script.

Python logo and red trash can
Delete Files Older than X Days in Python

Create a Python script to delete files older than x days.

Blue KDE Logo
Configure Screen Locking Shortcut in KDE

Learn to configure the screen locking shortcut in KDE.