In JavaScript, variables are used to store data values. You can declare a variable using the var
, let
, or const
keyword. For example:
var x = 10;
let y = 20;
const z = 30;
The var
keyword has function scope, meaning it is accessible within the function it is declared. The let
and const
keywords have block scope, meaning they are only accessible within the block they are declared.
JavaScript supports various data types, including:
Number: Represents both integer and floating-point numbers.
let age = 25;
let price = 19.99;
String: Represents text and is enclosed in single or double quotes.
let name = "John";
let greeting = 'Hello, world!';
Boolean: Represents logical values true
or false
.
let isActive = true;
let isMember = false;
Object: Represents a collection of key-value pairs.
let person = {
firstName: "Jane",
lastName: "Doe",
age: 30
};
Array: Represents an ordered list of values.
let colors = ["red", "green", "blue"];
Undefined: Represents an uninitialized variable.
let x;
console.log(x); // undefined
Null: Represents an intentional absence of any object value.
let y = null;
Symbol: Represents a unique and immutable value, often used as object keys.
let sym = Symbol("unique");
Understanding variables and data types is fundamental to writing effective JavaScript code.