Safety of global vs local variables? [duplicate] - javascript

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 5 years ago.
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?

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.

Related

JS: local var X global (window) var [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
window.variableName
(6 answers)
Closed 4 years ago.
Studying global vars in JS here, I set out to try it and to my surprise this:
var thisVar = "global var";
function showVarLet() {
var thisVar = "local var";
console.log("%s %s", thisVar, window.thisVar);
}
showVarLet();
gives me:
local var
undefined
but the same in the browser console, gives me:
local var
global var
So, what´s with this window object?
EDIT:
I tried to check in the console what would happen if instead of window.thisVar I referenced this.thisVar, my assumption was that I would access the local variable but I keep accessing the global one, why so?
and the code I showed is in a function called global()
then none of the two thisVars is global, one is a local variable of the global() function, the other one is a local variable of showVarLet(). You cannot access local variables via window..

Difference between local and global variables in javascript? [duplicate]

This question already has answers here:
What is the purpose of the var keyword and when should I use it (or omit it)?
(19 answers)
Closed 6 years ago.
I noticed that in JavaScript, Inside a function some times a variable created without mentioning var before it.
For example :
function myfunction() {
x = 10;
var y = 10;
}
what is the difference between these both?
function myact() {
x = 20;
var y = 10;
console.log(x);
console.log(y);
}
myact();
console.log(x);
//y not available here
var is used for declaration. So, assigning without declaration will simply give it global scope meaning: it will first search if it is available in any scope stack above, if not creates the variable implicitly in global scope and assigns.
JS Docs says:
The scope of a variable declared with var is its current execution
context, which is either the enclosing function or, for variables
declared outside any function, global.
Assigning a value to an undeclared variable implicitly creates it as a
global variable (it becomes a property of the global object) when the
assignment is executed.

Create variable name based on argument sent to function in javascript [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 7 years ago.
I wanted to create variable name based on value sent to function in javascript.
like following, when i call function variable : variable("zebra"); this should return variable name as zebra1
function create variable(i){
return i+"1";
}
var variable("zebra")="abc";//this line should create variable zebra1 and initialise as abc
Try:
window['zebra'] = 'abc';
The window object holds all the global variables, assuming this is a request for global variables.
To specifically answer your question, you could put return window[i + '1'] = 'abc'; in your variable naming function.
Alternatively, you could create a global (or local) object named variables to hold all your variables:
function whoknows() {
var variables = {};
variables['zebra'] = 'abc';
}
Read more on working with objects at mozilla.org
You can create global variable with
window["zebra"] = "abc";
and use later ether with the same indexer syntax or directly - zebra.

Javascript variable declaration, why is this legal? [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 8 years ago.
I just encountered this variable declaration syntax for the first time.
var myVar = (function() {
return 1;
})();
My 2 main questions are..
What is it called, and why is it legal?
Forgive me if this question has been asked before, I tried searching around but I have no idea what this notation is called so I wasn't able to find anything.
Also, I should add, what is the function of the 2 sets of parentheses? The first of which encloses the function, the second of which is empty.
Self executing functions are typically used to encapsulate context and avoid name collusions. Any variable that you define inside the (function(){..})() are not global.
The following code:
var same_name = 1;
var myVar = (function() {
var same_name = 2;
console.log(same_name);
})();
console.log(same_name);
produces this output:
1
2
By using this syntax you avoid colliding with global variables declared elsewhere in you javascript code.
I am not sure what this is called, other than defining an anonymous function and immediately invoking it.
It is perfectly legal, because
Defining an anonymous function is legal.
Invoking it and assigning the return value is also legal.
The end result is that myVar = 1.
This is an anonymous function (also called lambda function) that is being executed immediately with its return value (1) being assigned to a variable (myVar). It's legal because the specification says it is. It is a very common feature in many languages.

why without var? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between using var and not using var in JavaScript
seems stupid question but just curious.
num = "hello";
alert(num);
why is this possible I didnt initialize the num variable here.
num = "hello";
instead of
var num = "hello";
var means "Scope this variable to this function" not "Make it possible to use this variable".
If you leave var off then it will use the variable in the next scope up from the function. If that scope doesn't have the var yourVar then it will keep going up the scope chain until it becomes a global and dangles off the window object (assuming a browser or another JS environment in which the default object is window).
(This changes in strict mode, which you are presumably not using.)
Without the var keyword the variable is created at the global scope (in browsers under window).
If you add the var you just assign the variable to the current scope, which in most cases will be a function scope.
In general it will be better to use a function scope in order to not pollute the global scope and prevent conflicts between multiple variables of the same name!

Categories