Functions are reusable blocks of code that take input through parameters and hand back a result with return. This lesson covers function declarations and expressions, ES6 arrow functions and implicit returns, default parameters, local scope, and passing functions as arguments (callbacks).
1JS Functions | JavaScript Tutorial - In-Depth Guide Part 1
Welcome to JavaScript Functions. Functions are the heart of programmingβthey are reusable blocks of code that perform a specific task. Write once, execute everywhere.
// Functions: The Reusable Logic Blocks2JS Functions | JavaScript Tutorial - In-Depth Guide Part 2
A ''Function Declaration' uses the function keyword. It's 'Hoisted', meaning you can call it even before you define it in your script.
function greet() {
console.log('Hello World!');
}
greet(); // This is the 'Invocation'3JS Functions | JavaScript Tutorial - In-Depth Guide Part 3
Parameters act as placeholders for data you pass in. They allow the same function to work with different inputs every time it runs.
function showScore(name, pts) {
console.log(`${name}: ${pts} pts`);
}
showScore('Neo', 100);4JS Functions | JavaScript Tutorial - In-Depth Guide Part 4
A ''Function Expression' assigns a function to a variable. These are NOT hoisted, so you must define them before you try to use them.
const add = function(a, b) {
return a + b;
};
console.log(add(5, 10));5JS Functions | JavaScript Tutorial - In-Depth Guide Part 5
ES6 introduced ''Arrow Functions'. They offer a shorter syntax and are the modern standard for writing callbacks and small utility functions.
const multiply = (x, y) => {
return x * y;
};6JS Functions | JavaScript Tutorial - In-Depth Guide Part 6
For single-line arrows, you can omit the ''return' and the curly braces. This is called an 'Implicit Return'. It's incredibly concise.
const double = n => n * 2;
console.log(double(10)); // 207JS Functions | JavaScript Tutorial - In-Depth Guide Part 7
Watch the render. See how functions create their own ''Scope' and how data flows in through parameters and back out through returns.
8JS Functions | JavaScript Tutorial - In-Depth Guide Part 8
Scope: Variables defined inside a function are ''Local'βthey cannot be accessed from outside. This is called encapsulation.
function test() {
let local = 'secret';
}
// console.log(local); // Error!9JS Functions | JavaScript Tutorial - In-Depth Guide Part 9
Default Parameters: You can set a fallback value for a parameter in case the caller forgets to provide one.
function greet(name = 'Guest') {
console.log(`Hi, ${name}`);
}10JS Functions | JavaScript Tutorial - In-Depth Guide Part 10
Functions are ''First-Class Citizens' in JS. This means they can be passed as arguments to other functions, which is the basis of callbacks.
function runTask(task) {
task();
}
runTask(() => console.log('Done'));11JS Functions | JavaScript Tutorial - In-Depth Guide Part 11
You' You can now wrap complex operations into clean, reusable packages.
console.log('Logic Modularization: Enabled');12JS Functions | JavaScript Tutorial - In-Depth Guide Part 12
Function mastery achieved! Now let' Explore how to control the browser's display with the DOM.
13Step-by-Step Breakdown
Welcome to JavaScript Functions. Functions are the heart of programmingβthey are reusable blocks of code that perform a specific task. Write once, execute everywhere.
A ''Function Declaration' uses the function keyword. It's 'Hoisted', meaning you can call it even before you define it in your script.
Parameters act as placeholders for data you pass in. They allow the same function to work with different inputs every time it runs.
Checkpoint: What is the correct way to ''call' or 'invoke' a function named 'startEngine'?
- βstartEngine
- βstartEngine()
A ''Function Expression' assigns a function to a variable. These are NOT hoisted, so you must define them before you try to use them.
ES6 introduced ''Arrow Functions'. They offer a shorter syntax and are the modern standard for writing callbacks and small utility functions.
For single-line arrows, you can omit the ''return' and the curly braces. This is called an 'Implicit Return'. It's incredibly concise.
Watch the render. See how functions create their own ''Scope' and how data flows in through parameters and back out through returns.
Checkpoint: Which keyword is used to send a value back from a function to the code that called it?
- βsend
- βreturn
Scope: Variables defined inside a function are ''Local'βthey cannot be accessed from outside. This is called encapsulation.
Default Parameters: You can set a fallback value for a parameter in case the caller forgets to provide one.
Functions are ''First-Class Citizens' in JS. This means they can be passed as arguments to other functions, which is the basis of callbacks.
You' You can now wrap complex operations into clean, reusable packages.
Checkpoint: True or False: An Arrow Function with multiple parameters MUST use parentheses around them.
- βTrue
- βFalse
Function mastery achieved! Now let' Explore how to control the browser's display with the DOM.
Level Up π
Advanced cheat sheets, SEO tricks, and interview prep for this topic.
Browser Support
Fully supported.
Fully supported.
Fully supported.
Fully supported.
Accessibility (A11y)
1Event Handler Functions Must Prevent Default Behavior Correctly for Assistive Tech
A function attached to a form's submit event that forgets to call `e.preventDefault()` before doing custom validation will let the browser navigate away regardless, which can be jarring for screen reader and keyboard users who lose their place on the page.
SEO Implications
- 1
Functions That Generate Content Client-Side May Delay What Crawlers See
If a function builds and inserts page content into the DOM only after some client-side logic runs, search engine crawlers that don't wait for that execution may index a page missing that content. For SEO-relevant text, render it server-side rather than generating it entirely through client JS functions.
Best Practices
Prefer Function Declarations for Code That Needs Hoisting, Arrow Functions for Callbacks
Function declarations are hoisted, so they're useful when you want to call a function before its definition appears further down the file. Arrow functions are more concise and don't rebind `this`, making them the natural choice for callbacks passed to array methods or event listeners.
Use Default Parameters Instead of Manual undefined Checks
Writing `function greet(name) { name = name || 'Guest'; }` is a common workaround, but it also overrides falsy values like an empty string or 0. A default parameter (`function greet(name = 'Guest')`) only kicks in when the argument is actually omitted or explicitly undefined.
Frequent Bugs
`ReferenceError: Cannot access 'x' before initialization` when calling a function expression too early.
Unlike function declarations, function expressions assigned to a `const` or `let` variable are not hoisted with their value β the variable exists but isn't assigned yet at the top of the scope. Move the function expression above the code that calls it, or convert it to a function declaration if hoisting is required.
Real-World Examples
A Reusable Validator Function with a Default Parameter
A signup form needed to validate a username against a minimum length that could vary by context (e.g. stricter rules for admin accounts), so the minimum length was made an optional parameter with a sensible default.
function isValidUsername(username, minLength = 3) {
return typeof username === 'string' && username.trim().length >= minLength;
}
isValidUsername('ab'); // false
isValidUsername('alice'); // true
isValidUsername('bo', 2); // true