Progress2 of 20 topics

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.

JavaScript
1// Using var (older way, avoid when possible)
2var name = "John";
3
4// Using let (modern way, for variables that will change)
5let age = 25;
6age = 26; // We can change the value
7
8// 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 and Name are different)
  • Reserved words (like let or function) cannot be used as names
JavaScript
1// Valid variable names
2let firstName = "John";
3let last_name = "Doe";
4let $price = 29.99;
5let _private = "secret";
6let camelCase = "This is the standard convention";
7
8// Invalid variable names
9// let 1stPlace = "Gold"; // Cannot start with a number
10// let my-variable = 123; // Cannot use hyphens
11// 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.

JavaScript
1// Creating strings
2let firstName = "John";
3let lastName = 'Doe';
4
5// String concatenation (joining strings)
6let fullName = firstName + " " + lastName; // "John Doe"
7
8// Template literals (using backticks)
9let greeting = `Hello, ${firstName}!`; // "Hello, John!"
10
11// String properties and methods
12let 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.

JavaScript
1// Creating numbers
2let age = 25; // Integer
3let price = 19.99; // Decimal
4let temperature = -5; // Negative number
5let billion = 1e9; // Scientific notation (1 billion)
6
7// Basic math operations
8let sum = 10 + 5; // 15
9let difference = 10 - 5; // 5
10let product = 10 * 5; // 50
11let quotient = 10 / 5; // 2
12let remainder = 10 % 3; // 1 (remainder of 10/3)
13
14// Special number values
15let infinity = Infinity;
16let negInfinity = -Infinity;
17let notANumber = NaN; // Result of invalid calculations
18
19// Number methods
20let pi = 3.14159;
21console.log(pi.toFixed(2)); // "3.14" (rounds to 2 decimal places)
22console.log(Number.isInteger(age)); // true
23console.log(Math.round(pi)); // 3

3. Booleans

Booleans represent one of two values: true or false. They're essential for conditional logic.

JavaScript
1// Creating booleans
2let isActive = true;
3let isLoggedIn = false;
4
5// Comparison operators produce booleans
6let isAdult = age >= 18; // true if age is 18 or more
7let isEqual = 5 === 5; // true
8let isNotEqual = 5 !== 10; // true
9
10// Logical operators with booleans
11let 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)
14
15// Boolean function
16console.log(Boolean(0)); // false
17console.log(Boolean(1)); // true
18console.log(Boolean("")); // false
19console.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.

JavaScript
1// undefined - a variable that has been declared but not assigned a value
2let undefinedVar;
3console.log(undefinedVar); // undefined
4
5// null - an intentional absence of any value
6let emptyValue = null;
7console.log(emptyValue); // null
8
9// Checking for null or undefined
10console.log(undefinedVar === undefined); // true
11console.log(emptyValue === null); // true

5. Arrays

Arrays are ordered collections of values, which can be of any type.

JavaScript
1// Creating arrays
2let fruits = ["apple", "banana", "orange"];
3let mixedArray = [1, "hello", true, null, {name: "John"}];
4
5// Accessing array elements (zero-based indexing)
6console.log(fruits[0]); // "apple"
7console.log(fruits[1]); // "banana"
8console.log(fruits.length); // 3
9
10// Modifying arrays
11fruits.push("grape"); // Add to the end
12fruits.unshift("mango"); // Add to the beginning
13let lastFruit = fruits.pop(); // Remove from the end
14let firstFruit = fruits.shift(); // Remove from the beginning
15
16// Array methods
17console.log(fruits.includes("banana")); // true
18console.log(fruits.indexOf("orange")); // Index of "orange"
19console.log(fruits.join(", ")); // "apple, banana, orange"
20
21// Advanced array methods
22let 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.

JavaScript
1// Creating objects
2let 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};
13
14// Accessing object properties
15console.log(person.firstName); // "John"
16console.log(person["lastName"]); // "Doe" (alternative way)
17console.log(person.hobbies[0]); // "reading"
18console.log(person.address.city); // "New York"
19
20// Modifying objects
21person.age = 31; // Change a property
22person.email = "john@example.com"; // Add a new property
23delete person.isEmployed; // Remove a property
24
25// Object methods
26console.log(Object.keys(person)); // Array of property names
27console.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.

JavaScript
1// String to Number
2let 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)
7
8// Number to String
9let num = 42;
10let str1 = String(num); // "42" (explicit conversion)
11let str2 = num.toString(); // "42" (method)
12let str3 = num + ""; // "42" (implicit conversion)
13
14// To Boolean
15let zero = 0;
16let bool1 = Boolean(zero); // false
17let bool2 = !!zero; // false (shorthand)
18
19// 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.

JavaScript
// Unexpected results with loose equality (==)
console.log(0 == false); // true
console.log("" == false); // true
console.log("5" == 5); // true
// Strict equality (===) checks type and value
console.log(0 === false); // false
console.log("5" === 5); // false

Checking Data Types

You can check the type of a variable using the typeof operator.

JavaScript
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"
9
10// For arrays, a better check is:
11console.log(Array.isArray([])); // true
12console.log(Array.isArray({})); // false

Practice Exercises

Try these exercises:

JavaScript
// 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, and var
  • 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 more

Learn about different operators in JavaScript for calculations and comparisons.

Learn more

Learn about conditional statements and loops in JavaScript.

Learn more