JavaScript Variables

JavaScript Variables

Gist about variables and their scope in JavaScript

What is JavaScript Variable?

Variables means anything that can vary and holds the data value and we can mutate it anytime. A variable must have a unique name. Javascript includes variables that hold the data value and it can be changed on runtime as javascript is dynamic language. We have var, const, and let keyword to declare a variables.

Example:

const name='vignesh'
let age=25;
var city='bengaluru'

console.log(name) //vignesh
console.log(age) //25
console.log(city)//bengaluru

Rules for Naming Variables

  • The first character must be a letter or an underscore (_). We can't use a number as the first character.

  • The rest of the variable name can include any letter, any number, or the underscore. We can't use any other characters, including spaces, symbols, and punctuation marks.

  • JavaScript variables are case sensitive, for example aa, AA and aA are different variables.

Types of variables in JavaScript :

  • Local Variable

local variables are only visible in the function in which we define them. They will not have any significance outside that function.

Example:

function details()
{
  const name='vignesh'; //local var
  let ages=25;          //local var
  console.log(`Name: ${name} age:${ages}`);//Name: vignesh age:25 
}

details();
  • Global variable

Global variables have global scope i.e. they can be defined anywhere in your JavaScript code.

Example:

const name='vignesh';    //Global var
let ages=25;         //Global var

function details()
{
    console.log(`Name: ${name} age:${ages}`);   //Name: vignesh age:25 
}
console.log(`Name: ${name} age:${ages}`);      //Name: vignesh age:25 
details();