Home Courses JS Functions Explained

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:

  1. A cook for making food
  2. A driver for driving
  3. A cleaner for cleaning


Whenever you need a task, you call the respective person.

Similarly, in JavaScript:

  1. A function is a block of code
  2. It performs a specific task
  3. You can call it whenever needed


Why Do We Use Functions?

  1. To perform actions on events (like button click)
  2. To make code reusable
  3. To make JavaScript interactive (UI changes, alerts, etc.)


Example Use Case

  1. Clicking a button shows an alert
  2. Without functions, this is not easy


Types of Functions (Basic Idea)

  1. Predefined Functions (built-in)
  2. Example: alert(), console.log()
  3. User-defined Functions
  4. 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>
  1. When button is clicked, the function runs


Important Concepts

  1. Function must be called to run
  2. Just creating a function is not enough

Wrong:

function test() {
alert("Hi");
}

Correct:

test();


Function Hoisting (Important Interview Point)

  1. You can call a function before declaring it
test();

function test() {
console.log("Works");
}
  1. This works in JavaScript


Functions vs Variables

  1. Functions can be used before declaration
  2. 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>
  1. One function can be used for multiple buttons


Events in JavaScript

  1. Click, hover, input etc. are called events
  2. Example: onclick is an event


Share this lesson: