JavaScript - Variables

Javascript variables are basically the name of the value and it is used to store the data such as a string of text, numbers, boolean, etc. These stored data can be set, updated, retrieved.

How To Create Javascript Variable

Javascript variable can be created using var keyword followed by name of the variable.

      var variableName;

To assign value inside the variable,use assignment operator(=) like var varName = value.

General Syntax
      var variableName;   //variable initialization
var variableName = value;//assigning value to the variable
Try it now

Source Code

            var FruitName = "Mango";
var Cost = 25;
var isAvailable = true;          
Try it now

Variable Value :Undefined

A javascript variable that is declared without a value will have an undefined value.

Source Code

            var fruitName;
Try it now

Declaring Multiple Variables at Once

Javascript provides the flexibility to declare and set a variable value in a single statement. Each variable should be separated by a comma.

Declaring multiple Variables

General Syntax
      var fruit = "mango", cost = 50, isAvailable = true;
Try it now

Source Code

            var fruit = "mango",
cost = 50,
isAvailable = true;          
Try it now

Javascript Variables Scope

In javascript,variable can be declared either local scope or global scope.Followings are the javascript variable scope:

  • Local Scope
  • Global Scope

Local Variables

A local variable is declared inside the function and it can only access inside the function. It can not be accessed outside of the function.

Source Code

document.getElementById("result").innerHTML =
"Today, I would like to learn:" + learningResources;
function learningResource() {
var learningResources = "Web Designing";
Try it now

Global Variables

A global variable is declared outside of the function and it can be accessed anywhere in the javascript code, even inside the function.

Source Code

            var fruit = "Mango "; // global variable
function userTest() {
  var msg = " is the one of the best fruit.";
  alert(fruit + msg); //can access global and local variable
document.write(fruit); //can access global variable
document.write(msg); //error: can't access local variable          
Try it now

Web Tutorials

Javascript Variables
Html Tutorial HTML
Javascript Tutorial JAVASCRIPT
Css Tutorial CSS
Bootstrap 5 Tutorial BOOTSTRAP 5
Bootstrap 4 Tutorial BOOTSTRAP 4