Functions
Learn how to create reusable blocks of code and organize JavaScript programs using functions.
What is a Function?
A function is a reusable block of code that performs a specific task.
When the same task is required multiple times in a program, we can place that logic inside a function and call the function whenever needed.
This makes the program easier to organize and reduces repeated code.
Why Do We Use Functions?
Reusability
Write a task once and call the same function whenever you need it.
Organization
Divide a large program into smaller, meaningful blocks of code.
Maintainability
Keep related logic together so it is easier to update and understand.
Basic Function Syntax
function functionName() {
// code to execute
}
functionName();
Understanding the Syntax
function is the keyword used to create a function.
functionName is the name given to the function.
Parentheses () are used for parameters. They can be empty.
Curly braces { } contain the statements that execute when the function runs.
functionName() calls the function and executes its code.
How a Function Works
Example 1: Creating and Calling a Function
In this example, we create a function named showWelcome.
The code inside the function runs when we call showWelcome().
function showWelcome() {
console.log("Welcome to CIIT Training Institute!");
console.log("Start learning JavaScript.");
}
showWelcome();
Output
Start learning JavaScript.
Example 2: Function with a Parameter
A function can accept information through parameters. A parameter works like a variable inside the function.
Here, studentName receives the value "Gauri" when the function is called.
function greetStudent(studentName) {
console.log("Hello, " + studentName);
console.log("Welcome to JavaScript!");
}
greetStudent("Gauri");
Output
Welcome to JavaScript!
Important Note
Function Definition vs Function Call
Defining a function creates the reusable block of code.
Calling the function executes the statements inside that function.
Function Topics
Function Declaration
Learn how to declare and call traditional JavaScript functions.
Parameters & Arguments
Learn how functions receive input values.
Return Values
Learn how a function can return a result.
Arrow Functions
Learn the shorter syntax for writing functions.
Callback Functions
Learn how functions can be passed to other functions.
Summary
A function is a reusable block of JavaScript code designed to perform a specific task. Functions help reduce repeated code and make programs easier to organize and maintain. A function can be called whenever its task is required and can also receive parameters or return values.