Always declare local variables - javascript

W3School saying that All variables used in a function should be declared as local variables.
Local variables must be declared with the var keyword, otherwise they will become global variables.
function multiply () {
var x = 10;
var y = 20;
return x * y;
};
function multiply () {
let x = 10;
let y = 20;
return x * y;
};
But let variables in 2nd function are still local variables.
How local variables declared with other than var keyword could become global variables?

How local variables declared with other than var keyword could become global variables?
They cannot. Every variable declared with var, let or const will be scoped to the current (function / block) scope. W3Schools is just a bit outdated.

Let and const came into picture after es6. They are mainly used to add block scope to a variable. Using the Javascript MDN will give you a clear picture about how exactly both these keywords work.
"Local variables must be declared with the var keyword, otherwise they will become global variables". This statement is no longer correct, your source of information might be outdated.
https://hackernoon.com/js-var-let-or-const-67e51dbb716f - this article might help.

Related

Why global let declarations get overridden by unscoped variables?

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;
}

How should I access to overwritten variable in overwritten function?

I'm not able to understand of how should I get to particular variable a in next code:
var a = 1;
console.log(a);
function local() {
var a = 2;
console.log(a);
function local() {
var a = 3;
console.log(a);
function local() {
var a = 4;
console.log(a)
}
local();
}
local();
}
local();
I know this is artificial example but I can't go to sleep without the answer :)
So how should I get a particular variable a from any of overwritten function?
Thanks.
When you declare a variable in the local scope with the same name as a variable in a higher scope, the new declaration hides the higher scoped variable and there is NO way to access that higher scoped variable from the local scope.
This is just how Javascript is designed. There isn't some magic way around it. If you want access to the higher scoped variable, then don't declare a local variable with the same name. Pick a different name.
If the top-most variable is in the global scope, then you might be able to access that variable with a global prefix such as window.a or global.a (depending upon which environment you're running in). But, the intermediate variables that are not in the global scope are not accessible.
you can access global variables by the window object like this
var aa=11;
function my_func(){
var aa=22;
alert("local: "+aa+" global: "+window.aa);
}
but there is no way of accessing the local variables outside the function, as they do not really exist out there!

Access variable in if block

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.

Is the Javascript variable declaration shorthand making variables global or local?

I understand that the variables in the following function will only be available in this function;
function(){
var x;
var y;
var z = 3;
});
But I don't know about the following in shorthand. What is their scope? (Y and Z)
function(){
var x, y, z=3;
});
And If there's something I can go read somewhere about this shorthand please provide a link.
Thanks.
Both represent exactly the same thing, and thus the variables carry same scope. They will be defined everywhere inside this function.
You can read more about it here.
The variables declared without var keyword are made global variable.
Don't know the reason behind this. But I have tested this.
Also, in your 2nd example as well, the variables will be local to that function only as you have used var for 1st variable and it is continued by using comma.
Try this example
var a=10:
Function test()
{c=11; var b=12; a=0;}
console.log(a);
test();
console.log(a);
console.log(b);
console.log(c);
In javascripts,
If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.
In your case you are declaring then assigning value (var x,y,z = 3).
They all will be in local scope only.
For learning more about scope you can go through W3School.

Use strict and let not working as expected in Javascript

I declared variables twice in my function while I am using "use strict". I know this function has global scope and it's variables are also treated as global with window scope i.e window.car
But It should not re-declare speed and capacity variables inside if statement with let data type. ( "let" Declares a block scope local variable, optionally initializing it to a value. )
(function car() {
"use strict";
var speed = 100;
const capacity = '1000CC';
if(speed) {
let speed = 200;
let capacity = '5000CC';
console.log(speed,capacity);
}
console.log(speed,capacity);
})();
Please let me know what I am missing here.
"let" Declares a block scope local variable. But still global variable can be modified in local scope.
(function car() {
"use strict";
var speed = 100;
const capacity = '1000CC';
if(speed) {
let speed = 200;
let capacity = '5000CC';
console.log(speed,capacity);//inside local it is modified to 200
}
console.log(speed,capacity);//outside scope it pull from global scope to 100
})();
You can re-declare / modify the global variables even in strict mode.
You'll only get error when you re-declare the same variable in same scope. Look at the following example taken from MDN
if (x) {
let foo;
let foo; // TypeError thrown.
}
However, function bodies do not have this limitation! (But it throws an error in ES6 though as commented by #Bergi, may be there's wrong documentation in MDN)
function do_something() {
let foo;
let foo; // This works fine.
}
The variable speed declared with var and the speed declared with let are two different variables.
Inside the body of the if statement, the local declaration of speed hides the variable declared in the outer block - it doesn't redeclare it.

Categories

Resources