JavaScript - Variables
JavaScript - Variables
JavaScript Variables
JavaScript variables are used to store data that can be changed later on. These variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. In JavaScript, you can declare the variables in 4 ways β
- Without using any keywords.
- Using the βvarβ keyword.
- Using the βletβ keyword.
- Using the βconstβ keyword.
Theletandconstkeywords were introduced to JavaScript in 2015 (ES6). Prior to ES6, onlyvarkeyword was used to declare the variable in JavaScript. In this section, we will discuss βvarβ keyword. We will cover the βletβ and βconstβ keywords in subsequent chapters.
Variable Declaration in JavaScript
You can follow the syntax below to declare the variables without using any keywords.
<script>
Money = 10;
Name = "codescompiler";
</script>Furthermore, you can use the var keyword to declare the variables as shown below.
<script>
var money;
var name;
</script>You can also declare multiple variables with the samevarkeyword as follows β
<script>
var money, name;
</script>Variable Initialization using the Assignment Operator
Storing a value in a variable is calledvariable initialization. You can initialize a variable at the time of creation or at a later point in time when you need that variable.
For instance, you might create a variable namedmoneyand assign the value 2000.50 to it later. For another variable, you can assign a value at the time of initialization as follows.
<script>
var name = "Ali";
var money;
money = 2000.50;
</script>Note:Use thevarkeyword only for declaration or initialization, once for the life of any variable name in a document. You should not re-declare same variable twice.
JavaScript isuntyped language. This means that a JavaScript variable can hold a value of any data type. Unlike many other languages, you donβt have to tell JavaScript during variable declaration what type of value the variable will hold.
The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically.
JavaScript Data Types
In JavaScript, the variable can hold the value of the dynamic data type. For example, you can store the value of number, string, boolean, object, etc. data type values in JavaScript variables.
<script>
var num = 765; // Number
var str = "Welcome"; // String
var bool = false; // Boolean
</script>You will learn data types in detail inJavaScript Data Typeschapter.
JavaScript Variable Names (Identifiers)
In JavaScript, a unique character sequence is used to name the variables called identifiers.
Here are some rules for the naming of the identifiers in JavaScript β
- Valid charactersβ In JavaScript, a variable name can contain digits, alphabetical characters, and special characters like underscore (_) and dollar sign ($). JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example,123testis an invalid variable name but_123testis a valid one.
- Case sensitivityβ Variable names are case sensitive. It meansNameandnameare different identifiers.
- Unicode supportβ The identifiers can also contain the Unicode. So, developers may define variables in any language.
- Reserve keywordsβ You should not use any of the JavaScript reserved keywords as a variable name. For example,breakorbooleanvariable names are not valid. Here, we have given a full list of theJavaScript revered keywords.
JavaScript Dollar Sign ($) and Under Score (_)
You can use the $ and _ to define the variables in JavaScript, as the JavaScript engine considers it a valid character.
Example (Demonstrating the identifiers)
In this example, we have defined the variables using thevarkeyword. The first variable name starts with the underscore, and the second variable name starts with the dollar sign.
Programmers can uncomment the third variable declaration to check the error generated by JavaScript when we start any identifier with the digit.
It produces the following result β
_abc Hi!
$abc = Hello!Undefined Variable Value in JavaScript
When you donβt initialize the variable after declaring, it contains the undefined value. However, you can also assign the undefined value to the variable.
Example
Letβs look at the example below β
This produces the following result β
The value of num is: undefinedJavaScript Variable Scope
The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two scopes.
- Global Variablesβ A global variable has global scope which means it can be defined anywhere in your JavaScript code.
- Local Variablesβ A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. Take a look into the following example.
Example
In the example below, we have defined the variable named myVar outside the function and initialized it with the βglobalβ value. Also, we have defined the variable with the same identifier inside thecheckscope()function and initialized it with the βlocalβ value.
We print the myVar variableβs value inside the function. So, the local variable takes preference over the global variable and prints the βlocalβ in the output.
This produces the following result β
localExample
In the example below, we have defined the variables without using thevarkeyword. Thenamevariable contains the value of the string type, and thenumbervariable contains the value of the float data type.
When we define the variables without using any keyword, JavaScript considers them global variables and can use them anywhere inside the code.
This produces the following result β
name = codescompiler, number = 10.25Also, the identifier doesnβt lose the previous value if we declare the variable using the var keyword with the value and re-declare the same identifier without initialization. Lets understand it via the example below.
Example
In the example below, we have declared theagevariable and initialized it with 10. Again, we have declared theagevariable but havent initialized it.
Still, it prints 10 in the output because it doesnt lose the previous initializations value. However, if we update the value of the age variable, it successfully updates it.
This produces the following result β
age = 10