Variables are fundamental building blocks in JavaScript. They are containers for storing data values. Think of them as labeled boxes where you can put different types of information.
You can declare variables in JavaScript using three keywords:
var
: The older way of declaring variables. It has function scope and can be redeclared and updated.let
: Introduced in ES6 (ECMAScript 2015), it has block scope and can be updated but not redeclared within the same scope.const
: Also introduced in ES6, it has block scope and cannot be reassigned. You must initialize a constant when you declare it.Using let
:
let message;
message = "Hello, World!";
console.log(message); // Output: Hello, World!
Using const
:
const pi = 3.14159;
console.log(pi); // Output: 3.14159
// pi = 3.14; // This would cause an error
Using var
(generally avoid in modern JS):
var count = 10;
console.log(count); // Output: 10
_
), or a dollar sign ($
)._
) or dollar signs ($
).myVariable
is different from myvariable
).if
, for
, while
, function
, let
, const
, etc.) cannot be used as variable names.Valid Names:
userName
_userId
$price
myVariable123
Invalid Names:
1stPlace
(starts with a number)my-variable
(contains a hyphen)class
(reserved word)JavaScript has several primitive data types:
"
or '
).true
or false
.JavaScript also has a non-primitive data type:
let greeting = "Hello there!";
let age = 30;
let isStudent = false;
let x; // x is undefined
let person = { firstName: "John", lastName: "Doe" };
typeof
OperatorThe typeof
operator can be used to find the type of a variable:
let name = "Alice";
console.log(typeof name); // Output: string
let score = 95;
console.log(typeof score); // Output: number
let isActive = true;
console.log(typeof isActive); // Output: boolean
let data;
console.log(typeof data); // Output: undefined
console.log(typeof null); // Output: object (This is a known quirk in JavaScript)
const
by default for variables whose values will not change.let
when you know the variable's value will need to be reassigned.var
in modern JavaScript development due to its hoisting and scoping behaviors.