Variables are memory locations where data may be stored. Data type define the type of data that a vriable may store. Variables are named containers which are used to contain and refer to saved data inside them which may be called by only referring to the name assigned.
JavaScript support three primitive data types:
Along with these primitive data types, Java Script also supports two trivial data types, null and undefined, both of these are used to define and represent only a single value.
Variables are declared by using the key word of var as shown in the example:
var x;
var name;
Variable initialization is a way of assigning data to a variable. You can initialize the variable with the data when you are creating the variable or later in the program whenever the need arises for handling the data and assigning it to a variable. Variable initialization is explained below by using an example:
var player_name = "Evans";
var money = 2000;
JavaScript variables can hold the value of any datatype without providing any specification of which datatype the variable will hold at the time of its declaration making it an untyped language. JavaScript is able to infer datatypes during run time.
Java Script Variable Scope
The scope of a variable is the area of your program wherein it is characterized. JavaScript variables have only two scopes explained below
The precedence of the local and global variable varies according to the code context. The local variable has always a precedence over the global variable within the body of a function if both variables have the same name.
var test_var = "I am global"; // Global variable
function scoped() {
var test_var = "I am local"; // Local variable
document.write(local_var);
}
The output of this whole code will be:
I am local
Naming Convention for the JavaScript Variables
break case catch class const continue
debugger default delete do else export
extends finally for function if import
in instanceof new return super switch
this throw try typeof var void while with yield