JavaScript local and global variable confusion [duplicate] - javascript

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Variable: local scope, global scope or is it the JavaScript engine?
(3 answers)
Closed 9 years ago.
I am new to JavaScript and I was doing some practices on local and global variable scopes. Following is my code(fiddle):
var myname = "initial"
function c(){
alert(myname);
var myname = "changed";
alert(myname);
}
c();
When the first alert is called, it is showing myname as undefined. So my confusion is why I am not able to access a global instance of myname and if I don't define myname within the function then it will work fine.

In JavaScript, the variable declarations are automatically moved to the top of the function. So, the interpreter would make it look more like this:
var myname = "initial"
function c(){
var myname;
// Alerts undefined
alert(myname);
myname = "changed";
// Alerts changed
alert(myname);
}
c();
This is called hoisting.
Due to hoisting and the fact that the scope for any variable is the function it's declared in, it's standard practice to list all variables at the top of a function to avoid this confusion.

It is not replacing the global variable. What is happening is called "variable hoisting". That is, var myname; gets inserted at the top of the function. Always initialize your variables before you use them.
Try this:
var myname = "initial";
function c() {
alert(myname);
myname = "changed";
alert(myname);
}
c();

Related

Newbie Questions on Scoping and Hoisting? [duplicate]

This question already has answers here:
What is the temporal dead zone?
(3 answers)
Are variables declared with let or const hoisted?
(7 answers)
Closed 1 year ago.
I am learning Javascript and I got into the hoisting/scoping part. I got some questions that I really hope somebody can help me to clarify and here is my example:
So these works normally due to hoisting - the firstName variable is in Global Scope or function can be called before we declare the function:
function test() {
console.log(firstName);
}
const firstName = 'a';
test();
OR
const firstName ='a';
test();
function test (){
console.log(firstName)
}
However, if I swap the order of firstName and test(), the code does not work anymore:
function test() {
console.log(`${firstName}`)
};
test();
const firstName = 'a';
According to the hoisting, I thought the firstName variable is in the Global Scope. Thereby, the test function should have been able to look up at the variable firstName when it is executed.
But why in the case above, it does not work?
Is there anything wrong with my understanding of hoisting/scoping?
Variables declared with let and const are also hoisted, but unlike for
var the variables are not initialized with a default value of
undefined. Until the line in which they are initialized is executed,
any code that accesses these variables will throw an exception.
MDN DOCS

"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).

JavaScript: understanding scope chain [duplicate]

This question already has answers here:
Javascript function scoping and hoisting
(18 answers)
Closed 3 years ago.
What is the scope chain in following code snippet -
var name = 'John';
function foo() {
if (false) {
var name = 'James';
}
console.log(name);
}
foo();
I got couple of queries regarding this -
Why the logger in function foo is printing undefined even when the variable
is available in global scope? Is it due to the fact that same variable
is re-declared in conditional falsy block and so the global variable is
getting removed from the scope?
Also if we replace the variable declaration under if statement inside function foo from var to let, the logger inside the function foo prints name from global scope. How this is working?
Yes this is because the variables declared with var have function scope and they are hoisted to the top of the function. It logs undefined due to hoisting.
Variables declared with let have block scope so until the if block is not executed the variable name is not declared.
Even if you change it with if(true) it will not work because the variable will only be available inside the block. {} not outside.
Here is the example how let works.
if(true){
let x = 3
}
console.log(x);
If you redeclare variable with var, it has the scope in the whole function. If you do it with let instead of var, it will be available only in the if scope.
var name = 'John';
function foo() {
if (false) {
let name = 'James';
}
console.log(name);
}
foo();

Javascript object creation practices [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 6 years ago.
This is what I think is best for making an object in js
function obj(){
var x = "hi";
this.getX(){return x;}
}
var y = new obj()
console.log(y.x); //this returns undefined
But from what I have seen, using this.variable is used more often in object creation.
I am thinking in java where things should be "private" in a class (note I have read about closures), does that apply in js?
What is considered the best way of object creation?
It sounds like you're trying to apply Java concepts to JavaScript, but things works completely differently in JS. You should check out the MDN article on JavaScript closures.
var variables exist in the closure. They are accessible from any function declared in the same scope.
var me = 'hello';
function someFunction() {
console.log(me);
}
someFunction(); //prints 'hello' to console
this variables will be directly accessible, even outside the scope, in the resulting object.
function someFunction() {
this.me = 'hello';
}
var instance = new someFunction();
console.log(instance.me); //prints 'hello' to console

variables scope confusion in javascript [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 9 years ago.
I was studying the concept of variable scope in JS, found this example on it:
(function() {
var foo = 1;
function bar() {
var foo = 2;
}
bar();
console.log(foo) //outputs 1
if(true) {
var foo = 3;
}
console.log(foo) //outputs 3
})();
output of this function is
1
3
Now I am confused how come foo gets gets value 3 in second log. even when foo is declared by using var in if statement. shouldn't the foo declared in if will have a new instance as it gets in bar()??
if does not introduce a scope block (I understand it does in some langauges). In JavaScript, only function() {} creates a scope block.
There are only two kinds of scope in Javascript; function scope and global scope.
The code inside the if statement doesn't have a scope of its own, so the variable inside the if statement is the same one as the one outside it.
Declaring a variable more than once in a scope doesn't create more than one variable. The var keyword inside the if statement is ignored as the variable already is declared once in the scope, so it's just an assignment.
Note also that the declaration of variables is hoisted to the top of the scope, so even if a declaration is inside a code block that is not executed, the variable is still created:
var foo = 1; // a global variable
(function() {
console.log(foo) //outputs "undefined"
foo = 2; // sets the local variable
if(false) {
var foo = 3; // creates the local variable, but the assignment never happens
}
console.log(foo) //outputs 2
})();
console.log(foo) //outputs 1

Categories