Functions are reusable blocks of code designed to perform a particular task. They are fundamental to every programming language. This lesson covers how to write them: the keyword, the name, the parentheses, and the body. Functions help you reuse code (write once, run many times), organize code into smaller parts, and make code easier to read and fix.
function name(p1, p2, ...) {
// code to be executed
}
function keyword starts the definition( ), holding optional parameters separated by commas{ }, holding the body: the code to runA function can also send an optional value back to whoever called it, with return.
function sayHello() {
console.log("Hello!");
}
This one has no parameters (empty parentheses) because it needs no input. Very short functions are sometimes written on one line, function sayHello() { return "Hello World"; }, but spreading them over several lines is more common and easier to read.
}. Adding one does no harm, but it is not the convention.
Writing a function only defines it. The code above does nothing on its own. To run it, call it: its name followed by parentheses. The () means "execute now":
function sayHello() {
console.log("Hello!");
}
sayHello();
sayHello();
Function names follow the same rules as variable names (letters, digits, _, $; no leading digit) and use camelCase. Because functions do things, start their names with a verb:
// Good: clear actions
calculateTotal()
showMenu()
getUserName()
isValidEmail() // "is" / "has" / "can" for true/false answers
// Vague: what do these do?
stuff()
doIt()
data()
Put a name inside the parentheses to accept a value. Inside the body it works like a variable:
function square(n) {
console.log(n * n);
}
square(4);
square(9);
Separate several parameters with commas: function multiply(a, b) { return a * b; }.
Printing is fine for demos, but usually you want the result so you can use it. return hands it back to whoever called the function, and the returned value can be stored in a variable:
function add(a, b) {
return a + b;
}
let sum1 = add(5, 5);
let sum2 = add(50, 50);
console.log(sum1, sum2);
The same code with different input produces different results. That is the whole point.
console.log it. A returned value can be printed, stored, compared, or passed to another function. A logged value can only be looked at.
A call to a function that returns something can go anywhere a value can: in math, in a string, in a condition. You do not always need a variable in between:
function toCelsius(fahrenheit) {
return (5 / 9) * (fahrenheit - 32);
}
// With a variable in between
let x = toCelsius(77);
let text1 = "The temperature is " + x + " Celsius";
// Using the call directly
let text2 = "The temperature is " + toCelsius(77) + " Celsius";
console.log(text2);
The most useful functions take something in and give something back:
function greet(name) {
return "Hello " + name;
}
greet("Riya");
| Parameter | name | the name listed in the definition |
| Argument | "Riya" | the value sent in at the call |
| Function code | return "Hello " + name; | the work done inside |
| Return value | "Hello Riya" | what comes back out |
Variables declared inside a function are local to it. They are created when the function starts, deleted when it finishes, and can only be used from inside it:
// code here can NOT use carName
function myFunction() {
let carName = "Volvo";
// code here CAN use carName
}
// code here can NOT use carName
console.log(carName);
total without interfering with each other. JS Scope covers the full rules.
function square(n) {
return n * n;
}
function hypotenuse(a, b) {
return Math.sqrt(square(a) + square(b));
}
console.log(hypotenuse(3, 4));
Small functions that each do one job can be combined into bigger ones. This is how large programs are built.
What does this log?
function double(n) {
return n * 2;
}
console.log(double(3) + double(4));
14. Each call is replaced by its return value: 6 + 8.Which is the best name for a function that checks whether a number is positive?
positive()check()isPositive()Positive_Number()is prefix tells the reader it answers true or false.What happens here?
function setup() {
let level = 1;
}
setup();
console.log(level);
ReferenceError: level is not defined. level is local to setup, and it was deleted when the function finished. To get a value out of a function, return it.showBanner() so it prints a line of 20 dashes, then call it three timesdouble(n) that returns n times 2, and print double(21)square(n), then write cube(n) that uses square(n) inside ittoCelsius() and use it directly inside a template string to print the temperature for 212°F