Overview
A function is a system that allows you to group specific processes together, give them a name, and call them whenever needed. Functions are a core building block of JavaScript programs. Their basic role is to receive arguments (inputs), perform a process, and return a value (output). This article explains how to declare functions using the function keyword, the behavior of the return statement, and the concept of unreachable code (dead code).
Specifications (Input/Output)
- Input: Arguments such as numbers or strings.
- Output:
- Execution results (calculated values or judgment results) printed to the console.
- Values returned to the caller via the
returnstatement.
Basic Usage
To define a function, use the syntax: function functionName(arguments) { processing }. You execute (call) the defined function by using functionName().
Syntax Points
- Arguments (Parameters): These are values passed into the function. You can specify multiple parameters by separating them with commas.
- return: This command ends the function’s process and returns a value to the place where the function was called. Any code written after a
returnstatement will not be executed.
Full Code (HTML / JavaScript)
HTML (index.html)
This is the basic HTML structure used to verify how functions work.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Function Basic Demo</title>
<script src="function-demo.js" defer></script>
</head>
<body>
<div class="container">
<h1>Please check the Console</h1>
<p>The results of the function execution are output to the log.</p>
</div>
</body>
</html>
JavaScript (function-demo.js)
This code demonstrates various patterns: basic functions, calculations, early returns, and unreachable code.
/**
* 1. Basic function definition and return value
* Receives an argument and returns the calculated result.
*/
function addTwo(number) {
const result = number + 2;
return result; // Returns the result to the caller
}
// Execute the function and check the result
const value1 = addTwo(10);
console.log(`Result of addTwo(10): ${value1}`); // 12
/**
* 2. Function with multiple arguments
* Adds three numbers together.
*/
function calcSum(a, b, c) {
return a + b + c; // You can return the result directly without a variable
}
console.log(`Result of calcSum(10, 20, 30): ${calcSum(10, 20, 30)}`); // 60
/**
* 3. Characteristics of the return statement (Unreachable Code)
* The function ends the moment 'return' is executed.
*/
function checkReturnBehavior() {
console.log("This line will be executed.");
return 100;
// IMPORTANT: The following line will never be executed (Dead Code)
console.log("This line will be ignored.");
}
const returnVal = checkReturnBehavior();
console.log(`Return Value: ${returnVal}`);
/**
* 4. Conditional branching and Early Return
* Returns different values based on conditions.
*/
function selectValue(a, b) {
// If 'a' is 100 or more, return 'a' immediately and exit
if (a >= 100) {
return a;
}
// This part only runs if the 'if' condition above was not met
return b;
}
console.log(`Result of selectValue(150, 50): ${selectValue(150, 50)}`); // 150
console.log(`Result of selectValue(10, 50): ${selectValue(10, 50)}`); // 50
/**
* 5. Practical example: Tax-inclusive price calculation
*/
function calcTaxPrice(price, taxRate) {
const total = price + (price * taxRate);
return total;
}
const myResult = calcTaxPrice(100, 0.1);
console.log(`Tax-inclusive price: ${myResult}`); // 110
Customization Points
- Naming Functions: Your code will be easier to read if you start function names with a verb (e.g.,
calculate,get,check,render). - Default Arguments: Since ES6, you can set initial values for arguments, such as
function calc(price, tax = 0.1). Iftaxis omitted when the function is called,0.1is used automatically.
Important Points
- Forgetting the return statement: If you forget to write
returnwhen you intend to return a value, the function will returnundefined. Always usereturnif you need the result of a calculation. - Unreachable Code: Processes written after a
returnstatement are never executed. Always place yourconsole.logfor debugging before thereturnstatement. - Variable Scope: Variables declared inside a function (like
const result) cannot be accessed from outside the function (Local Scope).
Advanced Usage
Converting to Arrow Functions
In modern JavaScript development, “arrow functions” are frequently used because they allow for shorter syntax compared to the function keyword.
// Traditional function definition
// function add(a, b) {
// return a + b;
// }
// Arrow function definition (ES6+)
const add = (a, b) => {
return a + b;
};
// If there is only one line of processing, you can omit 'return' and '{}'
const simpleAdd = (a, b) => a + b;
Summary
A function is the smallest unit of programming: it takes input, processes it, and provides output.
- Define with
functionand call with(). - Use
returnto return a value and end the process. - Code after
returnis not executed. Understanding these three principles allows you to organize logic and write reusable code.
