JavaScript Functions

Table of contents

No heading

No headings in the article.

In JavaScript, functions are reusable blocks of code that can be invoked to perform a specific task or calculate a value. Functions allow you to encapsulate code, make it modular, and improve code reusability. Here are a few examples of JavaScript functions:

  1. Function without Parameters:
function greet() {
  console.log('Hello, World!');
}

greet(); // Output: Hello, World!

In this example, the greet() function is defined without any parameters and it simply logs a greeting message to the console when invoked.

  1. Function with Parameters:
function multiply(a, b) {
  return a * b;
}

const result = multiply(5, 3);
console.log(result); // Output: 15

The multiply() function takes two parameters, a and b, and returns their product when invoked. In the example, we pass arguments 5 and 3 to the function, and it returns the result 15, which is then logged to the console.

  1. Arrow Function:
const square = (num) => {
  return num * num;
}

console.log(square(4)); // Output: 16

The arrow function syntax is a more concise way to define functions. In this example, the square arrow function takes a parameter num and returns the square of that number. We pass 4 as an argument to the function and it logs the result 16 to the console.

  1. Function as a Method:
const person = {
  name: 'John',
  age: 30,
  greet: function() {
    console.log('Hello, my name is ' + this.name);
  }
};

person.greet(); // Output: Hello, my name is John

In this example, the greet() function is defined as a method within the person object. The method accesses the name property of the object using this keyword and logs a greeting message to the console.

  1. Callback Functions:
function calculate(num1, num2, operation) {
  return operation(num1, num2);
}

function add(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}

console.log(calculate(5, 3, add)); // Output: 8
console.log(calculate(5, 3, subtract)); // Output: 2

In this example, the calculate() function takes two numbers and an operation as arguments. The operation is expected to be a function. We define the add() and subtract() functions, and then pass them as arguments to calculate() function along with numbers 5 and 3. The calculate() function invokes the operation function with the given numbers and returns the result.

These are just a few examples of JavaScript functions. Functions in JavaScript can have optional parameters, default parameter values, rest parameters, and can also be assigned to variables or stored in arrays and objects. They provide a powerful way to structure and organize code in JavaScript.