Variables In JavaScript

Introduction

This article will cover the basic concepts of JavaScript, the most important being variables and data types.

Variable in JavaScript

A Variable is an identifier or a name used to refer to a value. It is media that stores the information referenced and manipulated in a computer program. Using the key of a variable in JavaScript “var”, the extension is important (.js).

Syntax

var <variable-name>;
var <variable-name> = <value>;

Note. In the example, the number 10 is assigned to “a”. Use only the special characters (__) underscore and ($) symbol, don't use other special characters like @, *, %, or  #. JavaScript is case-sensitive.

In this example, the variable name ‘a’ is uppercase.

var a=10;
document. Write(A); //varible name is lowercase

Error 

Example 1

<!DOCTYPE html>
<html>
  <head>
    <title>Java Script</title>
  </head>
  <body>
    <h4>Variables in JavaScript</h4>
    <script>
      var a = "30";
      document.write(a);
    </script>
  </body>
</html>

Output

Example 2

<!DOCTYPE html>
<html>
  <head>
    <title>Java Script</title>
  </head>
  <body>
    <h4>Variables in JavaScript</h4>
    <script>
      var name = "vijay";
      document.write(name);
    </script>
  </body>
</html>

Output

There are two types of Variables

  1. Local Variable
  2. Global Variable

JavaScript Local Variable

The local variable is a variable in which a variable can be declared within the function, and it can be used only inside that function. So, variables with the same name can be used in different functions.

Example

//local Variable

<!DOCTYPE html>
<html>
  <head>
    <title>Java Script</title>
  </head>
  <body>
    <h4>JavaScript</h4>
    <script>
      // local variable
      function article() {
        var name = "Variables in JavaScript"; //inside the function declare a variable
        document.write(name);
      }
      article();
    </script>
  </body>
</html>

Output

JavaScript Global Variable

The global variable is a variable in which variables can be defined outside the function. So, variables with the same name cannot be used in different functions.

Example

//Global Variable

<!DOCTYPE html>
<html>
  <head>
    <title>Java Script</title>
  </head>
  <body>
    <h4>JavaScript</h4>
    <script>
      //global variable
      var articlename = "variables in JavaScript"; //outside the function declare a variable
      function article() {
        document.write(articlename);
      }
      article();
    </script>
  </body>
</html>

Output

Summary

In this article, we looked at how to declare a variable in JavaScript. In my next article, we will learn the data types in JavaScript. I hope this article is very useful for you.

Reference

Thanks for reading.