In most languages I would write
declare var1 = undefined
if (condition) {
var1 = value1
}
but in javascript, it seems its allowed to write
if (condition) {
let var1 = value1
} else {
var1 = value2
}
Am I misguided on this?
In most languages I would write
declare var1 = undefined
if (condition) {
var1 = value1
}
but in javascript, it seems its allowed to write
if (condition) {
let var1 = value1
} else {
var1 = value2
}
Am I misguided on this?
Yes you can when you use var.
Not when you use let and const because they are block scoped.
Example for var
if (true) {
var var1 = 1
}
console.log(var1);
Example using let
if (true) {
let var1 = 1;
}
console.log(var1)
P.S :- In JS world using var is considered as bad coding practice.You should avoid using it until there is something you can't do with let and const.
In JavaScript, a variable can be declared after it has been used. In other words: a variable can be used before it has been declared. Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).
So:
x = 5
// ... some other code ...
var x
will be translated to:
var x;
x = 5
// ... some other code
But it would only work this way if you used var to declare variable. If you use const or let it wouldn't work, because variables and constants declared with let or const are not hoisted.
Declaring variables using let or const is preferred way in modern javascript.
No, it's completely bad idea. If you want to use JavaScript variable both inside and outside of the if statement you can do it by declaring it outside the if statement.
let var1 = value1;
if (condition) {
var1 = value1
} else {
var1 = value2
}
This way you will only create a block scoped variable. But, if you use var var1 = value1 then it will declare globally scoped variable which is not what you wanted most probably.
To learn more about how variables works in javascript, you can checkout this awesome article. Happy coding :)
You can do this using let, but NOT in Strict Mode!
'use strict';
var condition = false;
if (condition) {
let var1 = 42;
console.log(var1);
} else {
var1 = 43;
console.log(var1);
}
// ReferenceError: var1 is not defined
It's recommended to declare var1 outside the scope of if statement:
'use strict';
var condition = false;
var var1 = 42;
if (condition) {
console.log(var1);
} else {
var1 = 43;
console.log(var1);
}
// => 43