Simpleton
Simpleton

Reputation: 6415

Can you not use function variables inside another function's associated code?

In the code exercise at Codecademy[1], it asks you to cube a variable and I can easily do that using:

// Accepts a number x as input and returns its square
function square(x) {
  return x * x;
}

// Accepts a number x as input and returns its cube
function cube(x) {
  return x * x * x;
}

cube(7);

My question is for the cube function, why do I get a NaN error when I use the following code instead:

function cube(x) {
  return x * square;
}

[1] http://www.codecademy.com/courses/functions_in_javascript/0#!/exercise/1

Upvotes: 1

Views: 435

Answers (4)

hugomg
hugomg

Reputation: 69934

When you have a multiplication or division operation, both arguments are first converted to numbers. Functions don't have a reasonable conversion so they are converted to NaN.

Number(function(){}) //gives NaN

And if you multiply anything by NaN you also get NaN

2 * NaN
1 * (function(){}) //also gives NaN since the function is converted to that

The solution (as many mentioned) is multiplying by the square of x instead of by the square function itself.

x * square(x)

Upvotes: 1

steveyang
steveyang

Reputation: 9298

In your code, square is resolved as a function. And to get the returned value, you need to invoke the function instead just reference it.

function cube(x) {
  return x * square(x);
}

Upvotes: 1

pradeek
pradeek

Reputation: 22105

It should be

function cube(x) {
    return x * square(x);
}

x * square will attempt to multiply x with a function which causes the problem

Upvotes: 1

Royi Namir
Royi Namir

Reputation: 148524

try :

you missed (x)

function cube(x) {
  return x * square(x);
}

Upvotes: 1

Related Questions