Functions in JavaScript

What is Function?

Functions are an important concept in JavaScript, allowing you to wrap reusable blocks of code. They are a way to group together a set of statements to perform a specific task or return a value. They allow you to call that code whenever you need it, using a single command instead of typing out the same code multiple times. As a result your codebase become more organized, readable and maintainable.

Function Declaration

To define a named function in JavaScript, you use the 'function' keyword followed by the name of the function, a list of parameters enclosed in parentheses, and the JavaScript statements that define the function enclosed in curly brackets. This type of function can be called before the declaration in the code because JavaScript hoists function declarations to the top of their containing scope.

Here is the basic syntax:

// Function Declaration
function functionName(parameter1, parameter2, ...) {
  // Function body
  // Code to be executed
  return result; // Optional
}

Return statement: Optional. It specifies the value to be returned from the function. If omitted, the function returns undefined.

Function Invocation (Call)

To execute a function, use its name followed by parentheses containing arguments (if any).

// Function Call
functionName(arguments);

Arguments: Values passed to the function's parameters when it's called.

Function Parameters and Arguments

  • Parameters: Variables declared in the function's parameter list. They act as placeholders for the values that will be passed when the function is called.
  • Arguments: Actual values passed to the function when it is invoke, run or called (all 3 mean the same thing). You actually pass it the data, that will take place of the variables, those are called arguments.

People incorrectly use those terms interchangeably. One way to remember is that parameters are placeholders. The actual values that you pass in when calling a function are what are called argument.

// function definition
function calculateBill(billAmount, taxRate = 0.13, tipRate = 0.15) {
  // this is the function body
  console.log("Running Calculate Bill!!");
  const total = billAmount + billAmount * taxRate + billAmount * tipRate;
  return total;
}
 
// function call
const myTotal = calculateBill(150, 0.17, 0.13);
console.log(myTotal);

Here in the above example, the variables passed inside the paranthesis (billAmount, taxRate = 0.13, tipRate = 0.15) when declaring the functions are called Parameters and the actual values that are passed (100, 0.15, 0.15) when calling the function are called Arguments. Inside the paranthesis taxRate and tipRate are the Default Parameters.

Return Statement

A return statement specifies the value that a function will return after its execution. You can use it to pass a value back to the calling code. If a function does not have a return statement, it will return `undefined`.

function add(a, b) {
  return a + b;
}
 
const sum = add(2, 3);
console.log(sum); // Output: 5

Function Expression

A Function-Expression is a function that is assigned to a variable or a property of an object. This is called an anonymous function expression. Unlike with function declarations, function expressions are not hoisted, so they must be defined before they are called.

const sayHello = function() {
  console.log("Hello!");
};
 
sayHello(); // Output: Hello!

Arrow Function

An arrow function is a concise way to write a function in JavaScript. It uses the `=>` syntax and has a more compact syntax compared to regular function expressions. It does not have its own `this` binding and cannot be used as a constructor.

const sayHello = () => {
  console.log("Hello!");
};
 
sayHello(); // Output: Hello!

Function Scope

In JavaScript, variables declared within a function are considered local to that function and cannot be accessed outside of it. This concept is known as function scope. It means that variables defined within a function are not accessible outside of it.

function greet() {
  const message = "Hello!";
  console.log(message);
}
 
greet(); // Output: Hello!
console.log(message); // Throws an error

Anonymous Function

An anonymous function is a function without a name. It can be assigned to a variable or used as an argument to another function.

const sayHello = function() {
  console.log("Hello!");
};
 
sayHello(); // Output: Hello!

Named Function Expression

A named function expression is a function expression with a name. The name can be used within the function for recursive calls or to help with debugging.

const factorial = function fact(n) {
  if (n === 0 
 n === 1) {
    return 1;
  } else {
    return n * fact(n - 1);
  }
};
 
console.log(factorial(5)); // Output: 120

Default Parameters

Default parameters allow you to specify default values for function parameters. If an argument is not provided, the default value will be used instead.

function greet(name = "World") {
  console.log("Hello, " + name + "!");
}
 
greet("Alice"); // Output: Hello, Alice!
greet(); // Output: Hello, World!

Rest Parameters

Rest parameters allow you to pass an indefinite number of arguments to a function. Within the function, the rest parameters are treated as an array and can be manipulated using array methods.

function sum(...numbers) {
  let total = 0;
  for (let number of numbers) {
    total += number;
  }
  return total;
}
 
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(4, 5, 6, 7, 8)); // Output: 30

Key Takeaways

  • Function declarations and expressions are two ways to define functions in JavaScript.

  • Arrow functions provide a concise syntax for writing functions.

  • Parameters are defined in the function declaration, while arguments are passed to the function when it is called.

  • The return statement specifies the value that a function will return.

  • Variables declared within a function are considered local to that function and cannot be accessed outside of it.

  • Anonymous functions and named function expressions are useful in different scenarios.

  • Default parameters allow you to specify default values for function parameters.

  • Rest parameters allow you to pass an indefinite number of arguments to a function.

Comments

Popular posts from this blog

Mastering JavaScript Output: Communicating with Users

What is JIT compiler? Is JavaScript compiled or interpreted or both?

'for in' Loop