r/learnjavascript • u/Ob101010 • Sep 01 '15
Presented this piece of code to a room of devs recently. Surprised by how many didnt know an aspect or two of it.
Without googling anything, describe what this is doing :
!function(m){
return m;
}(this.k)()();
function k() {
return p;
}
function p() {
console.log('haha');
}1
u/ForScale Sep 01 '15
I'm not a professional nor an expert. I'll kind of take a guess...
So, I don't know wht the ! is doing... Saying "not a function?" Please explain! Skipping over that, the anonymous function is passed the result of function k, which is the result of function p, which is 'haha' logged to the console. So, ultimately, 'haha' is logged to the console.
How'd I do?
2
u/Ob101010 Sep 01 '15
spoiler alert!
The ! turns the anon func from a declaration into an expression.
function foo() {...} //declaration !function foo() {...} //expressionExpressions are evaluated, meaning foo gets ran.
Skipping over that, the anonymous function is passed the result of function k
Not the result. Its passed the actual function.
this.k gets passed into the anon as m, and m is returned, and the expression simplifies to
m()()m() is ran. Since m is k, and k() returns p, the expression is again simplified to
p()at which point p() is called and it logs 'haha'.
1
u/ForScale Sep 01 '15
Thanks!!
Expressions are evaluated, meaning foo gets ran.
You mean without having to call it with
foo()?1
u/Ob101010 Sep 01 '15
1
u/ForScale Sep 01 '15
Crazy! I would have simply done
(foo(){})();But I guess using the!means one less character being typed...Thanks again!!
2
u/Ob101010 Sep 01 '15
Yeah it would have got me too 6 months ago. Found it being used in a few libraries though. One less character typed is (I think) the ONLY upside, but when you host it on a CDN that gets hit a million times a day... it adds up.
1
1
u/yooossshhii Sep 11 '15
You should continue to write it like you did. That is standard for an IIFE. Using ! just makes it harder to read. If you really want to be cryptic, you could use the bitwise operator ~ but most people won't know what's going on.
1
3
Sep 01 '15
This code won't work in strict mode. Or in node. Just a heads up for everyone who are trying it.
3
1
u/JudeOutlaw Sep 02 '15
So it returns a function, which is activated, which itself turns a function, which is activated, which prints "haha?"
Am I missing something?
9
u/[deleted] Sep 02 '15
this is fucking stupid