In HTML, scripting variables are used to store and manipulate data within a script. They act as containers that hold different types of information, such as numbers, strings, or objects. By using variables, you can dynamically change values and perform various operations in your script.
Declaring Variables
To declare a variable in JavaScript, you need to use the var keyword followed by the name of the variable. For example:
var age;
This declares a variable called age. However, since it is not assigned a value yet, its initial value is undefined.
You can also assign a value to the variable at the time of declaration:
var age = 25;
In this case, the variable age is declared and assigned the value 25.
Data Types
In JavaScript, variables can hold different types of data:
- Numbers: Variables can store numeric values. For example:
var count = 10;
- Strings: Variables can store text values enclosed in single or double quotes. For example:
var name = 'John';
- Booleans: Variables can hold either true or false.
For example:
var isActive = true;
- Arrays: Variables can store multiple values in an ordered list. For example:
var fruits = ['apple', 'banana', 'orange'];
- Objects: Variables can hold complex data structures. For example:
var person = { name: 'John', age: 25, isActive: true };
- Null: Variables can also have a value of null, which represents the absence of any object value.
- Undefined: If a variable is declared but not assigned a value, it is considered to be undefined.
Manipulating Variables
Once you have declared and assigned values to variables, you can manipulate them using various operations:
- Assignment: You can assign a new value to a variable using the assignment operator (
=
). For example:age = 30;
This will change the value of the variable age from 25 to 30.
- Arithmetic Operations: Variables storing numeric values can be used in arithmetic operations like addition, subtraction, multiplication, and division. For example:
// Addition var total = count + age; // Subtraction var difference = count - age; // Multiplication var product = count * age; // Division var quotient = count / age;
- Concatenation: If you have variables storing strings, you can concatenate them using the concatenation operator (
+
). For example:// Concatenating two strings var fullName = firstName + ' ' + lastName;
- Comparison: Variables can be compared using comparison operators like
==
,!=
,>
,<
, etc. For example:// Equality check var isEqual = value1 == value2; // Inequality check var isNotEqual = value1 != value2; // Greater than check var isGreater = value1 > value2; // Less than check var isLess = value1 < value2;
Conclusion
Scripting variables are a fundamental concept in JavaScript that allow you to store and manipulate data within your scripts. By understanding how to declare, assign values, and perform operations on variables, you can create dynamic and interactive web applications.