javascript - undefined and NaN, convert to boolean value implicitly vs explicitly -
i'm learning javascript following book "you dont know js".
in section "type & grammer", when discussing implicit vs explicit boolean convertion, author mentioned
//come function make sure 1 argument truthy //implicit convertion function onlyone() { var sum = 0; (var i=0; < arguments.length; i++) { // skip falsy values. same treating // them 0's, avoids nan's. if (arguments[i]) { sum += arguments[i]; } } return sum == 1; } //explicit convertion function onlyone() { var sum = 0; (var i=0; < arguments.length; i++) { sum += number( !!arguments[i] ); } return sum === 1; }is explicit coercion form of utility "better"? avoid
nantrap explained in code comments. but, ultimately, depends on needs. think former version, relying on implicit coercion more elegant (if won't passingundefinedornan), , explicit version needlessly more verbose.
my question is, nan trap author talking about? thought when undefined , nan converted boolean value, regardless of whether converted implicitly or explicitly, both results in false. , passing undefined , nan implicit function ok, right?
i think example of real explicit check be...
function onlyone() { var sum = 0; (var i=0; < arguments.length; i++) { sum += boolean( arguments[i] ); } return sum == 1; } this of course avoid / guard against nan , should return false if no arguments present; if no arguments truthy , of course -if more 1 arguments truthy.
Comments
Post a Comment