I’ve been looking for information about immediately invoked functions, and somewhere I stumbled on this notation:
+function(){console.log("Something.")}()
Can someone explain to me what the + sign in front of the function means/does?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It forces the parser to treat the part following the
+as an expression. This is usually used for functions that are invoked immediately, e.g.:Without the
+there, if the parser is in a state where it’s expecting a statement (which can be an expression or several non-expression statements), the wordfunctionlooks like the beginning of a function declaration rather than a function expression and so the()following it (the ones at the end of the line above) would be a syntax error (as would the absense of a name, in that example). With the+, it makes it a function expression, which means the name is optional and which results in a reference to the function, which can be invoked, so the parentheses are valid.+is just one of the options. It can also be-,!,~, or just about any other unary operator. Alternately, you can use parentheses (this is more common, but neither more nor less correct syntactically):