Coming from a C#/Java background, it is almost habit to use “var” for every variable instantiation. In JavaScript world, this is a huge no-no and the JS community (to a certain extent) frowns upon the use of “var”. This blog will teach you practical tips and educate you on the difference so that you look cool in front of JS developers!
To understand the difference, you must learn the subtle differences of scope that JS employs.
What is Scope?
Scope determines the accessibility or visibility of variables in JavaScript. There are three types of scope in JS are Global, Function, and Block:
- Global Scope
- Function Scope
- Block Scope
When you first being coding JS (and haven’t started on functions), this is likely what scope your code resides in. Essentially, any code outside a function will likely reside in Global Scope.
An easy way to understand scope is to just remember “global” scope can be accessed anywhere, while function and block scope cannot. Function scope simply means, code within a function cannot be “seen” outside. Block scope is any other code that is within {} brackets like if statements and while loops.
The Var Keyword
var name = "teddy";
console.log(name);
function getName() {
console.log(name); //THIS WORKS
}
getColour();
if(true) {
var greeting = 'hello';
console.log(greeting);
}
console.log(greeting);