3 ms·
Ask HN: JS, what is this called and how does it work?
(function(test){console.log(test)})(1)
I don't think this really exists in other languages outside of JS. Where you can send in a parameter this way. I understand that the test variable becomes what ever you pass in the tail end but how does this work? What is this called so I can better ask other JS developers?
- uptownhr 11y agoSo after looking at this longer, it makes a lot more sense. Basically, things are evaluated left to right. The first (function(){}) evaluates the function(){} and returns the function. Then the function is called with the second (1), and passing that in as a param.
- Stoo 11y agoThat's it. This is often called the module pattern. It's often used to avoid polluting the global scope with variables, e.g. (function() { var x = 1; console.log(x); })(); console.log(x); Would output: 1 undefined
- ayers 11y agoWhat you have is a self executing anonymous function. Now you know the name you will be able to find out all the information you need. For example: http://esbueno.noahstokes.com/post/77292606977/self-executing-anonymous-functions-or-how-to-write http://esbueno.noahstokes.com/post/77292606977/self-executin...
- uptownhr 11y agothank you!
- cabirum 11y agoImmediately Invoked Function Expressions (IIFE). http://benalman.com/news/2010/11/immediately-invoked-function-expression/ http://benalman.com/news/2010/11/immediately-invoked-functio... Not unique to js, e.g. upcoming php v7 will support these.
- echeese 11y agoThis is the same as: var func = (function(test){console.log(test)}); func(1); What's going on is you're creating an anonymous function, and then calling it.