JavaScript Variables & Data Types
Variables are containers for storing data values. In JavaScript, there are several ways to declare variables, and understanding data types is crucial for effective programming.
Declaring Variables
JavaScript provides three ways to declare variables:
// Using var (function-scoped, older style)
var name = "John";
// Using let (block-scoped, introduced in ES6)
let age = 30;
// Using const (block-scoped constant, introduced in ES6)
const PI = 3.14159;
var vs let vs const
Feature | var | let | const |
---|---|---|---|
Scope | Function scope | Block scope | Block scope |
Hoisting | Yes, initialized as undefined | Yes, but not initialized (TDZ) | Yes, but not initialized (TDZ) |
Reassignment | Allowed | Allowed | Not allowed |
Redeclaration | Allowed | Not allowed in same scope | Not allowed in same scope |
Modern Best Practice: Use const
by default, and only use let
when you need to reassign a variable. Avoid using var
in new code.
JavaScript Data Types
JavaScript has eight basic data types:
Primitive Types
// String - for text
let name = "John";
let greeting = 'Hello';
let template = `Hello, ${name}`; // Template literal (ES6)
// Number - for integers and floating-point numbers
let age = 30;
let price = 19.99;
let infinity = Infinity;
let notANumber = NaN;
// Boolean - true or false
let isActive = true;
let isComplete = false;
// Undefined - variable declared but not assigned a value
let undefinedVar;
// Null - represents the intentional absence of any value
let emptyValue = null;
// Symbol - unique and immutable primitive value (ES6)
let uniqueId = Symbol("id");
// BigInt - for integers of arbitrary length (ES2020)
let bigNumber = 9007199254740991n;
Object Type
// Object - collection of properties
let person = {
name: "John",
age: 30,
isEmployed: true
};
// Array - special kind of object for ordered collections
let colors = ["red", "green", "blue"];
// Function - callable object
let greet = function() {
return "Hello!";
};
Type Checking
JavaScript provides several ways to check the type of a variable:
// Using typeof operator
typeof "Hello"; // "string"
typeof 42; // "number"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object" (this is a known JavaScript quirk)
typeof Symbol(); // "symbol"
typeof 42n; // "bigint"
typeof {}; // "object"
typeof []; // "object" (arrays are objects in JavaScript)
typeof function(){}; // "function"
// For arrays, use Array.isArray()
Array.isArray([]); // true
Array.isArray({}); // false
Warning: typeof null
returns "object"
, which is a historical bug in JavaScript. To check if a value is null
, use strict equality: value === null
.
Type Conversion
JavaScript is a dynamically typed language, which means variables can change types. There are two types of type conversion:
Implicit Conversion (Type Coercion)
// String conversion
"5" + 2; // "52" (number is converted to string)
"5" + true; // "5true" (boolean is converted to string)
// Numeric conversion
"5" - 2; // 3 (string is converted to number)
"5" * 2; // 10 (string is converted to number)
"5" / 2; // 2.5 (string is converted to number)
// Boolean conversion
if ("hello") { // non-empty string is truthy
console.log("This will execute");
}
if (0) { // 0 is falsy
console.log("This won't execute");
}
Explicit Conversion
// To String
String(42); // "42"
(42).toString(); // "42"
// To Number
Number("42"); // 42
parseInt("42"); // 42
parseFloat("42.5"); // 42.5
+"42"; // 42 (unary plus operator)
// To Boolean
Boolean(42); // true
Boolean(0); // false
Boolean(""); // false
Boolean("hello"); // true
!!"hello"; // true (double negation)
Truthy and Falsy Values
In JavaScript, values are evaluated as either truthy or falsy in boolean contexts:
Falsy Values
false
0
,-0
,0n
(BigInt zero)""
,''
,``
(empty strings)null
undefined
NaN
Truthy Values
Everything else is considered truthy, including:
true
- Any number other than 0
- Any non-empty string
- All objects and arrays (even empty ones)
- All functions
Interactive Example: Type Explorer
Variable Scope
The scope of a variable determines where it can be accessed in your code:
Global Scope
// Variables declared outside any function or block
let globalVar = "I'm global";
function testScope() {
console.log(globalVar); // Accessible here
}
testScope(); // Outputs: "I'm global"
Function Scope
function testScope() {
// Variables declared inside a function
let functionVar = "I'm function-scoped";
console.log(functionVar); // Accessible here
}
testScope(); // Outputs: "I'm function-scoped"
// console.log(functionVar); // Error: functionVar is not defined
Block Scope
// Variables declared with let and const are block-scoped
if (true) {
let blockVar = "I'm block-scoped";
const alsoBlockScoped = "Me too";
var notBlockScoped = "I'm not block-scoped";
console.log(blockVar); // Accessible here
}
// console.log(blockVar); // Error: blockVar is not defined
// console.log(alsoBlockScoped); // Error: alsoBlockScoped is not defined
console.log(notBlockScoped); // Outputs: "I'm not block-scoped"
Note: Variables declared with var
are hoisted to the top of their containing function or global scope, not block scope.
Next Steps
Now that you understand JavaScript variables and data types, you can explore:
- Operators and expressions
- Control flow (if statements, loops)
- Functions and scope
- Objects and arrays in depth