Javascript Functions

Table of contents

In JavaScript, a function is a block of code that can be defined and then called by name. Functions allow you to reuse code and can be used to perform a specific task.

Here is an example of a simple function in JavaScript:

function greet(name) {
  console.log('Hello, ' + name + '!');
}

greet('John'); // Outputs: "Hello, John!"

In this example, the greet function is defined with a single parameter called name. When the function is called, it logs a greeting to the console using the value of the name parameter.

Functions can also have multiple parameters and can return a value using the return statement. Here is an example of a function with multiple parameters and a return value:

function add(x, y) {
  return x + y;
}

let sum = add(10, 20); // sum is 30

In this example, the add function has two parameters, x and y, and returns the sum of these two values. When the function is called with the arguments 10 and 20, the sum the variable is assigned the value 30.

Types Of Functions:

There are several types of functions in JavaScript:

  1. Function Declarations: These are functions that are defined with the function keyword followed by the function name, a list of parameters in parentheses, and a function body. Function declarations are hoisted, which means that they are moved to the top of the code at runtime, so they can be called before they are defined.

  2. Function Expressions: These are functions that are defined as part of a larger expression. They can be named or anonymous. Function expressions are not hoisted, so they cannot be called before they are defined.

  3. Arrow Functions: These are a shorter syntax for defining function expressions. They are always anonymous and use the => syntax to define the function. Arrow functions are not hoisted.

  4. Generator Functions: These are functions that can be paused and resumed during their execution. They are defined using the function* syntax and can be paused using the yield keyword.

  5. Async Functions: These are functions that return a promise and can be used to perform asynchronous tasks. They are defined using the async keyword and can use the await keyword to wait for a promise to resolve.

// Function Declaration
function greet(name) {
  console.log('Hello, ' + name + '!');
}

// Function Expression (Named)
let add = function addNumbers(x, y) {
  return x + y;
};

// Function Expression (Anonymous)
let multiply = function(x, y) {
  return x * y;
};

// Arrow Function (Anonymous)
let divide = (x, y) => {
  return x / y;
};

// Generator Function
function* countDownFrom(n) {
  while (n > 0) {
    yield n;
    n--;
  }
}

// Async Function
async function getData() {
  let response = await fetch('https://example.com/data');
  let data = await response.json();
  return data;
}