Javascript Variable


JavaScript variable declaration

JavaScript variables are used to store characters, numbers, arrays, even object resources, etc., so that we can use where we need.

Use the var keyword to declare (create) a variable:

Examples of declaring variables:

var
var x;
var number;

JavaScript variable naming convention

Variable names start with a letter (az, AZ) or an underscore _ followed by any letter or number and underscores, but not spaces. In addition, variable names are case-sensitive.

These variable names are valid as follows:

var_char
varchar
_varchar
char5
Note

For variable naming, we recommend that variable names be preferred to indicate a combination of their actual semantics, such as my_name or myName.


JavaScript variable assignment

You can assign variables to variables while declaring variables:

var my_name = "Jack"; // Text character variable, enclosed in double quotation marks 
var number = 2; // Numeric variable 

In fact, JavaScript also supports assigning variables directly to variables without having to declare variables in advance:

 my_name = "Jack";
 number = 2;

The assigned variable is automatically declared, but pre-declaration of a variable is a good programming practice.

Examples of using variables

<html>
   <head>
      <script type="text/javascript">
         var my_name = "Jack";
         var age = 25;
      alert("My name is " + my_name + ", I'm " + age + " years old");
      </script>
   </head>
</html>

The pop-up prompt box will output:

My name is Jack, I am 25 years old.

The above simple demonstration of the application of variables, as can be seen from the above example, the variable can not be written with the string in double quotation marks, but need to connect with the + link, otherwise the variable will be as ordinary string output.




Copyright 2014-2017 by DeveloperTut.com. All Rights Reserved.
TwitterGoogle+Facebook