Javascript: Advise on variable creation -


i have couple of questions regards js.

when ever need return function create variable , return variable, seems maybe bad practise creating variable first , returning value , return value. true ? reason behind ?

variable creation @ top of function or create variable when needed ?

i have been creating variables @ top of function, beneficial create variables when need use them ? using es 2015 , other places es5.

and last thing check creation of variables on 1 line or separate lines i.e.

   var myfirstvariable = 1;    var mysecondvariable = 2;    var mythirdvariable = 3; 

vs

   var myfirstvariable = 1,        mysecondvariable = 2,        mythirdvariable = 3; 

does either style cause issues?

when ever need return function create variable , return variable, seems maybe bad practise creating variable first , returning value , return value. true ? reason behind ?

this coding style thing. if there no other use variable, can directly return value without first assigning local variable there no reason first assign local variable. if value being used other things before being returned, want assign local variable avoid computing more once.

for example, in this:

function multiply(x, y) {     var val = x * y;     return val; } 

there's no reason val variable. can do:

function multiply(x, y) {     return x * y; } 

today's interpreters smart enough recognize local variables have no other use other return value , optimize them out, people suggest should avoid using lines of code not needed , serve no other purpose.

variable creation @ top of function or create variable when needed ?

again, coding style choice. var declarations in javascript hoisted top of function scope not technically matter whether declared first @ top of scope vs. inline later in function. there legitimate situations both regards maximum code readability.

let declarations hoisted top of containing block there difference let declaration whether declared within block or @ top of function, no difference if declared within block or @ top of block.

and last thing check creation of variables on 1 line or separate lines

your second option:

var myfirstvariable = 1,     mysecondvariable = 2,     mythirdvariable = 3; 

is less typing, functionally no different first option. people prefer using commas separate multiple, consecutive declarations, again coding style choice minimize typing there no functional difference.