Javascript Undefined variable redefined inside function [duplicate] - javascript

This question already has answers here:
Why variable hoisting after return works on some browsers, and some not?
(5 answers)
Closed 6 years ago.
could you please help me understand why JS works this way here?
var timer = 3;
var func = function() {
alert(timer);
var timer = 5;
}
func();
It returns me "undefined".
If I do
var timer = 3;
var func = function() {
alert(timer);
timer = 5;
}
func();
it works as expected (alerts 3).
It is something with scopes that I didn't understand correctly.
Shouldn't JS overwrite the definition of "timer" after the alert?
Tested just on chrome.
Thank you guys.

var timer = 3;
var func = function() {
alert(timer);
var timer = 5;
}
This code becomes this when js interprets ;
var timer = 3;
var func = function() {
var timer; // Here local variable timer is undefined
alert(timer); // here local var timer alerts rather than global var timer
timer = 5; // here timer got initialized
}
This happens because of hoisting concept in javascript. You can read hoisting frome here

Variable hoisting is annoying in that javascript 'hoists' (send variable declarations) to the top of the current scope.
It doesn't however send initializations to the top of the current scope.
So:
var timer = 3;
var func = function() {
alert(timer);
var timer = 5;
}
becomes:
var timer = 3;
var func = function() {
var timer;
alert(timer);
timer = 5;
}
When it is interpreted.
Hoisting is (to many developers) an unknown or overlooked behavior of JavaScript.
If a developer doesn't understand hoisting, programs may contain bugs (errors).
To avoid bugs, always declare all variables at the beginning of every scope.
Since this is how JavaScript interprets the code, it is always a good rule.

Related

What happens when two variables hoisting with the same name?

So if i declare two variables like this:
var a = 5;
var b = 10;
Javascript compiles code and until the assignment occurred these variables are undefined.
But if i write like that:
var a = 5;
var a = 10;
what happens when these variables hoisting?They both have name a and
they are undefined?Or maybe it's one variable and undefined is written twice in it?
Hoisting isn't really relevant here. You can't have two variables with the same name in the same scope. As many times as you write var a, there is just one variable a, which is hoisted no differently than if you had a single var a.
This code...
function() {
var a = 5;
var a = 10;
}
is functionally equivalent to this code, with a hoisted:
function () {
var a;
a = 5;
a = 10;
}

javaScript issue about "this" [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 5 years ago.
I'm trying to build a game demon, and run into a problem when I'm trying to add a clickEventHanlder to a button, the code goes here:
function GameConstructor(){
this.start = startGame;
this.count = 5;
...
function startGame(){
if(this.count > 5){ //here goes the problem, this don't point to the game object when I click the button
...
}
}
...
var game = new GameConstructor(); //game object has a method called start
$("#someBtn").click(game.start); //in the method start this now point to the button so this.count is undefined.
I know I can define a global variable count = 5 to solve this, but I just wonder if there is a way to fix in my original way? Thanks.
I'm not a complete JavaScript wizard, but my guess is that the this inside your nested function is referring to that nested function, not the outer instance.
Many people opt to create a self variable instead, to be a bit more explicit about this scope stuff. Maybe try this:
function GameConstructor(){
var self = this; // <-- here, then reference self subsequently
self.start = startGame;
self.count = 5;
...
function startGame(){
if(self.count > 5){ //here goes the problem, this don't point to the game object when I click the button
...
}
}
this always point to the current function context in Javascript. Means the lowest function just out of the 'this'. So, you can do like;
function GameConstructor(){
var self= this;
this.start = startGame;
this.count = 5;
...
function startGame(){
if(self.count > 5){ //here goes the problem, this don't point to the game object when I click the button
...
}
}
...
var game = new GameConstructor(); //game object has a method called start
$("#someBtn").click(game.start); //in the method start this now point to the button so this.count is undefined.

"setInterval" function is dumping properties assigned in constructor function [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 6 years ago.
Hi I'm trying to create an object in jQuery and everything is working fine but somehow I cannot pass some necessary properties beyond the setInterval function bc when I test it it always pops "undefined". Here is the draft code of that I have.
Thanks in advance!!
function MyFunction(var1){
this.var = var1;
this.var2 = 2;
this.pause = 3000;
this.slideOn();
}
MyFunction.prototype.slideOn = function(){
alert(this.var); //alerts the value
setInterval(function(){ //doesnt work and it alerts "undefined"
alert(this.var2),1000,function(){}
},this.pause // works again with no hassle
};
When you use "this" inside some callback function, it uses function scoped "this". So, try setting an "outer this":
function MyFunction(var1){
this.var = var1;
this.var2 = 2;
this.pause = 3000;
this.slideOn();
}
MyFunction.prototype.slideOn = function(){
var _this = this;
alert(_this.var); //alerts the value
setInterval(function(){ //doesnt work and it alerts "undefined"
alert(_this.var2),1000,function(){}; //100 and function are senseless
},_this.pause); // works again with no hassle
};

Difference between let and var in JavaScript [duplicate]

This question already has answers here:
What is the difference between "let" and "var"?
(39 answers)
Closed 6 years ago.
I was going through the javascript style guide by Airbnb (https://github.com/airbnb/javascript).
In section 2.2 it is explained that
let is block-scoped rather than function-scoped like var.
// bad
var count = 1;
if (true) {
count += 1;
}
// good, use the let.
let count = 1;
if (true) {
count += 1;
}
I didn't get why the first one is bad practise and second is bad and if both let and var are block scoped then what difference does it make, if I use either of them?
Also what is the difference between function scoped and block scoped?
When something is block scoped it means that you can control the lifetime better and more intutive ways
for example
function a() {
if (true) {
var a = 7;
let b = 42;
}
}
The var a is pulled out in the scope of the function, rather than stying isolated in the block for the if, so like this;
function a() {
var a; // The JS compiler pulls the var out to this level
if (true) {
a = 7;
let b = 42; // but keeps the let in this block.
}
}
.. and that is counter intuitive and sometimes lead to problems -- the let does not have that problem.

Hoisting in javascript

I asked a question before and somebody give me a guide and I read it and I saw this
var temp = setTimeout,
setTimeout = function() {};
He said that temp will be undefined due to JavaScript hoisting and I dont understand why
Its not should be like that?
var temp;
temp = setTimeout;
setTimeout = function() {};
so why its undefined?
This is not the same. Your multiple var declaration also declares setTimeout:
var temp = setTimeout,
setTimeout = function() {};
which is hoisted to
var temp; // = undefined
var setTimeout; // = undefined
temp = setTimeout;
setTimeout = function() {};
The scope of a variable declared with the keyword var is its current execution context. When a variable is initialized, javascript engine by default initializes the variable to undefined.
Like,
var a; //it initializes to undefined
Again when you use a variable before declaring them, its now on running context.
For Example:
console.log(a);
var a=10;
in this case, javascript engine runs the code in following ways,
var a; // a = undefined
console.log(a); //
a =10;
it pick up the variable declaration to the top of the execution context but not its value. This is called hoisting that you have already probably known.
In your case:
var temp = setTimeout,
setTimeout = function() {};
from function(){}, suppose we get value =10;
now your code seems like:
var temp = setTimeout,
setTimeout = 10;
but javascript does the thing in the following way,
var temp; // temp = undefined
var setTimeout; // setTimeout = undefined
temp = setTimeout; // here temp is undefined as setTimeout is undefined
setTimeout =10;
it keep up all declared variable to the top of stack (Not its value but initializes to undefined).
If you want to learn more, visit the following link:
medium: what is javascript hoisting
scotch: understand hoisting in javascript

Categories

Resources