Functions: declare, call and return values
A function is a named block of code that performs a specific task and that you can run as many times as you want. Until now you have copied and pasted logic; with functions you write it once and reuse it. This reduces mistakes, makes changes easier and makes the program more readable, because a good name explains what is done without reading the details. Programming well is, to a large extent, splitting big problems into small functions.
Declaration, parameters and return
It is declared with the word function, a name, parameters in parentheses and a body in braces. Parameters are local variables that receive the values (arguments) you call the function with. The word return gives back a result and ends the function's execution at that point. If a function has no return, it returns undefined. A very common mistake is doing console.log inside the function instead of returning the value: that way you cannot reuse the result.
function add(a, b) {
return a + b;
}
const result = add(3, 4);
console.log(result); // 7
console.log(add(10, 5) * 2); // 30
function greet(name) {
console.log(`Hello, ${name}!`); // no return
}
const value = greet('Ana'); // prints Hello, Ana!
console.log(value); // undefined
function isAdult(age) {
if (age < 0) return false; // early return
return age >= 18;
}
console.log(isAdult(20), isAdult(-1)); // true falseFunction expressions and functions as values
In JavaScript functions are values like any other: you can store them in variables, put them in arrays and pass them to other functions. A function expression assigns an anonymous function to a variable. The practical difference from a declaration is hoisting: declarations can be called before the line where they appear, while expressions stored with const exist only from their line onward. You already used this idea when passing functions to map and filter.
console.log(square(4)); // 16 - declarations are hoisted
function square(n) {
return n * n;
}
const double = function (n) {
return n * 2;
};
console.log(double(6)); // 12
// Functions as arguments
function applyTwice(fn, value) {
return fn(fn(value));
}
console.log(applyTwice(double, 3)); // 12
console.log(applyTwice(square, 3)); // 81Good practices
- One function, one task: if you need to write and in the name, perhaps they are two functions.
- Names with verbs: calculateTotal, isValidEmail, formatDate.
- Return values instead of printing them, and print outside.
- Avoid changing external variables; receive data through parameters.
- Use early return for invalid cases and avoid nesting too many ifs.
Pure functions and side effects
A pure function always returns the same thing for the same arguments and changes nothing outside itself. They are very easy to test and to reason about. A side effect is anything the function does besides returning a value: printing, changing a global variable, modifying a received array or writing to the DOM. They are not bad, because a useful program needs them, but it is wise to concentrate them in a few functions and leave the calculation to pure functions. That way, the core of your logic can be tested without a browser or screen, simply by calling the function and comparing the result.
// Impure: changes the array it receives
function addItemImpure(list, item) {
list.push(item);
return list;
}
// Pure: returns a new array
function addItem(list, item) {
return [...list, item];
}
const original = [1, 2];
console.log(addItem(original, 3)); // [ 1, 2, 3 ]
console.log(original); // [ 1, 2 ] untouched✎ मेरे नोट्स
केवल इस ब्राउज़र में सहेजा गया। खाते में रखने के लिए साइन इन करें।0/5000 अक्षर