In the code below, I have declared variable i on for loop , and trying to access variable i and I can get the last updated value of i, how.
for(var i = 0; i <= 10; i++){
console.log(i);
}
console.log(i,'outside');
The var statement declares a variable in the scope of the current function, not the current block (which is what the let statement is for).
After the for loop, you are still in the same function, so the variable still exists (with whatever value it was last set to).
(NB: For the purposes of var, the code which runs outside of any function is effectively treated as being in a function of its own).
Well, you are using var, and that's exactly a var type should do!
We have var and let, let's see how they work.
when you declare your variable like this :
let something;
You only access something in that very scope (for example your own for loop), and outside the scope, you cannot have it. On the other hand, when you are using var type, like this :
var something;
You are able to use this variable outside the scope ( again like your own for loop )
Notice that we are not talking about global variables. we are just talking about scopes.
If you rather declare a global variable, just use var in the global scope.
Related
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.
When we create a variable without specifying let or var it gets added to window object in browser. For example
function change(){
val = 20;
}
change();
console.log(window.val); //20
console.log(val); //20
Here I am getting both console logs print value 20. But I do the same using let it doesn't get added to window object. I saw this answer with the explanation why this is happening.
let val = 20;
console.log(window.val); //undefined
console.log(val); //20
Now, in the below code, can someone explain, when I assign an un scoped variable inside the function why it is not getting added to window scope? Instead how it is changing the value of the variable declared with let
let value = 10;
function change(){
value = 20;
}
change();
console.log(window.value); //undefined
console.log(value); //20 why this is 20?
MDN says this about var:
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. If you re-declare a JavaScript variable, it will not lose its value.
MDN says this about let:
Variables declared by let have their scope in the block for which they are defined, as well as in any contained sub-blocks. In this way, let works very much like var. The main difference is that the scope of a var variable is the entire enclosing function:
They both end up in a scope which is then propagated to child scopes but which scope they end up in and how they go about determining that scope is different.
Note that the entirety of a <script> element does have an implicit block and this implicit block inherits window as an ancestor scope. Variable declared by var end up scoped into window while variables declared by let are scoped into this implicit block.
Declaring variables with let in the top-level of your script lets you access it inside your entire script and even outside. Inside your function, you are not assigning a value to an unscoped variable.
Even if you were to write your function as below, it would not assign to the window object as it would then be function scoped.
function change(){
var value = 20;
}
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.
var func = function () {
var i: number = 0;
if (i == 0) {
var y: number = 1;
}
document.body.innerHTML = y.toString(); // js/ts should complain me in this line
};
func(); // output: 1
As you can see, I've declared variable y inside if block. So, I think it couldn't be referenced outside the scope.
But, when I've tried to run the code, the output is 1.
Is it an issue in typescript/javascript?
Variables in Javascript are hoisted, meaning that var y is moved to the top of the function as if it were declared there.
Initialization, however is not hoisted, so if you change i to be something other than 0, the variable y will still exist, but it will have the value undefined.
This means that the function is exactly equivalent to:
var func = function () {
var i: number = 0;
var y: number;
if (i == 0) {
y = 1;
}
document.body.innerHTML = y.toString(); // js/ts should complain me in this line
};
To get the behavior you expect, you need to use let, which is a part of ECMAScript 2015 (ES6). It is block scoped, as you expect. It will also effectively work so that it is accessible only from the point of definition onwards, which is also probably as you would expect.
If you re-declare a JavaScript variable, it will not lose its value.
The second reference might pave way for a new variable syntax. Actually if you recall variable declaration is not neccessary in javascript. Simpe
y=1;
also works.
The second time when you reference y, outside if block, in my opinion, it tries a re-declaration and retains the old value.
Reference - http://www.w3schools.com/js/js_variables.asp
& http://www.w3schools.com/js/js_scope.asp
Javascript has function scope afaik. Any variable declared within a function, should be accessible from anywhere within the function. So, if you have a function checking if i==0, then you can achieve what you are trying to achieve.
This is as it is supposed to be. Javascript scopes by function, not by block. (This does make it unlike many popular languages)
Variables declared like var myVar = 10; will seep into nested functions but not the other way around. Variables declared like myVar = 10; will go global.
I couldn't find anything which suggested that typescript was any different.
Variables declared inside of an if statement are not scoped to the if statement. They're scoped to the current execution context. There's the Global execution context and then when a function is run, it creates it's own execution context. Inside of your function, you created the variables y and i. It doesn't matter that y was created inside of the if statement, because once it runs, y is created in the scope of the function. So then you do y.toString(), which can access y because it's scoped to the function not the if statement. That's why you get the output of 1. This is not an error, it's by design.
I am picking up maintenance of a project and reading code:
I see two methods of variable declaration. Can someone explain what the difference between the first and second line means?
To me, I am reading that in javascript, the var keyword is optional. in the first line, they have declared two new variables and initialized them. In the second line, they have declared two new varialbes but not have initialized them. Should I take anything more from this?
aURL = ""; msgNb = 1;
var mode, param, counter;
Unless all these variables are inside a function they're all globals, the first two are assignments which I would guess because they were previously declared, otherwise it may be shortened to
var aURL = '',
msgNb = 1,
mode,
param,
counter;
The unassigned ones have an undefined value by default.
You should always use the var keyword to keep the variable within the same function scope and not force it to become an implicit global, otherwise you could run into issues with duplicate variable naming and assignment.
If you're not using var then you're using (or creating) a variable from a "parent" scope, all the way up to being global if it doesn't find a local one at any scope.
This is not a "jquery" issue per say but rather a JavaScript issue. A variable without the "var" keyword has global scope, i.e., it is visible from all methods, objects, etc... A var is only visible within its specific scope.