JS Functions Explained
What is a Function?
A function can be understood with a simple real-life example.
Imagine you have different people for different tasks:
- A cook for making food
- A driver for driving
- A cleaner for cleaning
Whenever you need a task, you call the respective person.
Similarly, in JavaScript:
- A function is a block of code
- It performs a specific task
- You can call it whenever needed
Why Do We Use Functions?
- To perform actions on events (like button click)
- To make code reusable
- To make JavaScript interactive (UI changes, alerts, etc.)
Example Use Case
- Clicking a button shows an alert
- Without functions, this is not easy
Types of Functions (Basic Idea)
- Predefined Functions (built-in)
- Example:
alert(),console.log() - User-defined Functions
- Created by developers
Function Syntax
function functionName() {
// code here
}
Calling a Function
functionName();
Example
function showMessage() {
alert("Hello World");
}
showMessage();
Button Click with Function
<button onclick="showMessage()">Click Me</button>
- When button is clicked, the function runs
Important Concepts
- Function must be called to run
- Just creating a function is not enough
Wrong:
function test() {
alert("Hi");
}
Correct:
test();
Function Hoisting (Important Interview Point)
- You can call a function before declaring it
test();
function test() {
console.log("Works");
}
- This works in JavaScript
Functions vs Variables
- Functions can be used before declaration
- Variables (let, const) cannot
console.log(name); // Error
let name = "John";
Reusability Example
<button onclick="showMessage()">Button 1</button>
<button onclick="showMessage()">Button 2</button>
<button onclick="showMessage()">Button 3</button>
- One function can be used for multiple buttons
Events in JavaScript
- Click, hover, input etc. are called events
- Example:
onclickis an event