What's the difference in this while loop? - javascript

What is difference between
while(condition){
var variable;
...
}
and
while(condition){(function(){
var variable;
...
})();}
Can somebody explain me defference?

In the first case the variable is accessible anywhere inside the while (and even after it). In the second case it is private and accessible only inside the auto-invoking anonymous function. So the difference is basically in the scope of the variable. The second example seems pretty convoluted without providing more context.
First example:
while(condition) {
var variable;
... // the variable is accessible here
}
// the variable is accessible here
Second example:
while(condition) {
(function() {
var variable;
... // the variable is accessible here
})();
// the variable is NOT accessible here
}
// the variable is NOT accessible here

Variables have function scope in JavaScript. So in the first loop variable is visible anywhere inside your function—the function that contains the while loop, that is.
In the second one, variable is visible only inside the anonymous function, since that's the function in which it's declared.

In the first case, variable accessible anywhere in the function that encloses the while. That's because JavaScript does not have a local scope, only function scope.
This might be undesirable in some cases and hence the second variant, which encloses the variable (and loop's body) within anonymous function.

The auto calling function basically creates a scope. Variables defined inside it will not be accessible outside the while loop.
var i = 0;
while (i++ == 0) {
var a = "hi a";
}
console.log(a); //hi a
var ii = 0;
while (ii++ == 0) {
(function() {
var b = "hi b";
})();
}
console.log(b); //Uncaught ReferenceError: b is not defined
http://jsfiddle.net/

Got closures to consider as well as Darin Dimitrov comments.

Related

Can we access a variable declared using 'var' keyword inside a block? [duplicate]

This question already has answers here:
How JS hoisting works within functions?
(4 answers)
Closed 2 months ago.
A variable is declared using 'var' keyword inside a block ( {...} ). Can we access that variable outside the block?
I searched on several websites and the answer was 'yes'. 'Yes we can access the variable' it said.
But when I executed this on a browser console it said "the variable is not defined". Any thoughts why this is so?
Here's the screenshot of the same
I expected it to give 12345.
A variable is declared using 'var' keyword inside a block ( {...} ). Can we access that variable outside the block? I searched on several websites and the answer was 'yes'.
tldr; It's more precise to say Yes, unless that block is a function body.
var scopes a variable to the nearest function.
The body of the function (excepting some arrow functions) is a block.
Not all blocks are associated with functions.
{
var inBlock = 1;
}
console.log(inBlock); // This logs 1
function aFunction() {
var inFunction = 2;
}
aFunction();
console.log(inFunction); // This triggers a reference error
You can access the variable but that doesn't necessarily mean your variable will actually have a value before passing through said block.
var will be known throughout the entire function. So if you declare var x at the end of your function (or in an if-block nested in a while in another while) and assign it there, you will be able to call it at the start of the function, but the value will be "undefined" since it hasn't been assigned a value yet at that point of the execution.
Hence why var needs careful consideration on usage to make sure you actually need said variable outside the block where you're using/initializing it.
for-loops are (in my opinion) easiest to explain this with:
for( var i = 0; i < arr.length; i++ ) {
// do something
};
The variable i here will actually be known OUTSIDE the for-loop. It will be undefined before going through the for loop and will have the value of the last iteration after the for loop. (As oppposed to using let which will make it so variable i is not known outside the for-loop)
Variables declared with var has global and function scope but does not have block scope. Which means these variables are only accessible inside a function or globally.
// if we try to access it from function scope, it is not accessible
function greeting() {
var sayHi = "Hello"
return sayHi
}
console.log(sayHi) // sayHi is undefined. Because it has function scope
// if we try to access it from block scope, it is accessible.
if (1 < 2) {
var sayBye = "Bye"
}
console.log(sayBye) // prints 'Bye', because it has no block scope
After execution of the function, the variable will no longer be available and it will be referencing the globally scope which don't have your variable.

Not understanding the concept of local and global variables

Ok so just a quick one... I REAAAAAALLLLY am not understanding scope at all. Do some reason whenever I put a variable inside of a function it's undefined. It seems the only way it works it to declare it OUTSIDE of a function. So what gives? Am I simply misunderstanding the concept of local and global variables? Because it seems global variables are the only ones that work...
Edit:
Simple example...
let a = 'something';
function myFunction() {
// Code block
};
This works 👆
But the following gives me undefined variables:
function myFunction() {
let a = 'something';
// Code block
};
First lets take a look at the differences between local and global variables.
LOCAL VARIABLES - Any variable defined inside of a function or loop. If the variable is defined in a certain function/loop, it can only be accessed in that function/loop.
For example:
function number() {
let a = 0;
// Can access a here.
}
// Cannot access a here.
GLOBAL VARIABLES - Any variable that is not defined inside of any function or loop. These variables can be accessed anywhere.
For example:
let b = 0;
function number() {
// b can be accessed here.
}
// b can be accessed here.
The scope of a variable is where it can be accessed in. For ex, a scope of a local variable that is defined inside of function number() is the number() function since it can only be accessed there.
One more quick thing (Credit to Mikael Lennholm) var doesn't scope a variable to a loop (or any non-function statement block), it only scopes it to the current function. To scope a variable to any statement block you have to use let/const
Now let's look at your examples:
Here is the first example:
let a = 'something';
myFunction();
function myFunction() {
console.log(a);
};
That works fine, and that's what you said.
Here is the second example you said doesn't work:
function myFunction() {
let a = 'something';
console.log(a);
};
myFunction();
But, if you click the run button, you'll actually see it does work, it does get logged. If you after this go and check in the console what the variable a is of course it will be undefined, since a can be only accessed in the myFunction() function, and the console is not in that function.
You said that the script doesn't work, it's most probably because of something else (if it was because of this there would be an error in the console). You can try posting the website here and I can help you.
Hope this helped you :)
Global variables are variables that you have access to them anywhere in your codes.
Local variables are limited to their scopes like a function, module, class and etc.
if you define a local variable it can be accessible in the nested level like closures.
if you define a global variable and you define the same name as local variable , the local overwrite the global, then be careful.

Javascript Global vs Local Scope

I'm currently trying to understand Javascript's interesting take on global vs local scope.
My question is that why would the following returns undefined?
var a = 100;
function local() {
if (false) {
var a = 50;
}
alert(a);
}
Additionally, I ran this:
var a = 100;
function local() {
alert(a);
}
The result was a resounding: 100.
Is there some way that we can specify when we want the variable to be taken from the global scope, like a PHP global keyword, that we can use with Javascript?
Because of hoisting.
It means every variable declaration get's popped to the top of the function so the actual code that runs is:
var a = 100;
function local(){
var a;
if (false)
a = 50;
alert(a);
}
It has very little to do with global VS. local, you simply hid the outer a variable with the inner a variable.
Is there some way that we can specify when we want the variable to be taken from the global scope, like a PHP global keyword, that we can use with Javascript?
No
Regarding the question in the comment "In the case that I want to revert to using a global variable in case the if condition fails (which I intentionally did), how can I do so? ":
You can use eval:
var a = 100;
function local() {
if (false) {
eval('var a = 50;');
}
alert(a);
}
Live DEMO
But you should not!
JavaScript has function scope, not block scope (as many other programming languages). That means regardless where the var statement occurs (in your case, an if-branch that is not even executed), it declares a variable a in the function's local scope. It shadows the global a variable, but since it has no value assigned it returns undefined.
Is there some way that we can specify when we want the variable to be taken from the global scope, like a PHP global keyword, that we can use with Javascript?
You can access the variable as a property of the global object (window in browser environments):
var a = 100; // global
function loc() {
var a = 50;
alert(window.a); // 100
alert(a); // 50
}
loc();
However, you will hardly use this. Global variables are to be avoided in general, and in case of name clashes you should simply rename your local variable (for readability and maintainability at least).
I know that if a variable is in defined inside a function using var, then it will have Local Scope.
I also know that any function has easy access to Global variable.
When I tested following in Console of Browser, first output was undefined.
It means that function nwf() was unable to access Global variable nw1
This is due to reference error which highlights importance of Strict Mode
To avoid such scenario, never re-declare and/or initialize any variable with same name inside and outside any function, just unlike following:-
var nw1 = 1; // var creates global scope outside function
function nwf() {
alert(nw1);
var nw1 = 2; // var creates LOCAL scope inside function
alert(nw1);
};
nwf();

Trying to figure out how scope works

I'm trying to learn JS on codeacademy and I can't understand/get past this thing. Can someone please provide an answer and also an explanation of why is it so? Would deeply appreciate.
// This function tries to set foo to be the
// value specified.
function setFoo(val) {
// foo is declared in a function. It is not
// accessible outside of the function.
var foo = val;
}
setFoo(10);
// Now that we are outside the function, foo is
// not defined and the program will crash! Fix this
// by moving the declaration of foo outside of the
// function. Make sure that setFoo will still update
// the value of foo.
alert(foo);
You can see scope as a term meaning what variables you can reach at a specific "level" in the code. In JavaScript, these "levels" are defined by functions. Each function introduces a new level.
For example, take this sample code:
var a;
// you can access a at this level
function function1() {
var b;
// you can access a, b at this level
function function2() {
var c;
// you can access a, b, c at this level
}
}
So in your case, you should declare var foo; outside the function, preferably above it. Then you can set it inside setFoo with foo = val;. foo then refers to the one you declared in the level above setFoo.
foo is accessible both in setFoo and in the alert call that way; compare it with the above sample code (function1 is setFoo, a is foo and the alert call is in the top-most level. function2, b and c are not used in your case.).
// Create globale variable
// (You should not use globale variables!)
var foo;
// set value
function setFoo(val) {
foo = val;
}
setFoo(10);
// show value
alert(foo);
Just declare foo outside any function then it will be global:
var foo = null;
function setFoo(val) {
foo = val;
}
setFoo(10);
alert(foo);
Try it !
When you declare a variable in Javascript it is only visible to code that is in the same function as it is declared, or a function inernal to that function. Because foo is originally declared in the SetFoo function nothing outside of SetFoo is able to see it, so the call to alert fails as foo does not exist in the gloabl scope.
As the comments suggest, moving the declaration of foo out of the function and into the global scope (which you can think of as a catch-all function that contains everything) would allow you to use foo when calling alert.
var foo;
function setFoo(val) {
foo = val;
}
setFoo(10);
alert(foo); // No longer crashes
Every function in Javascript has it's own scope. That means that every variable you define there with the var keyword, will only be available within that function. That means that when you call setFoo(10), you create the variable foo, give it a value of five, after which it is immediately destroyed because it went out of scope.
There are multiple ways to solve this problem. The first would be to remove the var keyword. This would put foo in the global scope, which means that it's available everywhere. However, this is discouraged, you want to keep the global scope as uncluttered as possible, so that if you have javascript code provided by multiple people on the same page, they can't overwrite other people's variables. Another way to do it would be this:
function setFoo(val){
var foo = val;
alertfoo = function(){
alert(foo)
}
}
In this example, the only thing you're putting in the global scope is the alertfoo function, because you want that to be available everywhere. The alertfoo function is defined inside the setFoo function, this means that although foo should have gone out of scope after setfoo has been executed, it is kept in memory, because alertfoo has access to it.
This makes for some nice tricks. For example, let's say you're making a javascript library that will be included on other people's pages, you'll want to create a scope inside of which you can define variables, without polluting the global scope. The most common way to do this, is by declairing a self-executing function. This is a function which is executed immediately after being defined, it looks like this:
(function(){
//set variables you want to be global in your own code
var mainpage = document.getElementById('main');
//define functions you want to make available to other people in a way that puts them in the global scope
setMainElement = function(newmain){mainpage = newmain;}
})();
You can make this even better by making only one object global, and provide your interfae through the methods of that object, this way, you create a namespace with all the functions that your library contains. The next example uses an object literal to do this. In javascript, you can create an object by putting key/value pairs petween curly braces. the key/value pairs are properties of the object. for example:
(function(){
var privatevar = 10,otherprivate=20;
publicInterface = {
'addToPrivate': function(x){privatevar+=x;},
'getPrivate': function(){return private}
};
})();
Original code:
function setFoo(val) {
var foo = val;
}
setFoo(10);
alert(foo); // Crash!
Their advice to fix the crash:
Fix this by moving the declaration of foo outside of the function
I'm guessing you're confused as to what they mean by "outside of the function".
Try this edited code:
var foo = 5; // "var" declares the variable to be in this outer scope
function setFoo(val) {
foo = val; // but we can still access it in this inner scope...
}
setFoo(10);
alert(foo); // Displays a dialog box that says "10"
Variables defined in the function is valid only in the function
function setFoo(val) {
foo = val;
}
In JavaScript, new scopes are only created by functions

javascript: creating a local scope of a global variable undefines it before it is set

I do not understand this behavior:
var a = 1;
console.log('a is undefined1:', a == undefined);
var a;
//iterate selected jQuery elements:
jQuery.each(this, function(index, htmlElement) {
console.log('a is undefined2:', a == undefined);
var a;
Returns:
a is undefined1: false
a is undefined2: true
If the last line (var a;) is commented out, this is returned:
a is undefined1: false
a is undefined2: false
I would expect always the latter output. What do I not know?
Thanks so much!
Putting var a inside a function creates a different a variable that is scoped to that function.
Since you don't assign a value to it, it is undefined.
When you comment it out, you are testing the outer a which has the value of 1.
Variables are hoisted. It doesn't matter where in a function you use var foo, the foo for that function still applies to the whole function.
Declaring variable within function using var makes local copy (new variable) with scope on the whole function - it does not matter whether it is used before it is declared.
Never declare variables without var.
If you want to access the golobal variable and you have local variable of the same name, you can access the global foo variable using window.foo

Categories

Resources