SimpleTuts.com

Functions in JavaScript

Understanding Functions in JavaScript

1. What is a Function?

A function is a reusable block of code designed to perform a specific task. Instead of writing the same code many times, we place it inside a function and call it whenever we need it.

Real-life analogy:


2. Basic Function Syntax


function functionName(){
    // code to execute
}

Example:


function sayHello(){
    console.log("Hello Students!");
}

sayHello();

Explanation:


3. Functions with Parameters

Functions can receive values called parameters.


function greet(name){
    console.log("Hello " + name);
}

greet("Rahul");

Output:


Hello Rahul

4. Functions with Return Values

Functions can return results using the return keyword.


function add(a, b){
    return a + b;
}

let result = add(5,3);
console.log(result);

Output:


8

5. Real-Life Example: Simple Calculator

This application performs basic arithmetic operations.

Operations:

index.html


<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
</head>
<body>

<h2>Simple Calculator</h2>

<input type="number" id="num1" placeholder="Enter first number"><br><br>
<input type="number" id="num2" placeholder="Enter second number"><br><br>

<button onclick="add()">Add</button>
<button onclick="subtract()">Subtract</button>
<button onclick="multiply()">Multiply</button>
<button onclick="divide()">Divide</button>

<h3 id="result"></h3>

<script src="app.js"></script>

</body>
</html>
Run Code

app.js


function add(){

let a = Number(document.getElementById("num1").value);
let b = Number(document.getElementById("num2").value);

let result = a + b;

document.getElementById("result").innerText = "Result: " + result;

}

function subtract(){

let a = Number(document.getElementById("num1").value);
let b = Number(document.getElementById("num2").value);

let result = a - b;

document.getElementById("result").innerText = "Result: " + result;

}

function multiply(){

let a = Number(document.getElementById("num1").value);
let b = Number(document.getElementById("num2").value);

let result = a * b;

document.getElementById("result").innerText = "Result: " + result;

}

function divide(){

let a = Number(document.getElementById("num1").value);
let b = Number(document.getElementById("num2").value);

let result = a / b;

document.getElementById("result").innerText = "Result: " + result;

}
Run Code


6. How This Example Works

  1. User enters two numbers.
  2. When a button is clicked, the corresponding function runs.
  3. The function performs the calculation.
  4. The result is displayed on the webpage.

7. Practice Exercise

Create a Temperature Converter.

Input:

Output:

Formula:


F = (C * 9/5) + 32

8. What Students Learned


Next Chapter

Chapter 6: Arrays in JavaScript with Real-Life Example: Student List Manager