-3

I wrote simple code like this

var value = function(a){return a*3;}
var number = value(a);

when i type value(5); i will get number 15 thats OK, but after typing number; ill get NaN. I just want to write in variable the result of function.

Perezo123
  • 31
  • 1
  • 7

1 Answers1

0

JavaScript is not a computer algebra system, and it cannot store an algebraic expression like x * 3 in a variable. Instead, when you do:

var y = x * 3;

the variable y will be set to 3 times the value that x had when that statement was executed. If no value has been assigned to x before, then its default value will be undefined. And according to JavaScript's arithmetic rules undefined is automatically converted to NaN when used in an arithmetic expression, and NaN * 3 equals NaN.

(Actually, what you should be getting, if you try to execute the code above without declaring the variable x first, is a ReferenceError: x is not defined exception. But if you add a var x; statement before that code, to declare the variable x but leave its value undefined, then you'll indeed get NaN as the value of y.)

The fact that you've wrapped the multiplication inside a function makes no difference here. The following code:

var f = function (a) { return a * 3 };
var y = f(x);

does exactly the same thing as:

var y = x * 3;

(except, of course, for the fact that the former version also defines the function f.)

Ilmari Karonen
  • 49,047
  • 9
  • 93
  • 153