Javascript and Hoisting - javascript

In my code, the x value is undefined. If I remove if block, the x value is displayed as 77. I don't understand why if block is modifying the x value.
var x = 77;
function fn() {
if (false) {
var x = 55;
}
console.log(x);
}
fn();

var x = 77;
function fn() {
if (false) {
var x = 55;
}
console.log(x); // undefind
}
fn();
In the intermediate phase, x will be hoisted to its scope:
var x = 77;
function fn() {
//var x = undefind; intermediate phase
if (false) {
var x = 55;
}
console.log(x);
}
fn();
var x = 77;
function fn() {
if (false) {
x = 55;
}
console.log(x); // 77
}
fn();

The x variable is redeclared and hoisted inside the function, but never set because if (false) will never be reached thus undefined. The outer x is known inside the function if you remove the inner declaration.
This can be solved by using const or let (ES6) instead of var. const and let is not hoisted and lives only inside of the brackets they are declared:
const x = 77;
function fn() {
if (false) {
const x = 55;
}
console.log(x); // 77
}
fn()
Another solution is to just use two different variable names or remove the var inside the if statement depending on your needs...

Inside the scope of the function, the variable x is hoisted to the top as follows var x; If you print it, you get undefined. It is never assigned a variable as it is not going inside the if block

Simply remove the var inside the if-statement. That will fix the hoisting issue.
var x = 77;
function fn() {
if(false) {
x = 55;
}
console.log(x); // 77
}
fn();

You can also use let keyword.
let x = 77;
function fn() {
if (false) {
let x = 55;
}
console.log(x); // 77
}
fn()

one should use wither ES6 define syntax const OR let while assigning the variable, if needs to mutate the variable then use let, otherwise use const , stop using var .
In your scenario while using var there, it means you are trying to re initialize the x, it gets hoisted
var x = 77; means
var x; outside the block.
So one should not need to re initialize the x just pass the value or either use let or const .
function fn() {
if (false) {
//
x = 55;
}
console.log(x);
}
fn();

Related

javascript for-loop and timeout function

I am facing an issue with a for-loop running a setTimeout.
for (var x = 0; x < 5; x++) {
var timeoutFunction = function() {
return function() {
console.log(x)
}
}
setTimeout(timeoutFunction(), 1)
}
I expect the output
0
1
3
4
Yet, for some reason they all output 5.
Variable x is defined in the local scope of the for-loop, so I thought this may not count for the callback of setTimeout. I tested with defining x outside of the for-loop.
var x = 10
for (var x = 0; x < 5; x++) {
var timeoutFunction = function() {
return function() {
console.log(x)
}
}
setTimeout(timeoutFunction(), 1)
}
I figured this output would be giving 10, yet it didn't. Then I thought it would make sense to define x afterwards.
for (var x = 0; x < 5; x++) {
var timeoutFunction = function() {
return function() {
console.log(x)
}
}
setTimeout(timeoutFunction(), 1)
}
var x = 10
This does return only 10. This implies the callbacks are all called after the for-loop is executed? And why do they only conform to the parent scope of the for-loop once the variable is initialised after execution of the for-loop? Am I missing something?
I know how make this example working with
for (var x = 0; x < 5; x++) {
var timeoutFunction = function(x) {
return function() {
console.log(x)
}
}
setTimeout(timeoutFunction(x), 1)
}
Yet, I really wonder what is missing...
Note that specifying 1 as the delay value will not actually cause the function to execute after 1 millisecond. The fastest the function could execute is roughly 9 milliseconds (and that's based on the internals of the browser), but in reality, it can't run the function until there is no other code running.
As for the unexpected output, you are experiencing this behavior because the timeoutFunction includes a reference to the x variable that is declared in a higher scope. This causes a closure to be created around the x variable, such that each time the function runs it does not get a copy of x for itself, but it is sharing the x value because it is declared in a higher scope. This is the classic side effect of closures.
There are a few ways to adjust the syntax to fix the issue...
Make a copy of x and let each function use its own copy by passing x into the function. When you pass a primitive type (boolean, number, string) a copy of the data is created and that's what is passed. This breaks the dependence on the shared x scope. Your last example does this:
for (var x = 0; x < 5; x++) {
var timeoutFunction = function(x) {
return function() {
console.log(x)
}
}
// Because you are passing x into the function, a copy of x will be made for the
// function that is returned, that copy will be independent of x and a copy will
// be made upon each loop iteration.
setTimeout(timeoutFunction(x), 1)
}
Another example that does the same thing would be needed if your timeout function wasn't returning another function (because there would be no function to pass the value to). So, this example creates an extra function:
for (var x = 0; x < 5; x++) {
// This time there is no nested function that will be returned,
function timeoutFunction(i) {
console.log(i);
}
// If we create an "Immediately Invoked Funtion Expression" (IIFE),
// we can have it pass a copy of x into the function it invokes, thus
// creating a copy that will be in a different scope than x.
(function(i){
setTimeout(function(){
timeoutFunction(i); // i is now a copy of x
}, 1);
}(x));
}
If you are working with browsers that support the ECMAScript 2015 standard, you can simply change the var x declaration in your loop to let x, so that x gets block level scope upon each iteration of the loop:
// Declaring a variable with let causes the variable to have "block-level"
// scope. In this case the block is the loop's contents and for each iteration of the
// loop. Upon each iteration, a new "x" will be created, so a different scope from
// the old "x" is what's used.
for (let x = 0; x < 5; x++) {
var timeoutFunction = function() {
return function() {
console.log(x)
}
}
setTimeout(timeoutFunction(), 1)
}
You have to create new scope for your function to make it 'remember' value from given iteration:
for (var x = 0; x < 5; x++) {
var timeoutFunction = (function(x) {
return function() {
console.log(x)
}
})(x)
setTimeout(timeoutFunction(), 1)
}
Another solution is to use ES2015 let:
for (let x = 0; x < 5; x++) {
var timeoutFunction = function() {
console.log(x)
}
setTimeout(timeoutFunction(), 1)
}
use this snippet
for(let x = 0; x < 5; x++) {
var timeoutFunction = function() {
console.log(x);
};
setTimeout(timeoutFunction, 1);
};
console.log('For loop completed');
JavaScript is not multi threaded so with your code the timeoutFunction will execute after the for loop is completed since you are using the global variable (with respect to timeoutFunction context) the final result is printed

JavaScript var keyword: redefining a variable's value inside a closure

What am I missing here? This behaves as expected:
var x = 1;
(function(){
// x === 1
})();
But,
var x = 1;
(function(){
var x = x;
// x is undefined
})();
I would think that x should be 1. It seems as though the var x = x nukes the value of x before it is assigned. Is this a bug? This doesn't seem very intuitive.
Was this behavior changed? I remember doing something like this in the past.
For reference:
var x = 1;
(function(){
var y = x;
// y === 1
})();
And:
var x = 1;
(function(){
x = x;
// x === 1
})();
var x = 1;
(function(){
var x = x;
})();
After variable hoisting becomes:
var x = 1;
(function(){
var x;
x = x;
})();
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/var
Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.
That's why sometimes in plugins you see code like
var i,j,abc, d;
//code
In you example, the code is transformed like this:
function() {
var x;
x = x;
}
The example with function arguments is different, you just change the function argument itself and the var declaration is ignored.
If a scoped variable is declared with let, it will only move up to the beginning of that scope and not of the function, so this code works:
var x = 1;
(function(){
var y = x;
{
let x = y;
console.log(x);
}
})();
As pointed out, it's a new feature, so not supported everywhere.
And finally, here:
var x = 1;
(function(){
x = x;
// x === 1
})();
You do not declare x locally, so if you edit it, it'll also edit it at global scope.
In JavaScript all variables declared in global scope or in scope of whole function where it declared. Consider example:
var x = 1;
function f()
{
console.log(x);
if (true) {
var x;
}
}
f();
This is weird programming language design but this code also prints "undefined" because of this rule.
Everytime you type var you are reassigning a new variable. When you just reference x inside the function it looks up to the assignment statement above.
function f(){
var x = x; //this tries to reassign var x to undefined.
}
what you are doing here is setting x as a global variable and then setting it to reference itself, overwriting the 1, making x => x which would be undefined.

javascript re-define a variable

I'm getting stuck somewhere (as newbies do). Is it ok to re-define a variable once it has been trimmed and tested for content?
function setarea() {
var dbasedata = document.forms[0]._dbase_name.value;
dbasedata = dbasedata.toUpperCase();
dbasedata = dbasedata.replace(/\s/g, "");
dbasedata = dbasedata.remove("UK_CONTACTS", "");
if (dbasedata != "") {
_area.value = _dbase_name.value;
}
else var dbasedata = document.forms[0]._dbase_name.value;
dbasedata = dbasedata.toUpperCase();
dbasedata = dbasedata.replace(/\s/g, "");
if (dbasedata.indexOf("UK_CONTACTS")>-1 {
var dbaseterm = "UK_CONTACTS";
else var dbaseterm = "";
}
It makes no sense to use var more than once for the same variable in the same scope. Since all var x; are hoisted to the top of the scope every additional var on that variable will be a no-op.
Assigning a new value is fine though - they are variables and not constants after all.
function x() {
var x = 123;
foo();
x = 456;
var y = 'hello';
var x = 678;
}
is actually this internally:
function x() {
var x, y; // both are === undefined
x = 123;
foo();
x = 456;
y = 'hello';
x = 678;
}
Yes, you can do this and it is legal.
It may 'work', but isn't recommended. You don't need to redeclare it.
Probably want to run your code through JSLint . There are a few tidyness/bracing issues you would want to address.

closure in JavaScript

I want the variable i to be a counter, but it is being initialized to 100 each time.
How do I call myFunction().f() directly?
function myFunction() {
var i=100;
function f() {
i=i+1;
return i;
}
return f(); // with parenthesis
};
var X = myFunction();
console.log(X);
X = myFunction();
console.log(X);
You can't call f directly. It is wrapped in a closure, the point of which is to close over all the local variable. You have to expose it to the outside of myFunction.
First:
return f; //(); // withOUT parenthesis
Then just call X, as you'll have assigned a function to it.
var X = myFunction();
X();
This example would return 101 and 102: Be sure to try it.
function myFunction() {
var i=100;
function f() {
i=i+1;
return i;
}
return f; // without any parenthesis
};
var X = myFunction();
// X is a function here
console.log(X());
// when you call it, variable i gets incremented
console.log(X());
// now you can only access i by means of calling X()
// variable i is protected by the closure
If you need to call myFunction().f() that will be a pointless kind of closure:
function myFunction() {
var i=100;
function f() {
i=i+1;
return i;
}
return {x : f}
};
var X = myFunction().x();
// X now contains 101
var X = myFunction().x();
// X still contains 101
// pointless, isn't it?

var x, y = 'foo'; Can this be accomplished?

Since it is possible to do:
var x = 'foo', y = 'foo';
Would this also be possible?
var x, y = 'foo';
I tried it, however x becomes undefined.
I know this may seem like a silly or redundant question, but if I'm curious about something, why not ask? Also you will probably wonder why I would need two variables equal to the same thing in scope. That is not the point of the question. I'm just curious.
Not sure if this is what you're asking, but if you mean "Can I assign two variables to the same literal in one line without typing the literal twice?" then the answer is yes:
var x = 10, y = x;
You need two separate statements to get the exact same semantics.
var x, y; x = y = 'foo';
// or
var x = 'foo'; var y = x;
// or
var y; var x = y = 'foo';
The solution other users are suggesting is not equivalent as it does not apply the var to y. If there is a global variable y then it will be overwritten.
// Overwrites global y
var x = y = 'foo';
It is a good practice to correctly apply var to local variables and not omit it for the sake of brevity.
You can do
var x = y = 'test'; // Edit: No, don't do this
EDIT
I just realized that this creates/overwrites y as a global variable, since y isn't immediately preceded by the var keyword. So basically, if it's in a function, you'd be saying "local variable x equals global variable y equals …". So you'll either pollute the global scope, or assign a new value to an existing global y variable. Not good.
Unfortunately, you can't do
var x = var y = 'test'; // Syntax error
So, instead, if you don't want to pollute the global scope (and you don't!), you can do
var x, y;
x = y = 'test';
In order for that to work, you will either need to initialize them separately (like your first example) or you will need to set them in a separate statement.
// This causes bugs:
var x = y = 'test';
Watch:
var y = 3;
function doSomething(){ var x = y = 'test'; }
doSomething();
console.log( y ); // test !?
On the other hand:
// this does not
var x,y; x = y = 'test';
Watch:
var y = 3;
function doSomething(){ var x,y; x = y = 'test'; }
doSomething();
console.log( y ); // 3 -- all is right with the world.
Below is my test function. The currently uncommented line in the pollute function does what you were looking for. You can try it and the other options in jsfiddle here.
var originalXValue = 'ekis';
var originalYValue = 'igriega';
var x = 'ekis';
var y = 'igriega';
function pollute()
{
// Uncomment one of the following lines to see any pollution.
// x = 'ex'; y = 'why'; // both polluted
// var x = 'ex'; y = 'why'; // y was polluted
// var x = y = 'shared-ex'; // y was polluted
var x = 'oneline', y = x; // No pollution
// var x = 'ex', y = 'ex'; // No pollution
document.write('Pollution function running with variables<br/>' +
'x: ' + x + '<br/>y: ' + y + '<br/><br/>');
}
pollute();
if (x !== originalXValue && y !== originalYValue)
{
document.write('both polluted');
}
else if (x !== originalXValue)
{
document.write('x was polluted');
}
else if (y !== originalYValue)
{
document.write('y was polluted');
}
else
{
document.write('No pollution');
}
Note that although
var x = y = 'test';
is legal javascript
In a strict context (such as this example):
function asdf() {
'use strict';
var x = y = 5;
return x * y;
}
asdf();
You will get:
ReferenceError: assignment to undeclared variable y
to have it work without error you'd need
var x, y;
x = y = 5;
You'd use var x, y = 'foo' when you want to explicitly initialize x to undefined and want to restrict the scope of x.
function foo() {
var x, y = 'value';
// ...
x = 5;
// ...
}
// Neither x nor y is visible here.
On the other hand, if you said:
function foo() {
var y = 'value';
// ...
x = 5;
// ...
}
// y is not visible here, but x is.
Hope this helps.
Source: http://www.mredkj.com/tutorials/reference_js_intro_ex.html
I would avoid being tricky. Since I only use one variable per var (and one statement per line) it's really easy to keep it simple:
var x = "hello"
var y = x
Nice, simple and no silly issues -- as discussed in the other answers and comments.
Happy coding.
I am wondering why nobody posted that yet, but you can do this
var x, y = (x = 'foo');
You can't do
var a = b = "abc";
because in that case, b will become a global variable.
You must be aware that declaring a variable without var makes it global. So, its good if you follow one by one
var a = "abc";
var b = a;

Categories

Resources