JavaScript Functions
A function is a block of code with a name, that you can run many times. Functions make code shorter and easier to reuse.
Function declaration
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Robin"));
console.log(greet("Maria"));
Output of the above program is
Hello, Robin!
Hello, Maria!
nameis a parameter, the value you pass when you call is an argument.returnsends a value back and stops the function. Without it the function returnsundefined.
Default parameters
function greet(name = "Guest") {
return "Hello, " + name;
}
console.log(greet());
console.log(greet("Asha"));
Output of the above program is
Hello, Guest
Hello, Asha
Function expression
A function can be stored in a variable.
const add = function (a, b) {
return a + b;
};
console.log(add(2, 3));
Output of the above program is
5
Unlike a function declaration, a function expression is not hoisted, so you must define it before you call it.
Rest parameters
function total(...numbers) {
let sum = 0;
for (const n of numbers) sum += n;
return sum;
}
console.log(total(1, 2, 3, 4));
Output of the above program is
10
Functions as values (callbacks)
In JavaScript a function is a value. You can pass it to another function. This is called a callback.
function repeat(times, action) {
for (let i = 1; i <= times; i++) {
action(i);
}
}
repeat(3, function (n) {
console.log("Round " + n);
});
Output of the above program is
Round 1
Round 2
Round 3
Summary
- Declare with
function name() { }and call withname(). - Use
returnto give a value back. - Parameters can have default values or collect all arguments with
.... - Next: Arrow Functions.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |