DEV Community


Var in JavaScript

Muhammad Uzair
ReactJs | React-Native | JavaScript | Nodejs | MongoDB | UserInterface | Python
・2 min read

Before the advent of ES6, var declarations ruled. There are issues associated with variables declared with var though. That is why it was necessary for new ways to declare variables to emerge,First however, let us get the chance to comprehend var more before we talk about those issues.

Scope of Var

Scope basically implies where these variables are available for use. var declarations are globally scoped or function/locally scoped.

The scope is global when a var variable is declared outside a function. This means that any variable that is declared with var outside a function block is available for use in the whole window.

var is function scoped when it is declared within a function. This means that it is available and can be accessed only within that function.


var text= "hey hi";

function newFunction() {
    var hello = "hello";

We'll get an error which is as a result of hello not being available outside the function.

*var variables can be re-declared and updated *
Means you can re-assign the values created by var

console.log (text);
var text= "say hello"

Hoisting of var
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. This means that if we do this:

console.log (text);
var text= "say hello"

it is interpreted as this

var text;
console.log(text); //textis undefined
greeter = "say hello"

Because hoisting takes all the declarations at top but if you initialize it later without var key word than it will not moved to the top.

Dis-Advantages of Var

var text= "hey hi";
var conter = 6;

if (counter> 4) {
    var text= "hello world"; 
console.log(text) //"hello world"

Since counter>4 returns true, text is redefined with hello world it is not a problem yet, it will be complex when you didn't know that var text has already been declared/defined.If you have used text in other parts of your code, you may be shocked at the outputyou may get. This will likely cause a lot of bugs in your code. This is the reason for introducilet and const are necessary.

Discussion (0)

Forem Open with the Forem app