Function Declarations
Function Declarations
Basic Declaration
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet('John')); // "Hello, John!"
Function Expression
const greet = function(name) {
return `Hello, ${name}!`;
};
Named Function Expression
const greet = function greetFn(name) {
return `Hello, ${name}!`;
};
// greetFn is only accessible inside the function
Hoisting
// Declaration: hoisted
console.log(add(2, 3)); // 5
function add(a, b) {
return a + b;
}
// Expression: NOT hoisted
console.log(multiply(2, 3)); // Error!
const multiply = function(a, b) {
return a * b;
};
Default Parameters
function greet(name = 'Guest') {
return `Hello, ${name}!`;
}
greet(); // "Hello, Guest!"
greet('John'); // "Hello, John!"
Rest Parameters
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
sum(1, 2, 3); // 6
sum(1, 2, 3, 4); // 10
Early Return
function process(user) {
if (!user) return null;
if (!user.active) return null;
// Main logic here
return user.name;
}
Parameters and Return
Parameters and Return
Multiple Parameters
function add(a, b, c) {
return a + b + c;
}
add(1, 2, 3); // 6
Arguments Object
function sum() {
let total = 0;
for (let i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}
sum(1, 2, 3); // 6
Returning Multiple Values
// Using object
function getUser() {
return {
name: 'John',
age: 30,
email: 'john@example.com'
};
}
const { name, age } = getUser();
// Using array
function getCoordinates() {
return [10, 20];
}
const [x, y] = getCoordinates();
Returning Functions
function createMultiplier(multiplier) {
return function(number) {
return number * multiplier;
};
}
const double = createMultiplier(2);
const triple = createMultiplier(3);
double(5); // 10
triple(5); // 15
Void Operator
// Use when you don't care about return value
void console.log('no return value');
Undefined Return
function doNothing() {
// No return statement
}
console.log(doNothing()); // undefined
First-Class Functions
First-Class Functions
Functions in JavaScript are first-class citizens:
Assign to Variables
const greet = function(name) {
return `Hello, ${name}!`;
};
console.log(greet('John'));
Pass as Arguments
function doTwice(fn, value) {
fn(value);
fn(value);
}
doTwice(console.log, 'Hello');
// Hello
// Hello
Return from Functions
function createGreeter(greeting) {
return function(name) {
return `${greeting}, ${name}!`;
};
}
const sayHello = createGreeter('Hello');
const sayHi = createGreeter('Hi');
sayHello('John'); // "Hello, John!"
sayHi('Jane'); // "Hi, Jane!"
Callbacks
// Array methods
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(function(n) {
return n * 2;
});
// Event listeners
document.querySelector('button').addEventListener('click', function() {
console.log('Clicked!');
});
// Async callbacks
setTimeout(function() {
console.log('Done!');
}, 1000);
Higher-Order Functions
// Function that takes a function
function repeat(n, fn) {
for (let i = 0; i < n; i++) {
fn(i);
}
}
repeat(3, console.log);
// 0
// 1
// 2
// Function that returns a function
function multiplyBy(factor) {
return function(number) {
return number * factor;
};
}
const double = multiplyBy(2);
double(5); // 10
IIFE (Immediately Invoked Function Expression)
(function() {
const private = 'I am private';
console.log(private);
})();
// private is not accessible outside
Closures (Preview)
function createCounter() {
let count = 0;
return {
increment: () => ++count,
decrement: () => --count,
getCount: () => count
};
}
const counter = createCounter();
counter.increment(); // 1
counter.increment(); // 2
counter.getCount(); // 2
Practice Problems
Create a reusable React component implementing Functions. Include proper state management and accessibility.
Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where neededWrite unit and integration tests for Functions using React Testing Library.
Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility testsOptimize Functions for performance. Consider memoization, code splitting, and bundle size.
Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysisQuiz
1. What is the difference between function declaration and expression?
2. What does a function return if there's no return statement?
3. What is a higher-order function?
4. What are default parameters?
5. What is a callback?
Flashcards
Question
What is a function declaration vs expression?
Click to reveal answer
Answer
Declaration: function name() { }. Expression: const name = function() { }. Declarations are hoisted.
Question
What are default parameters?
Click to reveal answer
Answer
Parameters with fallback values used when no argument is passed: function greet(name = 'Guest') {}
Question
What is a higher-order function?
Click to reveal answer
Answer
A function that takes a function as an argument or returns a function.
Question
What is a callback?
Click to reveal answer
Answer
A function passed as an argument to another function, to be executed later.
Question
What is an IIFE?
Click to reveal answer
Answer
Immediately Invoked Function Expression - a function that runs immediately after being defined.
Revision Notes
Key Takeaways
- 1.Function declarations are hoisted, expressions are not
- 2.Functions return undefined by default
- 3.Higher-order functions take or return functions
- 4.Callbacks are functions passed as arguments
- 5.Default parameters provide fallback values
Interview Tips
- •Explain the difference between declarations and expressions
- •Know what higher-order functions are
- •Understand callbacks and their use cases
- •Be able to create functions that return functions
Cheat Sheet
Functions Cheat Sheet
Declaration
function greet(name) {
return `Hello, ${name}`;
}
Expression
const greet = function(name) {
return `Hello, ${name}`;
};
Arrow (Preview)
const greet = (name) => `Hello, ${name}`;
Default Parameters
function greet(name = 'Guest') { }
Rest Parameters
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
First-Class Functions
- Assign to variables
- Pass as arguments
- Return from functions
- Create closures