2 ms·
void implies that the return type should is undefined behavior and should not be relied upon, so that something like this const x = foo(); is incorrect wh
by zarzavat 5y ago
void implies that the return type should is undefined behavior and should not be relied upon, so that something like this
const x = foo();
is incorrect when foo() returns void. 99% of the time x will be undefined (the value) but there are cases where it would not be. For example
arr.forEach(x => x.sort())
sort returns a value as well as having a side effect. But forEach expects a void callback. This code is perfectly fine in JavaScript because forEach does not read the return value of the callback.
- amitport 5y agoI agree. I don't see where what you wrote contradicts what I said.
- IggleSniggle 5y agoPerhaps they were not trying to contradict you?
- true_religion 5y agoI agree. You should type something as null if you need to force callers to deal with the null value and can't do that with an exception. Type it as void if the value isn't really important to the caller, or you'll throw exceptions in an exceptional case. Common wisdom is to always have user-defined functions return void, but sometimes I think it's okay to use void if you're replacing a built in JavaScript functionality so the outer code was relying on that semantic. For example, replacing a simple usage of findIndex (that returned undefined) with something more complex that does API calls.