-1

Can anybody explain below code? All I know is it is anonymous function but what is (0) doing?

var output = (function(x) {
 delete x;
 return x;
})(0);
console.log(output);

Why output of above code comes zero. Can anybody explain?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
nirmesh
  • 121
  • 6
  • 4
    It is a [Immediately-Invoked Function Expression](https://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript) to which `0` is passed as first argument. – t.niese Feb 09 '19 at 16:00
  • 2
    You put 0 in, it splits 0 out. That's about it (ignoring the useless `delete`). – trincot Feb 09 '19 at 16:02
  • 2
    is a variable not a property and so it can't be deleted. a property would be `delete x.y` if `x = { y: 5};` – Pavlo Feb 09 '19 at 16:03
  • [MDN: delete examples](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Examples), delete on a local variable or parameter will do nothing and (and as of that returns `false` for that `delete`). So you can just remove the `delete x;` form the given code without changing anything about its logic. – t.niese Feb 09 '19 at 16:06

1 Answers1

0

That's because what you're doing is creating a function and then calling it immediately where x = 0. Your function is returning x, and thus 0.

As for what anonymous functions are, they are basically a function that gets stored in a variable. You call it from the variable instead of by name. So, for example:

var output = function (x) { return x;};

Can be called like this:

output(0);

As opposed to the normal way like this:

function myOutput(x) {
    return x;
}

myOutput(0);