~/
hackweb.dev
JavaScript Functions Basics
Quiz
⌘K
...
~/
/tutorials
/js/js-functions-basics/edit
~ Contribute
Suggest a correction or improvement. The author reviews it before it goes live.
Loading...
Comment
0 / 300
Typo
Grammar
Broken link
Clarify
Code
en/tutorials/js/8js-functions-basics
Write
Preview
Diff
# JavaScript Functions Basics Functions are reusable blocks of code that perform specific tasks. They are the building blocks of JavaScript programs. ## Function Declarations ```javascript function add(a, b) { return a + b; } let result = add(5, 3); // 8 ``` Declarations are hoisted — they can be called before they appear in the code. ## Function Expressions Functions can be assigned to variables: ```javascript let multiply = function(a, b) { return a * b; }; let result = multiply(4, 5); // 20 ``` ## Default Parameters Provide default values if no argument is passed: ```javascript function greet(name, greeting = "Hello") { return `${greeting}, ${name}!`; } greet("John"); // "Hello, John!" greet("John", "Hi"); // "Hi, John!" ``` ## Return Values ```javascript function getFullName(first, last) { return `${first} ${last}`; } let name = getFullName("John", "Doe"); // "John Doe" ``` **Remember:** A function without `return` returns `undefined`. ## Arrow Functions Shorter syntax for function expressions: ```javascript // Traditional let add = function(a, b) { return a + b; }; // Arrow let add = (a, b) => a + b; ``` Single expression functions get an implicit return. ## Complete Example: Calculator ```javascript function calculate(num1, num2, operator) { switch (operator) { case "add": return num1 + num2; case "subtract": return num1 - num2; case "multiply": return num1 * num2; case "divide": return num1 / num2; default: return NaN; } } calculate(10, 5, "add"); // 15 calculate(10, 5, "multiply"); // 50 ``` ## Complete Example: Data Processor ```javascript function processData(data, transform) { return data.map(transform); } let numbers = [1, 2, 3, 4, 5]; let doubled = processData(numbers, (n) => n * 2); // [2, 4, 6, 8, 10] let names = ["alice", "bob", "charlie"]; let capitalized = processData(names, (n) => n.charAt(0).toUpperCase() + n.slice(1)); // ["Alice", "Bob", "Charlie"] ``` ## Best Practices 1. **Keep functions small** — One responsibility per function 2. **Use descriptive names** — `calculateTotal()` not `calc()` 3. **Use default parameters** — For optional values 4. **Return early** — Reduce nesting with early returns 5. **Avoid side effects** — Pure functions are easier to test ## Common Mistakes 1. **Forgetting `return`** — Functions return `undefined` by default 2. **Using `var` in functions** — Use `let` or `const` 3. **Confusing parameters and arguments** — Parameters in definition, arguments in call 4. **Using arrow functions for methods** — They don't have their own `this` 5. **Deep nesting** — Break complex logic into smaller functions
No changes yet
Reset to original
Submit suggestion
cancel