0

Can somebody tell me, can I in javascript declare a function into var and execute it in the same experession(program-line)?

var tmp = 0,
a = function() {
    ++tmp; /*rest of code*/
};
a();
console.log(tmp);
Kamczatka
  • 151
  • 1
  • 2
  • 15

1 Answers1

1

if you surround a function declaration with parentesis you get an expression. an assigment is also an expression (is evaluated as the value assigned) and you can leverage this fact to obtains your result.

var tmp = 0, a;
(a = function() { ++tmp;})();
a();
console.log(tmp);

Said that, to me, I wouldn't like to have to read code like this. It is prone to errors and misinterpretation.

Eineki
  • 14,773
  • 6
  • 50
  • 59