JavaScript JS Tutorial JS Objects JS Functions JS Classes JS Async JS HTML DOM JS Browser BOM JS Web APIs JS AJAX JS JSON JS vs jQuery JS Graphics



JS Variables

JavaScript (JS) is a programming language that is used to create interactive and dynamic web pages. One of the fundamental concepts of JS is variables. Variables are used to store data values that can be used throughout the program. In this tutorial, we will discuss JS variables in detail.

Brief Explanation of JS Variables

Variables in JS are containers that hold data values. These values can be of different types such as numbers, strings, booleans, arrays, objects, etc. Variables are declared using the var keyword followed by the variable name. For example:

<script>
    var name = "John";
    var age = 25;
</script>

In the above example, we have declared two variables, name and age, and assigned them values "John" and 25 respectively. We can also declare variables without assigning them a value. For example:

<script>
    var x;
</script>

In the above example, we have declared a variable x without assigning it a value. The value of x will be undefined.

Variables in JS are dynamically typed, which means that the data type of a variable can change during runtime. For example:

<script>
    var x = 5;
    x = "John";
</script>

In the above example, we have assigned the value 5 to the variable x. Later, we have assigned the string "John" to the same variable. Now, the data type of x is a string.

Code Examples

Let's look at some code examples to understand JS variables better:

Example 1: Declaring and Assigning Variables

<script>
    var name = "John";
    var age = 25;
    var isStudent = true;
</script>

In the above example, we have declared three variables, name, age, and isStudent, and assigned them values "John", 25, and true respectively.

Example 2: Changing Variable Values

<script>
    var x = 5;
    x = 10;
    var y = "Hello";
    y = "World";
</script>

In the above example, we have declared two variables, x and y, and assigned them values 5 and "Hello" respectively. Later, we have changed the values of x and y to 10 and "World" respectively.

Example 3: Using Variables in Expressions

<script>
    var x = 5;
    var y = 10;
    var z = x + y;
    var name = "John";
    var greeting = "Hello " + name;
</script>

In the above example, we have declared four variables, x, y, z, and name, and assigned them values 5, 10, the sum of x and y, and "John" respectively. Later, we have declared a variable greeting and assigned it a value "Hello " concatenated with the value of name.

Conclusion

Variables are an essential concept in JS programming. They are used to store data values that can be used throughout the program. In this tutorial, we have discussed JS variables in detail, including their declaration, assignment, and usage in expressions. By understanding variables, you can write more efficient and effective JS code.

References

Activity