1

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

asked Nov 23, 2011 at 13:43
1
  • Because you cannot multiply a number with a function (what result do you expect?). The function object, represented as number, is NaN. Commented Nov 23, 2011 at 13:45

4 Answers 4

1

try :

you missed (x)

function cube(x) {
 return x * square(x);
}
answered Nov 23, 2011 at 13:44

Comments

1

It should be

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

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

answered Nov 23, 2011 at 13:44

Comments

1

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);
}
answered Nov 23, 2011 at 13:45

Comments

1

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)
answered Nov 23, 2011 at 13:49

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.