javascript - Why would we declare a 2nd variable in the below code? -


why declare second variable (val) when can use parameter of function variable?

here's how looks on codecademy:

var dividebythree = function (number) {     var val = number / 3;     console.log(val); }; dividebythree(6); 

i've made changes below:

var dividebythree = function (number) {     number = number / 3;     console.log(number); }; dividebythree(6); 

and works pretty fine!!

in example, not need preserve original value of parameter. however, may find easier use variables in future more complicated functions.

here example:

// function uses parameter "rawnumber" variable, uses variable "number" function testthis(rawnumber, p) {     // convert input (string) integer     // parseint returns nan or integer.  truncates decimals     var number = parseint(rawnumber);      // check see if result nan or integer     if (isnan(number)) {         log(rawnumber + " not number.", p); // log imitation of console.log()     }      // run if number type int     else {         if (number > 0 && number <= 100) {             log(rawnumber + " valid number.", p);         } else {             log(rawnumber + " not between 1 , 100.", p);         }     } } 

you can see code working in fiddle.

in function used variable called "number" in 3 different places. didn't have to, easier typing isnan(parseint(rawnumber)) , if(parseint(rawnumber) > 0 && parseint(rawnumber) <= 100). codecademy decided teach way because easier realize can simplify code realize can simplify more complex code through use of variables.

also, jk price's answer brings readability issue. put, code easier read , understand:

function example(number) {     var processednumber = 5/(math.log(1/number*3.14 - 7));     console.log("message: " + (processednumber * 2));     console.log("message: " + (processednumber / 10)); } 

this code might little harder:

function example(number) {     console.log("message: " + ((5/(math.log(1/number*3.14 - 7)) * 2));     console.log("message: " + ((5/(math.log(1/number*3.14 - 7)) / 10)); } 

Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

datatable - Matlab struct computations -