This is a very basic question. I’m learning Javascript, and I’m fairly new to programming in general. In a lot of tutorials, I’ve seen something like this:
function add(a,b) {
var sum = a+b;
return sum;
}
Now, for such a simple calculation, it seems to me that there’s no reason to create an intermediate variable. Rather, my instinct would be to do this:
function add(a,b) {
return a+b;
}
I can understand the rationale for using intermediate variables if I’m doing a more complex calculation with multiple steps, and of course they’re necessary for conditionals. Are these tutorials just trying to inculcate habits for readable code when things get more complicated, or is there a reason why the first example is inherently better? It seems like there’s a memory performance cost in doing it the first way. Is there something obvious that I’m missing?
I’ve searched SO and also googled it, but haven’t had much luck.
I use things like this often to make debugging easier. That way I can see exactly what the return value will be before stepping out of a function.
Also it makes scaleability much easier as, you can have more variables flying around before returning a value.
Don’t be cheap when it comes to using variables, else you’ll pay for it later. Of course I mean in cases more complex than your example.