javascript - Getting NaN as a result for my JS function. Could anyone explain why? -


i'm new javascript, please bear me. wrote function returns difference between highest , lowest number in array:

// function 1  function range (arr) {    var max = math.max.apply(null, arr);    var min = math.min.apply(null, arr);    var max_diff = max - min;    return max_diff;  }  console.log(range([6,2,3,4,9,6,1,0,5])); // 9

however, before came solution, tried approach:

// function 2  function range (arr) {    var max = function (arr) {      return math.max.apply(null, arr);    }    var min = function (arr) {      return math.min.apply(null, arr);    }    var max_diff = max - min;    return max_diff;  }  console.log(range([6,2,3,4,9,6,1,0,5])); // nan

this function returns "nan". read on nan, it's still not clear me why "nan" result.

the other strange thing is: if put function 2 before function 1, second function returns correct result (9).

whaaaat?

you subtracting 2 functions, max , min. functions first coerced primitive values, coerced numbers, , subtracted.

when coerced primitives, functions return implementation-dependent string representation of code. not coercible number, nan, i.e., not-a-number. subtracting nans produces nan.

maybe wanted run iifes (immediately-invoked function expressions) instead:

// function 2  function range (arr) {    var max = function () {      return math.max.apply(null, arr);    }(); // <-- max value returned calling function    var min = function () {      return math.min.apply(null, arr);    }(); // <-- min value returned calling function    var max_diff = max - min;    return max_diff;  }  console.log(range([6,2,3,4,9,6,1,0,5])); // 9


Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -