Skip to main content

Command Palette

Search for a command to run...

JavaScript Variables and Data Types: A Beginner's Complete Guide

JavaScript Variables and Data Types

Updated
7 min read
JavaScript Variables and Data Types: A Beginner's Complete Guide
A

Hi, I’m Abdul Samad. A web development learner and tech enthusiast. I write about what I learn, share practical coding tips, and publish in-depth blogs on programming and modern web development.

Check out my full collection of blogs on Hashnode: https://abdulsamad30.hashnode.dev/

Connect with me on X for quick updates and insights: @abdul_sama60108

If you've ever wondered how websites remember your name, keep track of items in your shopping cart, or save your game progress, the answer is variables.

They're one of the most fundamental concepts in JavaScript and in programming as a whole.

In this guide, we'll break down everything you need to know about variables and data types in JavaScript, starting from the absolute basics.

By the end, you'll understand what variables are, how to create them, and how to work with different types of data.


What Are Variables and Why Do We Need Them?

Think of a variable as a labeled box that stores information. Just like you might have a box labeled "Photos" that holds your family pictures, a variable in JavaScript has a name and holds a piece of data.

For example, imagine you're building a simple program that greets users. You need to store the user's name somewhere so you can use it later.

That's exactly what a variable does it holds onto information so your program can remember and use it whenever needed.

Without variables, you couldn't:

  • Store user input

  • Keep track of scores in a game

  • Remember whether someone is logged in

  • Perform calculations with changing numbers

Variables make your code dynamic and interactive instead of static and lifeless.


How to Declare Variables in JavaScript

JavaScript gives you three ways to create (or "declare") variables: var, let, and const. Each has its own purpose and behavior.

Using var

var is the oldest way to declare variables in JavaScript. Here's how it looks:

var userName = "Sarah";
var userAge = 25;

The word var tells JavaScript, "I'm creating a variable." The name comes next (like userName), followed by an equals sign and the value you want to store.

Using let

let is a more modern way to declare variables, introduced in ES6 (2015). It works similarly to var but with some important differences we'll cover later:

let city = "New York";
let temperature = 72;

Using const

const is used when you want to create a variable whose value won't change:

const birthYear = 1998;
const pi = 3.14159;

Once you assign a value to a const variable, you can't reassign it to something else. Think of it as a permanent label.


Understanding Primitive Data Types

Now that you know how to create variables, let's talk about what kind of information they can hold.

JavaScript has several primitive data types these are the basic building blocks of data.

String

A string is text any sequence of characters wrapped in quotes. You can use single quotes, double quotes, or backticks:

let firstName = "Alex";
let lastName = 'Johnson';
let greeting = `Hello, world!`;

Strings are perfect for names, messages, addresses, or any text-based information.

Number

Numbers in JavaScript can be whole numbers (integers) or decimals (floats). Unlike some languages, JavaScript doesn't distinguish between them:

let age = 28;
let price = 19.99;
let temperature = -5;

You can use numbers for calculations, ages, prices, scores, and more.

Boolean

A boolean is a simple true/false value. It's like a light switch—it's either on or off:

let isStudent = true;
let hasGraduated = false;
let isLoggedIn = true;

Booleans are incredibly useful for conditions and decision-making in your code.

Null

null represents the intentional absence of a value. It's like an empty box that you've deliberately left empty:

let selectedItem = null;

You might use this when you want to show that something exists but currently has no value.

Undefined

undefined means a variable has been declared but hasn't been given a value yet:

let futureValue;
console.log(futureValue); // undefined

JavaScript automatically assigns undefined to variables you declare without initializing.


The Key Differences Between var, let, and const

While all three keywords create variables, they behave differently in important ways.

Can You Change the Value?

This is the most obvious difference:

var score = 10;
score = 15; // Works fine

let level = 1;
level = 2; // Works fine

const maxLives = 3;
maxLives = 5; // Error! Cannot reassign a const

Both var and let allow you to change the value later. const does not once set, it's permanent.

When to Use Each

  • Use const by default when you know a value won't change (birthdays, configuration settings, fixed limits)

  • Use let when you know a value will change (user input, counters, game scores)

  • Avoid var in modern JavaScript let and const are generally better choices


What Is Scope?

Scope determines where in your code a variable can be accessed. Think of it like rooms in a house.

Imagine you have a note in your bedroom. You can read it while you're in your bedroom, but if you go to the kitchen, you can't see that note anymore it's out of scope.

Block Scope with let and const

Variables declared with let and const are block-scoped, meaning they only exist within the curly braces {} where they're defined:

{
  let message = "Hello";
  console.log(message); // Works fine
}

console.log(message); // Error! message is not defined outside the block

Function Scope with var

Variables declared with var are function-scoped, meaning they're available anywhere within the function they're declared in, but this can sometimes lead to unexpected behavior. This is one reason why modern JavaScript prefers let and const.

The key takeaway: let and const give you more predictable, controlled scope, which helps prevent bugs.


Seeing Variables in Action

Let's put everything together with a practical example:

// Using const for values that won't change
const companyName = "Tech Solutions";
const founded = 2015;

// Using let for values that might change
let employeeCount = 50;
let isHiring = true;

// Displaying the information
console.log(companyName); // "Tech Solutions"
console.log("Founded in:", founded); // "Founded in: 2015"
console.log("Employees:", employeeCount); // "Employees: 50"
console.log("Currently hiring:", isHiring); // "Currently hiring: true"

// Updating values where allowed
employeeCount = 55; // This works
console.log("Updated employees:", employeeCount); // "Updated employees: 55"

// This would cause an error:
// founded = 2016; // Error! Cannot reassign const

Notice how we chose const for information that's fixed (the company name and founding year) and let for information that changes (employee count and hiring status).


Your First Assignment

Ready to practice? Here's a simple exercise to cement what you've learned:

Task

Create a small program that stores and displays information about yourself:

  1. Declare a variable for your name (use const since your name doesn't change)

  2. Declare a variable for your age (use let since age increases each year)

  3. Declare a variable called isStudent and set it to true or false (use const if your student status is fixed right now)

  4. Print all three variables to the console using console.log()

  5. Try changing the value of your age variable and print it again

  6. Try changing the value of your name variable—what happens?

Expected Output

Your console should show something like this:

Sarah
28
true
29
Error: Assignment to constant variable

What You'll Learn

This assignment will help you understand:

  • How to choose between let and const

  • How reassignment works differently for each

  • What error messages look like when you try to change a const


Wrapping Up

You've just learned one of the most essential concepts in JavaScript! Variables are the containers that hold your data, and understanding how to use them properly is the foundation for everything else you'll build.

To recap:

  • Variables are like labeled boxes that store information

  • JavaScript has three ways to declare them: var, let, and const

  • Different data types (string, number, boolean, null, undefined) serve different purposes

  • Use const by default, let when values change, and avoid var

  • Scope determines where variables can be accessed in your code

Keep practicing with the assignment above, and experiment with different types of data. The more you work with variables, the more natural they'll become.

FIN ✌️

JavaScript Variables and Data Types Explained for Beginners