Skip to content

Functions

Function Definition

// Defining the function:
function sum(num1, num2) {
  return num1 + num2;
}

// Calling the function:
sum(3, 6); // 9

Anonymous Functions

// Named function
function rocketToMars() {
  return "BOOM!";
}

// Anonymous function
const rocketToMars = function () {
  return "BOOM!";
};

Arrow Functions (ES6)

With two arguments

const sum = (param1, param2) => {
  return param1 + param2;
};
console.log(sum(2, 5)); // => 7

With no arguments

const printHello = () => {
  console.log("hello");
};
printHello(); // => hello

With a single argument

const checkWeight = (weight) => {
  console.log(`Weight : ${weight}`);
};
checkWeight(25); // => Weight : 25

Concise arrow functions

const multiply = (a, b) => a * b;
// => 60
console.log(multiply(2, 30));

Arrow function available starting ES2015

return Keyword

// With return
function sum(num1, num2) {
  return num1 + num2;
}

// The function doesn't output the sum
function sum(num1, num2) {
  num1 + num2;
}

Calling Functions

// Defining the function
function sum(num1, num2) {
  return num1 + num2;
}

// Calling the function
sum(2, 4); // 6

Function Expressions

const dog = function () {
  return "Woof!";
};

Function Parameters

// The parameter is name
function sayHello(name) {
  return `Hello, ${name}!`;
}

Function Declaration

function add(num1, num2) {
  return num1 + num2;
}

Comments