In JavaScript, a variable is a named storage location for holding data. Variables allow you to store and manipulate data in your programs.
- Variable Declaration: You declare a variable using the
var
,let
, orconst
keyword followed by the variable name.
var age;
let name;
const pi = 3.14;
- Assignment: You assign a value to a variable using the
=
operator.
age = 25;
name = "John";
- Variable Types: JavaScript is dynamically typed, meaning variables can hold values of any type without any type enforcement.
var age = 25; // Number
var name = "John"; // String
var isStudent = true; // Boolean
var car = { brand: "Toyota", model: "Camry" }; // Object
var fruits = ["apple", "banana", "orange"]; // Array
- Scope: Variables can have global or local scope depending on where they are declared.
var globalVariable = "I am global";
function myFunction() {
var localVariable = "I am local";
console.log(globalVariable); // Accessible
console.log(localVariable); // Accessible
}
console.log(globalVariable); // Accessible
console.log(localVariable); // Throws an error (not accessible)
- Hoisting: In JavaScript, variables are hoisted to the top of their scope, which means you can use a variable before it is declared, but its value will be
undefined
.
console.log(myVariable); // undefined
var myVariable = 10;
- Constants: Variables declared with
const
cannot be reassigned.
const pi = 3.14;
pi = 3; // Error: Assignment to constant variable
- Let vs. Var:
let
has block scope, whereasvar
has function scope.
var x = 10;
if (true) {
var x = 20; // This will overwrite the outer 'x'
console.log(x); // 20
}
console.log(x); // 20
let y = 10;
if (true) {
let y = 20; // This creates a new 'y' inside the block
console.log(y); // 20
}
console.log(y); // 10