10% complete
JavaScript Variables and Data Types
Variables are like containers that store data in your JavaScript program. Understanding variables and data types is one of the first steps to mastering JavaScript. In this tutorial, we'll cover everything you need to know to get started.
Real-World Analogy
Think of variables like labeled boxes where you can store different things:
- String - A box containing text, like your name
- Number - A box containing a number, like your age
- Boolean - A box containing a simple yes/no answer
- Array - A box with compartments for multiple items
- Object - A box with labeled compartments for different items
Declaring Variables in JavaScript
In JavaScript, there are three ways to declare variables: var
, let
, and const
.
1// Using var (older way, avoid when possible)2var name = "John";34// Using let (modern way, for variables that will change)5let age = 25;6age = 26; // We can change the value78// Using const (for variables that won't change)9const PI = 3.14159;10// PI = 3; // This would cause an error!
Best Practice
Modern JavaScript favors const
by default, and let
when you need to reassign values. Only use var
when you have a specific reason to do so (like supporting very old browsers).
Variable Naming Rules
When naming variables in JavaScript, follow these rules:
- Names can contain letters, digits, underscores, and dollar signs
- Names must begin with a letter, $ or _ (not a number)
- Names are case sensitive (
name
andName
are different) - Reserved words (like
let
orfunction
) cannot be used as names
1// Valid variable names2let firstName = "John";3let last_name = "Doe";4let $price = 29.99;5let _private = "secret";6let camelCase = "This is the standard convention";78// Invalid variable names9// let 1stPlace = "Gold"; // Cannot start with a number10// let my-variable = 123; // Cannot use hyphens11// let let = "value"; // Cannot use reserved words
JavaScript Data Types
JavaScript has several built-in data types. Let's explore each one with examples.
1. Strings
Strings are used to store text. You can create strings using single quotes, double quotes, or backticks.
1// Creating strings2let firstName = "John";3let lastName = 'Doe';45// String concatenation (joining strings)6let fullName = firstName + " " + lastName; // "John Doe"78// Template literals (using backticks)9let greeting = `Hello, ${firstName}!`; // "Hello, John!"1011// String properties and methods12let message = "Welcome to JavaScript";13console.log(message.length); // 23 (number of characters)14console.log(message.toUpperCase()); // "WELCOME TO JAVASCRIPT"15console.log(message.toLowerCase()); // "welcome to javascript"16console.log(message.indexOf("to")); // 8 (position of "to")17console.log(message.slice(0, 7)); // "Welcome"
2. Numbers
In JavaScript, all numbers (integers and decimals) are stored as a single data type: number
.
1// Creating numbers2let age = 25; // Integer3let price = 19.99; // Decimal4let temperature = -5; // Negative number5let billion = 1e9; // Scientific notation (1 billion)67// Basic math operations8let sum = 10 + 5; // 159let difference = 10 - 5; // 510let product = 10 * 5; // 5011let quotient = 10 / 5; // 212let remainder = 10 % 3; // 1 (remainder of 10/3)1314// Special number values15let infinity = Infinity;16let negInfinity = -Infinity;17let notANumber = NaN; // Result of invalid calculations1819// Number methods20let pi = 3.14159;21console.log(pi.toFixed(2)); // "3.14" (rounds to 2 decimal places)22console.log(Number.isInteger(age)); // true23console.log(Math.round(pi)); // 3
3. Booleans
Booleans represent one of two values: true
or false
. They're essential for conditional logic.
1// Creating booleans2let isActive = true;3let isLoggedIn = false;45// Comparison operators produce booleans6let isAdult = age >= 18; // true if age is 18 or more7let isEqual = 5 === 5; // true8let isNotEqual = 5 !== 10; // true910// Logical operators with booleans11let andResult = true && false; // false (both must be true)12let orResult = true || false; // true (at least one must be true)13let notResult = !true; // false (inverts the value)1415// Boolean function16console.log(Boolean(0)); // false17console.log(Boolean(1)); // true18console.log(Boolean("")); // false19console.log(Boolean("hello")); // true
Truthy Values
These are considered true
when converted to a boolean:
- Non-zero numbers (positive or negative)
- Non-empty strings
- Objects and arrays (even if empty)
- The boolean
true
itself
Falsy Values
These are considered false
when converted to a boolean:
- 0 (zero)
- Empty strings ("")
null
undefined
NaN
(Not a Number)- The boolean
false
itself
4. Null and Undefined
These special values represent the absence of a value.
1// undefined - a variable that has been declared but not assigned a value2let undefinedVar;3console.log(undefinedVar); // undefined45// null - an intentional absence of any value6let emptyValue = null;7console.log(emptyValue); // null89// Checking for null or undefined10console.log(undefinedVar === undefined); // true11console.log(emptyValue === null); // true
5. Arrays
Arrays are ordered collections of values, which can be of any type.
1// Creating arrays2let fruits = ["apple", "banana", "orange"];3let mixedArray = [1, "hello", true, null, {name: "John"}];45// Accessing array elements (zero-based indexing)6console.log(fruits[0]); // "apple"7console.log(fruits[1]); // "banana"8console.log(fruits.length); // 3910// Modifying arrays11fruits.push("grape"); // Add to the end12fruits.unshift("mango"); // Add to the beginning13let lastFruit = fruits.pop(); // Remove from the end14let firstFruit = fruits.shift(); // Remove from the beginning1516// Array methods17console.log(fruits.includes("banana")); // true18console.log(fruits.indexOf("orange")); // Index of "orange"19console.log(fruits.join(", ")); // "apple, banana, orange"2021// Advanced array methods22let numbers = [1, 2, 3, 4, 5];23let doubled = numbers.map(num => num * 2); // [2, 4, 6, 8, 10]24let evenNumbers = numbers.filter(num => num % 2 === 0); // [2, 4]25let sum = numbers.reduce((total, num) => total + num, 0); // 15
6. Objects
Objects store collections of data as key-value pairs. They're one of the most important data types in JavaScript.
1// Creating objects2let person = {3 firstName: "John",4 lastName: "Doe",5 age: 30,6 isEmployed: true,7 hobbies: ["reading", "gaming", "coding"],8 address: {9 city: "New York",10 country: "USA"11 }12};1314// Accessing object properties15console.log(person.firstName); // "John"16console.log(person["lastName"]); // "Doe" (alternative way)17console.log(person.hobbies[0]); // "reading"18console.log(person.address.city); // "New York"1920// Modifying objects21person.age = 31; // Change a property22person.email = "john@example.com"; // Add a new property23delete person.isEmployed; // Remove a property2425// Object methods26console.log(Object.keys(person)); // Array of property names27console.log(Object.values(person)); // Array of property values
Type Conversion
JavaScript is dynamically typed, which means you can change a variable's type. Sometimes JavaScript automatically converts types for you (implicit conversion), or you can do it explicitly.
1// String to Number2let numStr = "42";3let num1 = Number(numStr); // 42 (explicit conversion)4let num2 = +numStr; // 42 (shorthand)5let num3 = parseInt(numStr); // 42 (parses integers)6let num4 = parseFloat("3.14"); // 3.14 (parses floating point)78// Number to String9let num = 42;10let str1 = String(num); // "42" (explicit conversion)11let str2 = num.toString(); // "42" (method)12let str3 = num + ""; // "42" (implicit conversion)1314// To Boolean15let zero = 0;16let bool1 = Boolean(zero); // false17let bool2 = !!zero; // false (shorthand)1819// Automatic type conversion (be careful!)20console.log("5" + 2); // "52" (string concatenation)21console.log("5" - 2); // 3 (numeric subtraction)22console.log("5" * "2"); // 10 (numeric multiplication)
Careful with Type Coercion!
JavaScript tries to be helpful by automatically converting types, but this can lead to unexpected results. It's often better to explicitly convert types to make your code more predictable.
// Unexpected results with loose equality (==)console.log(0 == false); // trueconsole.log("" == false); // trueconsole.log("5" == 5); // true// Strict equality (===) checks type and valueconsole.log(0 === false); // falseconsole.log("5" === 5); // false
Checking Data Types
You can check the type of a variable using the typeof
operator.
1console.log(typeof "hello"); // "string"2console.log(typeof 42); // "number"3console.log(typeof true); // "boolean"4console.log(typeof undefined); // "undefined"5console.log(typeof null); // "object" (this is a known JavaScript quirk)6console.log(typeof []); // "object"7console.log(typeof {}); // "object"8console.log(typeof function(){}); // "function"910// For arrays, a better check is:11console.log(Array.isArray([])); // true12console.log(Array.isArray({})); // false
Practice Exercises
Try these exercises:
// 1. Variable Practice// Create variables for your name, age, and whether you're learning JavaScript// Print a message using all three variables// 2. Type Conversion// Convert the string "123.45" to a number// Convert the number 42 to a string// Convert an empty string to a boolean// 3. Object Creation// Create an object representing a book with title, author, year, and genre// Add a method to the object that returns a string describing the book// 4. Array Manipulation// Create an array of your favorite foods// Add a new food to the beginning// Remove the last food// Check if "pizza" is in your array
Summary
In this tutorial, you've learned:
- How to declare variables using
let
,const
, andvar
- The basic data types in JavaScript: strings, numbers, booleans, null, undefined
- Complex data types: arrays and objects
- How to convert between different data types
- How to check the type of a variable
Variables and data types form the foundation of JavaScript programming. In the next tutorials, you'll learn how to perform operations on these data types and how to control the flow of your program.
Related Tutorials
Learn the basics of JavaScript and why it's essential for web development.
Learn moreLearn about different operators in JavaScript for calculations and comparisons.
Learn moreLearn about conditional statements and loops in JavaScript.
Learn more