JavaScript Functions
📘 What is a JavaScript Function?
A function in JavaScript is a block of reusable code that performs a specific task. You can
define a function once and use it many times.
✅ Why Use Functions?
- To reuse code.
- To break programs into smaller, manageable pieces.
- To increase readability and organization.
🧱 Basic Function Syntax
function functionName(parameters) {
// code to execute
}
✅ Example:
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Pascal"); // Output: Hello, Pascal!
🧩 Types of Functions
1. Named Functions
function add(a, b) {
return a + b;
}
2. Function Expressions
const subtract = function(a, b) {
return a - b;
};
3. Arrow Functions (ES6)
const multiply = (a, b) => a * b;
const greet = name => "Hi, " + name;
🔁 Calling a Function
You call (or invoke) a function by using its name followed by parentheses:
greet("John");
📦 Parameters vs. Arguments
Parameters are variables in the function definition.
Arguments are values passed to the function when calling it.
function greet(name) {
console.log("Hi, " + name);
}
greet("Neema");
🔙 Return Statement
A function can return a value using the return keyword.
function square(num) {
return num * num;
}
let result = square(4); // result is 16
🔄 Function Scope
Variables declared inside a function are local to that function.
function test() {
let x = 10;
console.log(x);
}
console.log(x); // Error: x is not defined
🧠 Examples & Practice
➕ Add Two Numbers:
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // 5
📅 Check if a number is even:
function isEven(n) {
return n % 2 === 0;
}
console.log(isEven(4)); // true
console.log(isEven(5)); // false
❓ Common Interview Question
🔹 What is the difference between a function declaration and function expression?
Feature Function Declaration Function Expression
Syntax function add(a, b) {} const add = function(a, b) {}
Hoisted? Yes No
Can be anonymous? No Yes
🧠 Small Quiz
1. What will this output?
function sayHello() {
return "Hello!";
}
console.log(sayHello());
✅ Answer: Hello!
2. What is the result of this?
const double = n => n * 2;
console.log(double(5));
✅ Answer: 10