Function Declaration
Learn how to declare a JavaScript function, understand its parts, and call it to execute reusable code.
What is a Function Declaration?
A function declaration is a standard way of defining a named function in JavaScript.
The declaration specifies the function name, optional parameters, and the block of code that should execute when the function is called.
Once declared, the same function can be called multiple times whenever the task is required.
A JavaScript function declaration creates a reusable block of code.
Basic Structure
function functionName(parameter1, parameter2) {
// function body
}
functionName(value1, value2);
Parts of a Function Declaration
function Keyword
The function keyword tells JavaScript that we are declaring a function.
Function Name
The function name identifies the function and is used when calling it.
Function Body
The statements inside curly braces form the function body.
How Function Declaration Works
Example 1: Simple Function Declaration
Here, the greetStudent function is declared with a name and a simple function body.
The function is executed by calling greetStudent().
function greetStudent() {
console.log("Welcome to JavaScript!");
console.log("Start practicing functions.");
}
greetStudent();
Output
Start practicing functions.
Example 2: Calling a Function Multiple Times
One important benefit of a function is reusability. After declaring a function once, we can call it multiple times.
function showCourse() {
console.log("JavaScript Full Stack");
}
showCourse();
showCourse();
showCourse();
Output
JavaScript Full Stack
JavaScript Full Stack
Important Note
Function Name Should Be Meaningful
Use a clear function name that describes the task performed by the function.
Names such as calculateTotal(), showCourse(), and greetStudent() make code easier to understand.
Summary
A function declaration uses the function keyword followed by a function name, parentheses, and a function body. The declared function can then be called whenever its task is required. Function declarations are useful for creating reusable and organized JavaScript code.