-2

In following code of javascript second parameter kept undefined, why is so?

(function(a,b){
   ...
})(window)

What is the technique behind this? Any reference to know about this technique?

blue ghhgdtt
  • 907
  • 4
  • 11
  • 16
  • ...it's undefined because no value is passed to it. What did you expect it to be? – JJJ Mar 01 '13 at 09:07
  • 1
    because it would remain truly undefined – Sudhir Bastakoti Mar 01 '13 at 09:07
  • see this to get more about it:: http://stackoverflow.com/questions/2716069/how-does-this-javascript-jquery-syntax-work-function-window-undefined – Sudhir Bastakoti Mar 01 '13 at 09:09
  • Based on the comments in the other question, the real question seems to be "Why would anyone write such code?" [This post](http://stackoverflow.com/a/15153248/502381) answers that question. – JJJ Mar 01 '13 at 09:11

2 Answers2

1

You've asked this question about an hour ago. What did you expect? you're giving first parameter, after that javascript tries to find the others. if there are no more parameters given to function, all the others (b in your case) will be set to undefined. Javascript is not like C++ or java. There are no compile time errors because javascript is not compiling. So it tries to resolve problems itself. In this case if you pass less count of parameters it sets the others to undefined and works.

shift66
  • 11,760
  • 13
  • 50
  • 83
  • I didn't understand till now, why second parameter is undefined. Why to keep second parameter undefined? Can't we neglect second arguments `b`? – blue ghhgdtt Mar 01 '13 at 09:11
  • and how the function will work? say there is a line `b = 5;` what should javascript do if there is no `b`? it will throw an exception and your code won't work. The function is defined with 2 parameters and it expects 2 parameters always! – shift66 Mar 01 '13 at 09:13
  • if you call it with one, javascript adds the second for you with the value of undefined (I think the most logical value for this case). otherwise your function would not understand how to work with 1 parameter because it's defined for 2. – shift66 Mar 01 '13 at 09:15
0

Here you require 2 parameters in the anonymous function, but you are only providing single parameter (window). Thus the second parameter is always undefined.

nefarianblack
  • 802
  • 8
  • 16