Introduction

A function declaration is a way to define a named function in JavaScript. Functions are one of the fundamental building blocks in JavaScript, allowing you to encapsulate code for reuse and organization.

Syntax

The syntax for declaring a function is straightforward. Here's the basic form:

function functionName(parameters) {
  // function body
}

Components

NOTES:

  • function The keyword used to declare a function.
  • functionName The name of the function, used to call it.
  • parameters Optional. Comma-separated list of input parameters.
  • function body The code to be executed when the function is called.

Examples

Basic Function Declaration

script.js
function greet() {
  console.log("Hello, World!");
}

// Calling the function
greet(); // Output: Hello, World!

Function with Parameters

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

// Calling the function
console.log(add(2, 3)); // Output: 5

Function with Default Parameters

script.js
function multiply(a, b = 1) {
  return a * b;
}

// Calling the function
console.log(multiply(5)); // Output: 5 (5 * 1)
console.log(multiply(5, 2)); // Output: 10 (5 * 2)

Hoisting

Function declarations are hoisted to the top of their scope, meaning you can call the function before it is defined in the code.

Example of Hoisting

hoisting.js
console.log(square(5)); // Output: 25

function square(n) {
  return n * n;
}

NOTES:

  • Hoisting allows functions to be used before they are declared. This can make the code more flexible but can also lead to confusion if not used carefully.

Scope

Functions have their own scope, meaning variables declared within a function are not accessible outside of it.

scope.js
function sayHello() {
  var message = "Hello!";
  console.log(message); // Output: Hello!
}

sayHello();
console.log(message); // Error: message is not defined

NOTES:

  • Local ScopeVariables declared inside a function are local to that function.
  • Global ScopeVariables declared outside any function are in the global scope.

Parameters and Arguments

Parameters

Parameters are placeholders in the function definition.

parameters.js
function example(param1, param2) {
  console.log(param1, param2);
}

Arguments

Arguments are the actual values passed to the function when called.

arguments.js
example(1, 2); // Output: 1 2

Rest Parameters

Rest parameters allow you to represent an indefinite number of arguments as an array.

rest-parameters.js
function sum(...numbers) {
  return numbers.reduce((acc, num) => acc + num, 0);
}

console.log(sum(1, 2, 3, 4)); // Output: 10

NOTES:

  • Rest ParametersUse rest parameters to handle functions with an unknown number of arguments.
  • Default ParametersProvide default values for parameters to avoid undefined values.

Return Values

Functions can return a value using the return statement.

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

let result = subtract(10, 5);
console.log(result); // Output: 5

NOTES:

  • Return StatementThe return statement ends function execution and specifies a value to be returned.

Best Practices

NOTES:

  • Use Descriptive NamesFunction names should clearly describe what they do.
  • Keep Functions SmallEach function should perform a single task.
  • Avoid Side EffectsFunctions should avoid modifying global variables or outputting directly to the console.
  • Use Default ParametersProvide default values for parameters to handle unexpected undefined values.
  • KDocument FunctionsUse comments or documentation to describe the purpose and usage of functions.

Example of Best Practices

best-practices.js
/**
 * Calculate the area of a rectangle.
 *
 * @param {number} width - The width of the rectangle.
 * @param {number} height - The height of the rectangle.
 * @returns {number} - The area of the rectangle.
 */
function calculateArea(width, height) {
  return width * height;
}

COMMON MISTAKES:

  • Not Using return: Forgetting to use the return statement when a value is expected.
  • Overusing Global Variables: Relying too much on global variables can lead to conflicts and bugs.
  • Not Handling Edge Cases: Failing to handle edge cases, such as missing arguments or invalid input.
  • Ignoring Function Scope: Misunderstanding the scope of variables can lead to unexpected behavior.

Example of Common Mistake

common-mistake.js
// Mistake: No return statement
function incorrectAdd(a, b) {
  a + b;
}

console.log(incorrectAdd(2, 3)); // Output: undefined

Things to Know

  • Function Hoisting Function declarations are hoisted to the top of their scope.
  • Scope Relying too much on global variables can lead to conflicts and bugs.
  • Parameters vs. Arguments Parameters are in the definition; arguments are in the call.
  • Return StatementEnds function execution and specifies a value to return.