JavaScript Tutorial #7 – Variables and Datatypes

The developers can use the following primitive datatypes in their web application or Windows store application.

– String

– Boolean

– Numbers

JavaScript also support null and undefined.

The variables are like containers that can hold data . The data can be accessed by specifying the variable name. The variable in JavaScript are declared using var keyword. The developers can initialize the variable with a value either during the variable initialization or later in the program.

Below is a sample program demonstrating the usage of variables of various datatypes in JavaScript.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Ginktage.com Home Page</title>
    <script language="javascript" type="text/javascript">
        var TutorialName = "Ginktage.com - Learn JavaScript";
        var Salary  = 10000.50;
    </script>
</head>
<body>
</body>
</html>

The var keyword has a purpose . Javascript language is kind of untyped language . You don’t have to specify the type of variable during the declaration . Javascript takes care of the type automatically based on the values assigned.

The JavaScript variable can either have a Global scope or local scope . A global scoped variable is accessible everywhere in your javascript file but a local scoped variable is only visible within the function where it is defined.

Below is a sample code snippet demonstrating the Global scope and local scope variable.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Ginktage.com Home Page</title>
    <script type="text/javascript">
    var Variable1 = "Ginkatge.com"; // Global Variable
    function checkscope() {
        var Variable1 = "Google.com";  // Local Variable
    }
    </script>

</head>
<body>
</body>
</html>

There are some rules to be followed when declaring a variable in JavaScript.

  • The variable name should not have any reserved keyword of JavaScript.
  • The variable name should not start with a number . It should begin with a letter or underscore . Also note that it is case sensitive.
  • Eg : _Test1 is a valid variable name.

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

JavaScript supports different types of operators that includes Assignment Operator JavaScript supports different types if Assignment Operators like = +=...
Assume that you have an angle in degree and you wish to convert it to radians in JavaScript so that...
The JavaScript elements and statements are placed within the script tag within the HTML page. You can specify the language...