A function in JavaScript is a block of reusable code that performs a specific task. Functions help organize code, avoid repetition, and make programs easier to read and maintain. Think of a function as a machine: you provide input, it does something, and it may give you output.
1️⃣ Defining a Function
A function is defined using the function keyword, followed by a name, parentheses (), and a block {}:
function greet() {
console.log("Hello, world!");
}
greet → function name() → holds parameters (optional input){} → contains statements the function executes2️⃣ Calling (Invoking) a Function
Defining a function does not run it. You need to call it:
greet(); // Output: Hello, world!
() are used to invoke the function.3️⃣ Function Parameters and Arguments
Functions can take parameters, which are like placeholders for input values:
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!
greet("Bob"); // Output: Hello, Bob!
name → parameter"Alice" and "Bob" → arguments4️⃣ Returning Values from a Function
Functions can return a value using the return keyword:
function add(a, b) {
return a + b;
}
let sum = add(5, 3);
console.log(sum); // Output: 8
return sends a value back to the code that called the function5️⃣ Function Expressions
Functions can also be stored in a variable (function expression):
const multiply = function(a, b) {
return a * b;
};
console.log(multiply(4, 5)); // Output: 20
multiply now holds the function6️⃣ Arrow Functions (Modern Syntax)
Modern JavaScript allows shorter syntax using arrow functions:
const divide = (a, b) => {
return a / b;
};
console.log(divide(10, 2)); // Output: 5
() hold parameters=> separates parameters from the function bodyreturn and {}:const square = x => x * x; console.log(square(4)); // Output: 16
Explanation:
showGreeting() → simple function with no inputadd(a, b) → returns sum of two numberssquare(x) → arrow function for squaring a number<!DOCTYPE html>
<html>
<head>
<title>JavaScript Functions Example</title>
<style>
body { font-family: Arial; padding: 20px; }
button { padding: 10px 20px; margin: 5px; cursor: pointer; }
p { font-size: 18px; color: darkgreen; }
</style>
</head>
<body>
<h1>JavaScript Functions Demo</h1>
<p id="demo">Click buttons to see function results</p>
<button onclick="showGreeting()">Greet</button>
<button onclick="showSum()">Add Numbers</button>
<button onclick="showSquare()">Square a Number</button>
<script>
// Function without parameters
function showGreeting() {
document.getElementById("demo").innerHTML = "Hello, visitor!";
}
// Function with parameters and return value
function add(a, b) {
return a + b;
}
function showSum() {
let sum = add(10, 5);
document.getElementById("demo").innerHTML = "Sum: " + sum;
}
// Arrow function
const square = x => x * x;
function showSquare() {
document.getElementById("demo").innerHTML = "Square of 6: " + square(6);
}
</script>
</body>
</html>