When to use a new variable in JavaScript


#1

hi,

this may seem like a silly question, but i'm curious as to when, how, and why to properly use new variables in JavaScript. it seems like anytime the original variable changes through use, you store it with the changes in a new variable, as opposed to including the new information with the old variable.
specifically, instead of saying like:
var perimeterBox = function(length, width) {
return( ( 2 * length) + (2 * width));
};
var newNum = perimeterBox(3,1);
console.log(newNum);

why wouldn't you just say:
var perimeterBox = function(length, width) {
return( ( 2 * length) + (2 * width));
};

console.log(perimeterBox(3,1));

i understand both work, there are different coding styles, and there are multiple ways to write the same thing, but it seems like a little bit further into JavaScript, changing the name of the variable every time you use it in a slightly different way is quite common i don't quite understand why this happens. this notion has been a real stumbling block to my understanding, so any concrete answers would be much appreciated!

thanks!


#2

Variables should usually be named by what they represent, so if you compute a value that represents something other than already existing variables, then that goes into a new variable..Otherwise you'd be writing lies, eh.

If you're only going to use something once, then there's no need to store it. That doesn't mean the whole program should be a single statement, better to avoid complicated statements by splitting them up into smaller parts.