CodesCompiler
πŸ”
HTMLCSSJavaScriptPythonSQLPHPSEOPostsBooksKids About Contact πŸš€ Get Started Free

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.

JAVASCRIPT CODE
<script>
   Money = 10;
   Name = "codescompiler";
</script>

Furthermore, you can use the var keyword to declare the variables as shown below.

JAVASCRIPT CODE
<script>
   var money;
   var name;
</script>

You can also declare multiple variables with the samevarkeyword as follows βˆ’

JAVASCRIPT CODE
<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.

JAVASCRIPT CODE
<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.

JAVASCRIPT CODE
<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.

Preview

It produces the following result βˆ’

JAVASCRIPT CODE
_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 βˆ’

Preview

This produces the following result βˆ’

JAVASCRIPT CODE
The value of num is: undefined

JavaScript 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.

Preview

This produces the following result βˆ’

JAVASCRIPT CODE
local

Example

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.

Preview

This produces the following result βˆ’

JAVASCRIPT CODE
name = codescompiler, number = 10.25

Also, 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.

Preview

This produces the following result βˆ’

JAVASCRIPT CODE
age = 10