Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Tip] Put + at the beginning of function #18

Closed
phuocng opened this issue Feb 22, 2021 · 1 comment
Closed

[Tip] Put + at the beginning of function #18

phuocng opened this issue Feb 22, 2021 · 1 comment

Comments

@phuocng
Copy link
Owner

phuocng commented Feb 22, 2021

Usually, we can invoke a function by using the form of Immediately Invoked Function Expression (IIFE).

(function(a, b) {
    return a + b;
})(4, 2);

// 6

Do you know that we get the same result if we omit the parentheses and put + at the beginning as follow:

+function(a, b) {
    return a + b;
}(4, 2)

// 6

It works because putting + at the beginning of function declaration will turn it to an expression, and passing the parameters with () at the end will invoke the expression.
It is rare to see that code in development, but it is used in the minifications to save the file size.
In addition to +, you can use other operators such as -, !, ~ and void in the similar way to invoke a function:

-function() { ... }();
!function() { ... }();
~function() { ... }();
void function() { ... }();

Note that the return value could be different from the original function, for example:

!function() { return false; }();     // true
@phuocng
Copy link
Owner Author

phuocng commented Feb 23, 2021

@phuocng phuocng closed this as completed Feb 23, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant