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!

  • name is a parameter, the value you pass when you call is an argument.
  • return sends a value back and stops the function. Without it the function returns undefined.

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 with name().
  • Use return to 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
What are arrow functions in JavaScript?
What is the this keyword in JavaScript?
What is the difference between call, apply and bind?
What is the difference between debounce and throttle?
What is the difference between function declaration and function expression?
What is a closure in JavaScript?