简体   繁体   中英

Why am I getting NaN for this variable?

Anyone know why the bigNumberB variable is returning Not a number? I'm new to java and messing around with functions and I can't see what I'm doing wrong here but I'm sure its something simple. Thanks, I am getting 24, 24, NaN

function mathEquation(moja, mbili, tatu, tano) {  
var value = moja * mbili * tatu * tano;  
console.log(value);  
}

mathEquation(1, 2, 3, 4);

function inceptEquation(sita, tisa) {  
var bigNumber = mathEquation(1, 2, 3, 4);  
console.log(bigNumber);  
var bigNumberB = sita + tisa + bigNumber;  
console.log(bigNumberB);  
}

inceptEquation(11, 23);

You aren't returning anything from mathEquation

function mathEquation(moja, mbili, tatu, tano) {  
  var value = moja * mbili * tatu * tano;  
  console.log(value);  
  return value; // <- return the value here
}

Without returning a value, you are trying to add 11 + 23 + undefined

You're not returning the sum of value in mathEquation . By default a function with no explicit return value will return undefined . So essentially you're doing this in inceptEquation :

11 + 23 + undefined;

Adding undefined to any number will result in NaN .

Instead just return the sum as so. There's no need for the value if it's not being used anywhere else in the function:

function mathEquation(moja, mbili, tatu, tano) {  
  return moja * mbili * tatu * tano;  
}

All you have to do is to change the console.log() s to return() s. Here is the simple version:

function multiplication(x, y, z, c) {
  var value = x * y * z * c;
  return(value);
}

console.log(multiplication(1, 2, 3, 4));

function addition(x, y) {
  multiplication(1, 2, 3, 4);
  return(x + y + multiplication(1, 2, 3, 4));
}

console.log(addition(11, 23));

Hopefully this is what you were expecting!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM