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
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.
1// Declare a variable named 'userName' using 'let'2let userName = "Chilly";34// Declare a constant named 'MAX_ATTEMPTS' using 'const'5const MAX_ATTEMPTS = 3;67// Declare a function named 'greetUser'8function greetUser() {9 // This function uses the 'userName' variable10 console.log("Hello, " + userName + "!");11}1213// Now, we can use the declared items:14console.log(userName); // Prints: Chilly15console.log(MAX_ATTEMPTS); // Prints: 316greetUser(); // 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.
1const globalMessage = "I am everywhere!"; // This is a global declaration23function showMessages() {4 let functionMessage = "I am inside the function!"; // This is a function-scoped declaration5 console.log(globalMessage); // You can use globalMessage here6 console.log(functionMessage); // You can use functionMessage here7}89showMessages(); // Run the function1011console.log(globalMessage); // You can still use globalMessage here12// console.log(functionMessage); // ❌ Error! functionMessage only exists inside showMessages
console.log(score); // ❌ ReferenceErrorscore = 10; // This creates a global variable (bad practice!)
let score; // ✅ Declare firstscore = 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// This function is 'hoisted' — it can be called before its line in the code.calculateSum(5, 3); // Works! Prints: 8function calculateSum(a, b) {console.log(a + b);}
// Function Expression// This function is stored in a variable and can only be used after its line.// calculateProduct(5, 3); // ❌ Error! Cannot access before initializationconst calculateProduct = function(a, b) {console.log(a * b);};calculateProduct(5, 3); // Works! Prints: 15
// Function Declaration// This function is 'hoisted' — it can be called before its line in the code.calculateSum(5, 3); // Works! Prints: 8function calculateSum(a, b) {console.log(a + b);}
// Function Expression// This function is stored in a variable and can only be used after its line.// calculateProduct(5, 3); // ❌ Error! Cannot access before initializationconst 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).
Declare Global Constants
Start by declaring important, unchanging values that your whole program might need.
1const APP_NAME = "Task Manager";2const MAX_TASKS = 10;
Declare a Class Blueprint
Create a class to define how objects, like tasks, will look and behave.
1class Task {2 constructor(description, isComplete = false) {3 this.description = description;4 this.isComplete = isComplete;5 }67 toggleComplete() {8 this.isComplete = !this.isComplete;9 }10}
Declare a Function to Manage Tasks
Write a function that uses the Task class and variables to perform actions.
1let tasks = []; // Declare a variable to hold all tasks23function addTask(description) {4 if (tasks.length < MAX_TASKS) {5 const newTask = new Task(description); // Create a new Task object6 tasks.push(newTask);7 console.log(`Added: ${description}`);8 } else {9 console.log("Cannot add more tasks. Limit reached.");10 }11}
Use the Declarations
Now you can use your declared variables, class, and function to run your program.
1console.log(`Welcome to ${APP_NAME}!`);2addTask("Learn JavaScript Declarations");3addTask("Build a small project");4tasks[0].toggleComplete(); // Mark the first task as complete5console.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
| Keyword | What it Declares | Can Be Redeclared? | Hoisted? |
|---|---|---|---|
| `let` | Block-scoped variable | No (in same scope) | No (Temporal Dead Zone) |
| `const` | Block-scoped constant variable | No (in same scope) | No (Temporal Dead Zone) |
| `function` | Function | Yes (in non-strict mode) | Yes (entire function) |
| `class` | Class blueprint | No (in same scope) | No (Temporal Dead Zone) |
| `var` | Function-scoped variable (old) | Yes | Yes (only declaration, not value) |
Test Your Knowledge
Test Your Knowledge
Which of these is NOT a declaration statement?
What happens if you try to declare a const variable without an initial value?
Which type of function can be called before its actual line of code appears in the script?
What is the primary purpose of declaration statements?
Quick Reference
Quick Reference
- 1Declaration Statement — introduces a new named entity (variable, function, class) into your program's scope.
- 2
letDeclaration — creates a block-scoped variable whose value can be changed. Example:let count = 0; - 3
constDeclaration — creates a block-scoped constant variable whose value cannot be changed after assignment. Example:const PI = 3.14; - 4
functionDeclaration — 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() { ... }; - 6
classDeclaration — 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;
vardeclarations are hoisted butundefineduntil assigned. - 8Temporal Dead Zone (TDZ) —
letandconstvariables are in a TDZ from the start of their block until their declaration, preventing use before definition. - 9No Redeclaration — You cannot declare the same
letorconstvariable twice in the same scope; this will cause aSyntaxError. - 10
importandexport— 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.