Why can I declare a javascript var multiple times? [duplicate] - javascript

This question already has answers here:
Declaring a Javascript variable twice in same scope - Is it an issue?
(5 answers)
Closed 4 years ago.
Why am I able to declare a var multiple times? I would expect an error.
This code raises an error:
let a = true;
let a = false;
Uncaught SyntaxError: Identifier 'a' has already been declared
Why doesn't this raise an error too?
var b = true;
var b = false;
Expected: Uncaught SyntaxError: Identifier 'b' has already been declared

It's because there's variable hoisting with var, but not with let (or const for that matter).
So that means that each time you use var, it'll essentially cancel out the previous operations because to the JavaScript interpreter, your first code looks like:
var b;
b = true;
b = false;
But this doesn't work with let or const because let and const are block scoped, whereas var is function scoped.

var gets hoisted; duplicate variable names are ignored. To the interpreter, your second snippet looks like:
var b;
b = true;
b = false;
In contrast, let is not hoisted, so duplicate declarations are forbidden.

Related

Why global let variables not added to window object of browser? [duplicate]

This question already has answers here:
why don't const and let statements get defined on the window object [duplicate]
(2 answers)
Closed 3 years ago.
Consider the code below which I am running in my chrome browser console:
var x = "hello";
let foo = function(){
console.log("hi");
};
console.log(x); // hello
console.log(foo()); //hi
console.log(window.x); // hello
console.log(window.foo()); // Error
If I had used var foo =... instead of let foo = .. then this would have worked. Why ?
This is by design:
let allows you to declare variables that are limited to a scope of a block statement, or expression on which it is used, unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope. The other difference between var and let is that the latter is initialized to a value only when a parser evaluates it (see below).
Just like const the let does not create properties of the window
object when declared globally (in the top-most scope).

Why does this for loop work without passing the incrementing variable? [duplicate]

This question already has answers here:
JavaScript loop variable scope
(5 answers)
How do JavaScript closures work?
(86 answers)
Closed 3 years ago.
My code was compiled to the following, and it works, but I do not know why. The variable that references the incrementing value is not included as an argument in the for loop.
var _loop2 = function _loop2() {
var p = document.createElement('p');
p.setAttribute('class', 'location__result');
p.setAttribute('data-id', response.features[i].id);
p.setAttribute('data-center', response.features[i].center);
p.textContent = response.features[i].place_name;
p.addEventListener('click', function () {
endingInput.value = p.textContent;
endingResults.style.display = "none";
placeIconAndZoom(p, position);
});
endingResults.appendChild(p);
};
for (var i = 0, length = response.features.length; i < length; i++) {
_loop2();
}
A function (x) declared inside another function (y) has access to all variables in the scope of the x (unless they are masked by another variable of the same name).
y can also be the global or module scope rather than a function per se.
var i = "example";
function x() {
console.log(i);
}
x();
This is the classic case of why const and let were introduced in ES6
var has a function level scope. This differs to const and let in terms of scoping, where the variable defined in var can be accessible anywhere in hits function declaration.
In your case, we declare var i inside the for loop (the function level scope), and your for loop is calling your _loop2 function. Since _loop2 is part of the for loops function scope, you're able to access that variable.
This SO answer can explain it a million times better than I can:
What's the difference between using "let" and "var"?
You can fix this by either adding: use 'strict' ontop of your script file, but a much better way is to avoid using var all together (unless there is a special circumstance) and switch it to let

Let variable declared but not defined Javascript [duplicate]

This question already has answers here:
Chrome console already declared variables throw undefined reference errors for let
(2 answers)
Is there any difference between declared and defined variable
(1 answer)
Closed 3 years ago.
I have trouble understand the let declaration in javascript.
When I assign the variable to something syntactical incorrect ( and give error), it still declare the variable. But I can not change value or access it. For example:
let test = abc; //reference error: abc not defined. Expected
let test = 5; //syntax error: test already "declare"
test = 5; //reference error: test not defined
alert(test); //reference error: test not defined
So even when the code occurs error, the variable is still declared and unchangeable?
The first let test tries to create a globally scoped variable name test.
The interpreter sees the request for a new variable and creates room for it, sees the name of the variable and labels it, then sees the initial value and goes, "Wait a minute: abc is not a thing!" and ignores the assignment.
You can think of let varname = value; as actually two commands together:
let varname;
then
let varname = value;
You can test this by seeing that let the_var; in your console will instantiate a variable with an undefined value called the_var.

Javascript lambda function does not see variable from parent scope [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 7 years ago.
In the code below
var x = 1;
(function () {
console.log(x);
var x = 2;
}());
Why is it that when console.log(x), x is undefined?
Variable hoisting. The actual code is executed like this.
var x = 1;
(function() {
var x; // x = undefined
console.log(x);
x = 2;
})();
Edit: On Mr Lister's advice, a bit on variable hoisting. From MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var):
"Variable declarations, wherever they occur, are processed before any code is executed. 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."
Because of the compiler, even if you initiate a var down below the code, the compiler send it to the top, just like var x;, so it first initiate as undefined "x" before running console.log, that's why is such a good practice to initate all vars you're going to use first thing in the function, so these mistakes won't happen.

Difference between declared function with name and without name [duplicate]

This question already has answers here:
Why JavaScript function declaration (and expression)?
(5 answers)
Closed 7 years ago.
can anybody tell me whats the difference between this two examples:
//difference with this:
var x = function withName(a,b,c) {} //why i should declare a name here?
//and this
var y = function (a,b,c) {}
According to the ECMA specification, a function can be written either through declaration or through expression,
Declaration is writing function as below,
function withName(a,b,c) {
}
With declaration, it is required to write an identifier which in this case is withName
Both the example that you have given are of function expression where it is not required to write the identifier i.e. withName as you can still call this function with the variable x or y
var x = function withName(a,b,c) {}
var y = function (a,b,c) {}
However, the only difference here is that if you don't specify the identifier you are creating a anonymous funtion.
You can see this link for detailed explanation.
On this particular case, there is no difference. But in general, the fact that the function assigned to a variable has a name, makes it possible to invoke the function from inside the same function (recursion).

Categories

Resources