javascript

Declaration Statements

Learn what JavaScript declaration statements are, how to declare variables with let and const, functions, and classes to build structured programs.

10 min read 8 sections Tutorial
Share

A **declaration statement** is a command that introduces a new name or entity into your JavaScript program. These statements create things like variables, functions, or classes. They are essential for organizing your code and making sure everything has a proper name and purpose.

Declaration Statements

Declaration Statements

In JavaScript, a declaration statement is how you tell the computer, "Hey, I'm making something new, and here's its name." This "something new" could be a place to store data (a variable), a set of instructions to run (a function), or a blueprint for creating objects (a class).

Declaration statements are different from other code because they don't do something immediately. Instead, they define something that can be used later. They are like drawing a map before starting a journey.

What is a Declaration Statement?

A declaration statement introduces a new identifier (like a variable name, function name, or class name) into the current scope, making it available for use in your code.

Variables

Declare containers for data using let or const. These store numbers, text, or other values.

Functions

Declare blocks of reusable code using the function keyword. They perform specific tasks.

Classes

Declare blueprints for creating objects using the class keyword. They define structure and behavior.

Modules

Declare parts of your code to share with other files using import and export statements.

Declaring Variables and Functions

Getting Started

Declaring Variables and Functions

The most common declaration statements are for variables and functions. When you declare a variable, you are creating a named space in memory to hold a value. When you declare a function, you are creating a named block of code that you can run later.

Using let and const for variables is the modern way. Using the function keyword is the standard way to declare a function.

javascript
1// Declare a variable named 'userName' using 'let'
2let userName = "Chilly";
3
4// Declare a constant named 'MAX_ATTEMPTS' using 'const'
5const MAX_ATTEMPTS = 3;
6
7// Declare a function named 'greetUser'
8function greetUser() {
9 // This function uses the 'userName' variable
10 console.log("Hello, " + userName + "!");
11}
12
13// Now, we can use the declared items:
14console.log(userName); // Prints: Chilly
15console.log(MAX_ATTEMPTS); // Prints: 3
16greetUser(); // Calls the function, prints: Hello, Chilly!

Always Declare Before Use

If you try to use a variable or call a function before it has been declared, JavaScript will give you an error. The computer needs to know what something is before you ask it to use it. Think of it like telling a story: you must introduce the character before they speak.

Why Declarations Are Important

Why Declarations Are Important

Declaration statements are fundamental because they give structure to your code. Without them, your program would just be a series of actions without any named parts to refer to. They help you organize your code into reusable pieces.

They also help JavaScript understand the scope of your items. Scope means where in your program a variable or function can be accessed. Declarations define these boundaries, preventing accidental changes or conflicts between different parts of your code.

javascript
1const globalMessage = "I am everywhere!"; // This is a global declaration
2
3function showMessages() {
4 let functionMessage = "I am inside the function!"; // This is a function-scoped declaration
5 console.log(globalMessage); // You can use globalMessage here
6 console.log(functionMessage); // You can use functionMessage here
7}
8
9showMessages(); // Run the function
10
11console.log(globalMessage); // You can still use globalMessage here
12// console.log(functionMessage); // ❌ Error! functionMessage only exists inside showMessages
✗ BadWrong — Undeclared Variable
console.log(score); // ❌ ReferenceError
score = 10; // This creates a global variable (bad practice!)
✓ GoodCorrect — Declared Variable
let score; // ✅ Declare first
score = 10;
console.log(score); // 10

Function Declaration vs. Function Expression

Function Declaration vs. Function Expression

While the function keyword directly declares a function, you can also declare a function by assigning it to a variable. This is called a function expression. Both create functions, but they behave a little differently, especially regarding when they are available to be used.

A function declaration is often simpler for basic, named functions. A function expression is more flexible, letting you pass functions as arguments or define them only when needed.

Function Declaration
// Function Declaration
// This function is 'hoisted' — it can be called before its line in the code.
calculateSum(5, 3); // Works! Prints: 8
function calculateSum(a, b) {
console.log(a + b);
}
VS
Function Expression
// Function Expression
// This function is stored in a variable and can only be used after its line.
// calculateProduct(5, 3); // ❌ Error! Cannot access before initialization
const calculateProduct = function(a, b) {
console.log(a * b);
};
calculateProduct(5, 3); // Works! Prints: 15

When to Use Which?

Use function declarations for general-purpose functions that you want available throughout your code. Use function expressions (often arrow functions assigned to const) when you need a function for a specific task, like passing it to another function or defining it conditionally.

Building with Declarations

Building with Declarations

In a real program, you combine different types of declaration statements to create a structured application. You might declare variables to hold user input, functions to process that input, and classes to model complex data. Each declaration serves a specific purpose.

This approach makes your code modular and easier to understand. Imagine building a house: you declare the rooms (functions), the materials (variables), and the overall blueprint (class).

1

Declare Global Constants

Start by declaring important, unchanging values that your whole program might need.

javascript
1const APP_NAME = "Task Manager";
2const MAX_TASKS = 10;
2

Declare a Class Blueprint

Create a class to define how objects, like tasks, will look and behave.

javascript
1class Task {
2 constructor(description, isComplete = false) {
3 this.description = description;
4 this.isComplete = isComplete;
5 }
6
7 toggleComplete() {
8 this.isComplete = !this.isComplete;
9 }
10}
3

Declare a Function to Manage Tasks

Write a function that uses the Task class and variables to perform actions.

javascript
1let tasks = []; // Declare a variable to hold all tasks
2
3function addTask(description) {
4 if (tasks.length < MAX_TASKS) {
5 const newTask = new Task(description); // Create a new Task object
6 tasks.push(newTask);
7 console.log(`Added: ${description}`);
8 } else {
9 console.log("Cannot add more tasks. Limit reached.");
10 }
11}
4

Use the Declarations

Now you can use your declared variables, class, and function to run your program.

javascript
1console.log(`Welcome to ${APP_NAME}!`);
2addTask("Learn JavaScript Declarations");
3addTask("Build a small project");
4tasks[0].toggleComplete(); // Mark the first task as complete
5console.log(tasks);

Redeclaring Variables with `let` or `const`

You cannot declare the same let or const variable twice in the same scope. This prevents mistakes where you accidentally overwrite an important variable. Trying to do so will cause a SyntaxError.

let user = 'Bob';
// let user = 'Alice'; // ❌ SyntaxError: 'user' has already been declared

Common Declaration Types

Common Declaration Types

KeywordWhat it DeclaresCan Be Redeclared?Hoisted?
`let`Block-scoped variableNo (in same scope)No (Temporal Dead Zone)
`const`Block-scoped constant variableNo (in same scope)No (Temporal Dead Zone)
`function`FunctionYes (in non-strict mode)Yes (entire function)
`class`Class blueprintNo (in same scope)No (Temporal Dead Zone)
`var`Function-scoped variable (old)YesYes (only declaration, not value)

Test Your Knowledge

Test Your Knowledge

Test Your Knowledge

Quick Check

Which of these is NOT a declaration statement?

Quick Check

What happens if you try to declare a const variable without an initial value?

Quick Check

Which type of function can be called before its actual line of code appears in the script?

Quick Check

What is the primary purpose of declaration statements?

Quick Reference

Quick Reference

Quick Reference

Pro Tips
  • 1Declaration Statement — introduces a new named entity (variable, function, class) into your program's scope.
  • 2let Declaration — creates a block-scoped variable whose value can be changed. Example: let count = 0;
  • 3const Declaration — creates a block-scoped constant variable whose value cannot be changed after assignment. Example: const PI = 3.14;
  • 4function Declaration — creates a named, reusable block of code. These are hoisted. Example: function greet() { ... }
  • 5Function Expression — declares a function by assigning it to a variable, often const. Not fully hoisted. Example: const sayHi = function() { ... };
  • 6class Declaration — creates a blueprint for objects, defining properties and methods. Example: class Car { ... }
  • 7Hoisting — JavaScript moves declarations to the top of their scope. Functions are fully hoisted; var declarations are hoisted but undefined until assigned.
  • 8Temporal Dead Zone (TDZ)let and const variables are in a TDZ from the start of their block until their declaration, preventing use before definition.
  • 9No Redeclaration — You cannot declare the same let or const variable twice in the same scope; this will cause a SyntaxError.
  • 10import and export — Module declaration statements used to share code between different JavaScript files.

Data Types

Explore the different types of values (numbers, strings, booleans, objects) that variables can hold.

Operators

Learn how to use operators to perform calculations and comparisons with your declared variables.

Control Flow

Understand how to use if/else statements and loops to control when your declared functions run.

Scope

Dive deeper into how block, function, and global scope affect where your declarations are available.

You now understand JavaScript Declaration Statements!

You've learned how to introduce variables, functions, and classes into your JavaScript programs. Mastering declarations is a key step towards writing organized, reusable, and error-free code. Keep practicing, and you'll be building complex applications in no time!

Try it in the Javascript Compiler

Run and experiment with Javascript code right in your browser — no setup needed.

Continue Learning