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

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.

Related

"this" refers to "window" object not working as expected [duplicate]

This question already has answers here:
Do let statements create properties on the global object?
(5 answers)
Closed 2 years ago.
I experimented a bit with this keyword and I found a strange problem. When a variable is declared as var then this correctly refer to this variable. But if i declared the same variable as let or const then this lost reference and show undefined in console.
var prop = "outer"; // not working if let or const.
let foo = {
prop: "inner",
show() {
console.log(this.prop)
}
}
let a = foo.show;
let b = foo.show.bind(foo);
a()
b()
When you run this code outside of strict mode (as here), then the this keyword defaults to the global object - which in the browser is window. (In strict mode it would be undefined so a() will throw an error.)
The difference in behaviour between var and let/const is a simple consequence of the fact that var-declared global variables are the same thing as properties on the global (window) object, whereas that doesn't happen with variables (even global ones) declared with let or const.
See for example MDN:
Just like const the let does not create properties of the window object when declared globally (in the top-most scope).

Safety of global vs local variables? [duplicate]

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.

Will JavaScript Closure save all variables in its scope, or only those the closure referred? [duplicate]

This question already has answers here:
Over how much of its enclosing scope does a (javascript) closure close?
(2 answers)
Closed 5 years ago.
We knew that
function foo () {
var x = 10;
var y = 20;
function bar () {
return x + 1;
}
bar(); // 11
}
The function bar create a closure, and save the reference of x.
But what about the variable y? Will the closure bar created hold its reference? I tried it in Chrome Dev Tools, and it shows only x in the [[Scopes]] field, without y. But I can not find any articles about that.
Does it means the closure creation will only pick what it need to save?
Scopes are chained together and it'll check with parent scope when reference cannot be find. This question is answered before and you can reference it here:
Scope Chain in Javascript

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.

define variable with/without var prefix 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 8 years ago.
Is there a difference define variable in global scope between
var my_var;
and
my_var;
In global scope, there is no difference, unless you using it again: var my_var; will redeclare it, while my_var; will be simply useless expression.
There is a difference only when not in global context.
Ex1 (with var):
var x = 0;
(function(){
var x = 1;
alert('fx: '+ x);
})();
alert('gx: '+ x);
//fx: 1
//gx: 0
Ex2 (without var):
x = 0;
(function(){
x = 1;
alert('fx: '+ x);
})();
alert('gx: '+ x);
//fx: 1
//gx: 1
var is actually (re)declaring the variable in any current scope while second form is declaring it (globally?) unless it's been declared in a containing scope before. The second form is implicitly declaring, while first form is doing so explicitly.
Thus there is no difference in global scope, for it isn't contained in any other scope.

Categories