Function Definition and Parameter Passing

Main Topic: JavaScript

Core Syntax

Function Definition and Parameter Passing

Functions are fundamental to JavaScript, enabling code organization and reusable logic. A function is defined using the function keyword, followed by a function name and parentheses containing parameters. Parameters are variables that receive values passed to the function.

Function Definition

A function definition consists of the function keyword, a function name, and parentheses enclosing parameters. Parameters can be declared with default values, and functions can return values using the return statement.

Example:

function greet(name) {  
  console.log(`Hello, ${name}!`);  
}  
greet("Alice"); // Output: Hello, Alice!  

Functions can also omit parameters, as shown below:

function calculateArea() {  
  const radius = 5;  
  const area = Math.PI * radius * radius;  
  console.log(area);  
}  
calculateArea(); // Output: 78.53981633974483  

Parameter Passing

Parameters are passed to a function in the order they are declared. The type of parameter (value or reference) determines how the function handles the data.

By Value

When a parameter is passed by value, the function receives a copy of the value. This means changes to the parameter inside the function do not affect the original value.

Example:

function square(num) {  
  return num * num;  
}  
console.log(square(4)); // Output: 16  

By Reference

When a parameter is passed by reference, the function modifies the original value. This is common for mutable data types like objects or arrays.

Example:

function modifyArray(arr) {  
  arr.push(10);  
}  
const numbers = [1, 2, 3];  
modifyArray(numbers);  
console.log(numbers); // Output: [1, 2, 3, 10]  

Advanced Concepts

JavaScript supports rest parameters to handle multiple arguments as an array, and default parameters to provide fallback values.

Rest Parameters:

function sum(...numbers) {  
  return numbers.reduce((a, b) => a + b, 0);  
}  
console.log(sum(1, 2, 3, 4)); // Output: 10  

Default Parameters:

function greet(name = "Guest") {  
  console.log(`Hello, ${name}!`);  
}  
greet(); // Output: Hello, Guest!  

Practical Applications

Functions are essential for modular programming, data manipulation, and event handling. Proper parameter passing ensures data integrity and avoids unintended side effects.

Example:

function calculateTotal(price, tax = 0.07) {  
  return price * (1 + tax);  
}  
console.log(calculateTotal(100, 0.05)); // Output: 107.0  

Best Practices

  • Use descriptive function names.
  • Avoid mutating parameters; prefer returning values.
  • Use rest and default parameters for flexibility.

By mastering function definition and parameter passing, developers can write efficient, maintainable, and scalable JavaScript code.