Before ES6, all variables in JavaScript were declared with the var keyword. This keyword causes our variables to have a function scope.
Lets understand this better with the following code snippet:
function SayName(){
var name = "Tega";
}
console.log(name)//Undefined
The console prints out undefined
because the variable name
inside the SayName
function is not visible outside the SayName
function.
The behaviour is quite different in another block that is not a function block. For example, see what happens in an if block.
if(true){
var name = "Tega";
}
console.log(name)//Tega
The console prints Tega
.
Considering the results from the two examples, it is evident that variables declared with the var
keyword have a local scope only when they are found within a function block.
It's a bad behaviour
This is a bad behaviour that has caused a lot of frustration amongst JavaScript programmers. Prior to ES6, JavaScript had function scope, but block scoping is more common in most programming languages. With ES6, let
and const
keywords were introduced to allow us to declare variables that are block scoped which is a safe behaviour.
Thank you for reading!
Happy Coding!❤
Top comments (0)