A common interview question explained
If var is used within in a function, then it is only available within the that function. If it is not used within a function it is a global variable and will be recognized anywhere within your code. Var is also hoisted which means that it does not matter where you define that variable within your code on the global scope it will still be recognized and available for use in code before your actual declaration. With var as well, you can declare it and not actually assign it a value, unless you want to later. Using var in the global scope will bind it to the “this” keyword, referring to the window object.
}printCoins()var numberOfCoins;numberOfCoins = 5
In the example above. We are executing printCoins() but numberOfCoins is declared and then assigned a value AFTER the execution. In this case printCoins() will still print, “5”.
Let and const were introduced in ES6, because with var, there are too many instances that are prone to error. Var can be easily reassigned a value anywhere within your code and became increasingly difficult to debug. Let solves this by only having the variable available within the block of code within which it is defined. Let is not hoisted and you must assign it a value upon its declaration.
Const is similar to let. The only difference is you cannot reassign any variable declared with const. This assures that you are not accidentally reassigning its value if it is a variable that you want to remain constant throughout your program. However, you may edit and built upon variables declared with const, such as when you are manipulating an array with .push() or .shift() or inserting key-values within an object.
const numberArray = [1, 2, 3, 4, 5]const numberArray = [5, 4, 3, 2, 1]
Above, this will not work. It will throw and error. However :
const numberArray = [1, 2, 3, 4, 5]numberArray.push(numberArray + 1)console.log(numberArray)
numberArray = [1, 2, 3, 4, 5, 6]