What is the JavaScript void(0)?

You've probably seen the JavaScript void(0) before. But, what is it? And, what does it do?

First, let's take a look at the history of void(0). JavaScript was created in 1995 by Netscape. And, in the early days of JavaScript, void(0) was used to indicate that a function didn't return a value.

Here's an example of how void(0) was used in the early days of JavaScript:

function square(x) {
    console.log(x * x);
    return;
}

square(3);

The code above would log 9 to the console. Because the function doesn't return a value, we use void(0) to indicate that.

However, in later versions of JavaScript, void(0) stopped being used to indicate that a function doesn't return a value. Instead, void(0) is now used to indicate that a function doesn't throw an error.

Here's an example of how void(0) is used in modern JavaScript:

function square(x) {
	console.log(x * x);
}

square(3);

The code above will log 9 to the console, just like the example from the early days of JavaScript.

Now that we know what void(0) is, let's take a look at some code samples.

Here's an example of how to use void(0) in a function:

function square(x) {
    if (x > 0) {
        console.log(x * x);
    }
}

square(3);

The code above will log 9 to the console. If x is greater than 0, then the function will log x * x. If x is not greater than 0, then the function will log void(0) to the console.

Here's another example of how to use void(0) in a function:

function square(x) {
    if (x > 0) {
    throw new Error("x must be greater than 0");
    }
}

square(3);

The code above will throw an error. If x is greater than 0, then the function will log x * x. If x is not greater than 0, then the function will throw a new Error.

💡
Need a writer? Want to work with me? I have a subscription copywriting service available at Zipply.io. Subscribe to a set number of words and split it into as many copy assets as you need. Scale your startup, small business, or MVP. Upgrade, downgrade and pause at any time. Start your subscription here.