You don’t need to use var/let/const
to declare a variable, at least outside of strict mode, but you absolutely should use them. And really you should only be using let
and const
because they are better about scoping and errors and help you out. But like kevin said in strict mode its not going to like variables without var/let/const
and will toss an error, and can lead to buggy code with unintended consequences like the linked test is trying to show. And you don’t need var/let/const
if all you are doing is using or assigning an already declared variable.
let something;
console.log(something)//undefined
//declared the variable but did not assign value
something = 10;
console.log(something)//10
//now we are storing 10 in the variable something without using let
something = 20
//still ok because im not re declaring just assigning a new value
let somethingElse = something;
console.log(somethingElse, something)//20 20
//something did not need a let but somethingElse did
Or you can also declare them in a chain with only one let.
let something, anotherThing, somethingElse;
someOtherThing = 'oops im undeclared because im on a new line without a var/let/const'
something = 10, anotherThing = 20, somethingElse = 30;
console.log(something, anotherThing, somethingElse, someOtherThing)//10 20 30 and a long string
Use let multiple times on variables with the same name, but in different scopes.
let something = 10;//global
{
let something = 50
console.log(something)//50 in block scope
}
function func(){
let something = 20;
console.log(something)//20 in function scope
{
let something = 30
console.log(something)//30 block scoped
}
console.log(something)//20 in function scope still
}
console.log(something)//still 10 in global
But doing it twice in the same scope is a no go, and probably why you had problems with it only accepting it without let/const
.
let something = 10;
let something = 20;
//not cool because they are in the same scope and tosses an error
And why you should not use var.
var something = 10;
console.log(something)//10 global
var something = 20;
console.log(something)//20 and no error even in strict mode
{
var something = 30
console.log(something)//30 block scope
}
function func() {
var something = 50;
console.log(something)//50 in function
}
console.log(something)//30 from block scope in global