3

I was reverse engineering a jQuery plugin and found a peculiar function definition.

function myFunction(value, undefined){
  ...
}

Of course, this works but similar declarations like

function myFunction(value, null) {
  ...
}

OR

function myFunction(value, 5) {
  ...
}

do not work.

The initial declaration where the parameter is undefined works like a default parameter value (refer the snippet below). Can someone point to this phenomenon in ECMA6 specification. I have clue on what to even search for.

function strange (value, undefined) {
  document.getElementById("output").innerHTML += "<br/>" + "- " + arguments[1];
}

strange(5,6);
strange(5);
<div id="output"></div>
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Lordbalmon
  • 1,634
  • 1
  • 14
  • 31

1 Answers1

8

Oddly, undefined is not a reserved keyword and its global value can be overridden (or could be in the past, in some runtime environments). Thus that trick provides a way to wrap code expecting undefined to really be undefined: when that function is called, if only one parameter is passed the second argument, called "undefined", will have the authentic undefined value inside the function.

Why would undefined be overwritten? Who knows. People who write code for pages that also have to host 3rd-party code (generally adverts and things like that) become paranoid and defensive after a while.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 2
    summarized nicer than I could do in 2 minutes :D – Mulan Feb 01 '19 at 21:43
  • Couldn't it be a bad naming? – Cid Feb 01 '19 at 21:44
  • You mean somebody made the weird decision to call their global variable "undefined"? Sure, that could be it. Again, no JavaScript programmer with any experience (and who's not crazy) would do this, but it's easy enough to build-in a defense anyway. – Pointy Feb 01 '19 at 21:46