0

I am doing a small work in JavaScript and I want to avoid problems, so I am asking beforehand.

Can I use two different variables and name them the same in different functions, given that one of these functions calls the other?

So, when I define the variable in the second function, will it interpret as two different variables, or will it rewrite the value of the original variable from the first function? (Or, will it throw an error due to the fact that a variable with that name already exists?)

Here is an example:

function first()
{
var a = somevalue;
second();
}

function second()
{
var a = differentvalue;
}

Thanks!

1
  • It's two distinct variables. No matter if the functions call each other. Commented Mar 27, 2013 at 14:11

2 Answers 2

3

Variables declared inside a function are local to that function, and doesn't conflict with variables with the same name anywhere else.

You can even have a global variable with the same name, and the code inside the function will only see the local variable.

Example:

var a; // global variable

function first() {
  var a; // local variable in first
  second();
}

function second() {
  var a; // local variable in second
}

(Global variables should of course be used as little as possible, but it's good to know that you can have a local variable that is unaffected by any global variables that may exist.)

A local variable inside a function is not only local to the function, it's actually local to that execution of the function. If you call the function again, a new variable is created, and if the function calls itself (recursion), each level will have it's own variable.

Sign up to request clarification or add additional context in comments.

Comments

2

Yes you can, as long as you don't forget the var keyword : the scope of a variable is either the function in which it is declared or the global scope. There is no way from outside the functions to gain access to the variables they declare.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.