Function Declaration Syntax
What you'll learn: How to create named, reusable blocks of code using the classic function declaration syntax.
What Is a Function Declaration?
A function declaration is the most traditional way to define a named function in JavaScript. It lets you package a set of statements into a reusable block that you can call by name anywhere in your code.
The syntax follows this pattern:
function functionName() {
// Code to execute goes here
}
Breaking Down the Parts
functionkeyword: Tells JavaScript you're declaring a function- Function name: A descriptive identifier (follows variable naming rules)
- Parentheses
(): Will eventually hold parameters (coming in future lessons) - Curly braces
{}: Contain the function body—the code to execute
Your First Function
function greet() {
console.log("Hello, world!");
}
// Call (invoke) the function
greet(); // Output: Hello, world!
You define the function once, then call it as many times as needed by writing its name followed by ().
Why Use Functions?
Think of functions like recipes. Instead of writing out "mix flour, eggs, sugar..." every time you want a cake, you write the recipe once and say "make cake" whenever needed. Functions let you:
- Avoid repeating code
- Organize logic into named chunks
- Make code easier to read and maintain
Simple Example
function celebrateVictory() {
console.log("You won!");
console.log("Congratulations!");
}
celebrateVictory(); // Runs both console.log statements
celebrateVictory(); // You can call it again!
Key Takeaway: A function declaration creates a named, reusable block of code using the function keyword, a name, parentheses, and curly braces containing statements to execute when called.