Second variable inside of a function? (with/without)


Hi guys,

I tried making a function called "double" to double the input number.
I created the below to different formulas which both work, one with including the second var "val", and one without.

1) var double=function(number){console.log(number*2)};double(2)
2) var double=function(number){var val= number*2;console.log(val)};double(2)

These both got the same result, but is there anything significant/important that should make me want to use the second "var val" in my functions? Code on line #1 seems a lot easier to write than 2 since I don't have to call a second variable.


Hello @systemmaster50025,

As you rightly pointed out, both give same answer, 4, with the first written in a minified fashion. There is so much comfort in doing stuffs the way and matter you find best and easier, just like in the first line of code.

But you see, generally, if you would need to reuse certain variables in a code chunk, rather than rewrite them over and over and over again, I will definitely advise you stick with declaring your variables. Also, it's easier for continuity. That is, anyone who needs to rework and continue work on the project, will find it easy -- if not easiest.

I know it's easy to say, "I will comment every portion", but you will use less comments if you heed to defining/assigning variables.

I will like to stop here, but I hope the above gives my view in clear way.

Thank you! :slight_smile:


Thanks for your answer!

One more question -- In line #2 of my code, when I further declared variable "var", is that variable only usable in the {} brackets it is located in, or can I use it on other liens of code past the closing } bracket?


Except it is a global variable. That is, the variable could be inside a function (main) and another function in it.

See JavaScript closures


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.