Skip to main content

Declare JavaScript variables using var keyword

A variable is to put it simply it is a container where we can store some valuable information and access that information via the container. Think of it as a cookie jar where you store cookies and can munch them later, but it needs to be stored first right that's why we are using a jar.

There are 3 ways that we can declare a variable in javascript 

  • via keyword var
  • via keyword let
  • via keyword const

let us see how we can store the variable using var.

Var Keyword:

  • Basically var is a keyword to create a variable for storing the value.
  • Before the arrival of Ecma-Script 6, Var ruled the party of variable declaration.
  • Rather than its convenient appearance, var has some downsides to it.
  • Think of it as the content label of what is inside the cookie jar.

Example:

var pill1 = "Red Pill";
var pill2 = "Blue Pill"

console.log("Do you want the " +pill1+ " or the " +pill2+ "?")

Output:

Do you want the Red Pill or the Blue Pill?

You get the idea right?

I declared the variable and concatenated it into a print statement by passing the variable. Simple stuff!! Note: Var variables can be redeclared and reused again.

Scope Of Var:

  • The scope is the definition of where the variables can be used.
  • var is global and local scope.
  • The scope of var is global when the variable is declared outside the function where it can be accessed in the whole code.
  • Whereas when it is declared inside a function its scope is locally limited and can be used within the block of the function scope.

Example:

var x = 1;
  function foo() 
  {
    var y = 3;
    x = 2
    console.log("value of x: ", x); // output 2
    console.log("value of y: ", y); // output 3
  }
  
  foo();
  console.log("value of x: ", x); // output 2
  console.log("value of y: ", y); // output: ReferenceError: y is not defined

Here x has global scope and y has local scope. That is why you will get reference error: y is not defined when you try to access y outside the foo() function. 

Tags
Submitted by arilio666 on September 16, 2021

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.