0

Is it safer to only use local variables within your JavaScript code?

As I understand variables declared within the $(document).ready(function () {code here...} block are local. Meaning these cannot be accessed or changed by other scripts?

Also, if a variable is declared global but assigned a value locally, is this value then globally visible?

var a; function myFunction() { var a = 4; }

Will other scripts on the page be able to see the value of a being set to 4?

  • 1
    note: if you redeclare `a` with a `var` inside the function, this will create a second variable which will be local, thus hiding access to the first one. If you had used `a=4`, it would have set the value to the first one declared. I recommend that you also read about javascript var hoisting. – Kaddath May 10 '17 at 08:46
  • Yes, yes, no, no. – Bergi May 10 '17 at 08:46
  • Take a look at this http://stackoverflow.com/questions/10525582/why-are-global-variables-considered-bad-practice – Alexis May 10 '17 at 08:50

1 Answers1

0

No, the variable a in your function is not visible outside of the function scope. If you try to access the variable a somewhere else in the code it will display undefined, because you have just declared the variable, but didn't assign any value to it.

Let's extend your example:

var a;
function myFunction() {
    var a = 4;
}
function anotherFunction() {
    console.log(a);
}
anotherFunction();
> undefined

When we called anotherFunction() it accessed the globaly declared a, it doesn't see the local variable a from myFunction. They are completely different.

It is better not to use local variables in this way. If you need them, you better group them in one object, which would have the role of a namespace:

var allMyLocalVariables = {
    a: 'a',
    b: 'b'
}

Now you can access them anywhere like this:

console.log(allMyLocalVariables.a);

and the probability that they will collide with other variables is very low if you chose a sensible and meaningfull name for your object/namespace.

cezar
  • 11,616
  • 6
  • 48
  • 84
  • Not agree with this. When you change the global variable, his global value change too and is accessible – Alexis May 10 '17 at 08:47
  • You don't change the global variable. The variable `a` in `myFunction` is not the same as the global variable `a`. If you do the statement like this: `a = 4`, without the keyword `var`, that would be another story. – cezar May 10 '17 at 08:49
  • 1
    if you use var on the function then you're not using the global variable you're just define an local variable and don't use the global... – Alexis May 10 '17 at 08:56
  • 1
    Exactly that is what I was explaining. They are completely different variables in different scopes. – cezar May 10 '17 at 09:36