In JavaScript, variables are used to store data values. Each variable has a name, which is used to reference the stored value, and a data type, which defines the type of data that the variable can hold. JavaScript supports several data types, each with its own characteristics and uses.
Let's go through some common data types with code examples:
- Numbers: Used for storing numeric values.
var age = 25; // Integer
var price = 99.99; // Floating-point number
- Strings: Used for storing text.
var name = "John"; // Double or single quotes can be used
var message = 'Hello, world!';
- Booleans: Used for storing true or false values.
var isLogged = true;
var hasPermission = false;
- Null: Represents the intentional absence of any value.
var myVar = null;
- Undefined: Represents an uninitialized variable or a missing value.
var myVar;
console.log(myVar); // Outputs: undefined
- Objects: Used for storing collections of key-value pairs.
var person = {
firstName: "Alice",
lastName: "Johnson",
age: 30
};
- Arrays: Used for storing ordered collections of values.
var colors = ["red", "green", "blue"];
- Functions: Used for storing reusable blocks of code.
function add(a, b) {
return a + b;
}
- Symbols (ES6): Used to create unique identifiers.
var id = Symbol("uniqueID");
- BigInt (ES11): Used for working with large integers.
var bigValue = 1234567890123456789012345678901234567890n;
Now, let's see some variable examples:
// Variable declaration and assignment
var age = 30;
var name = "Alice";
var isLoggedIn = true;
// Variable reassignment
age = 31;
name = "Bob";
isLoggedIn = false;
// Using variables in expressions
var total = age + 10;
var greeting = "Hello, " + name + "!";