41. Defining Functions: Function Declarations
A function is a block of code designed to perform a particular task. Functions allow us to reuse code (DRY principle).
Function Declaration Syntax
The most traditional way to define a function is via a function declaration. This defines the function with a specific name.
javascript function functionName(parameter1, parameter2) { // Block of code to be executed // ... }
Example: Greeting Function
javascript // 1. Declare the function function greetUser(name) { console.log('Hello, ' + name + '!'); }
// 2. Call (execute) the function greetUser('Sarah'); // Output: Hello, Sarah! greetUser('Tom'); // Output: Hello, Tom!
Hoisting
Function declarations benefit from hoisting. This means the function can be called before it appears in the code. (We will cover hoisting in depth later.)
javascript sayGoodbye(); // This works even though the function is defined below.
function sayGoodbye() { console.log('Goodbye!'); }