JavaScript: JavaScript Functions

Last updated: 2026-10-13

Functions are reusable blocks of code — write once, use endlessly. Think of them as recipes: define the steps once, then follow them every time you cook. A programmer who doesn't use functions is like someone reinventing every dish from scratch — exhausting and error-prone.

Related Statements:setTimeout forEach filter return const let var map

1. What Is a Function?

A function "packages" a piece of logic, gives it a name, and lets you call it whenever needed:

HTML
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Calling Functions</title></head>
<body>
<div id="output"></div>
<script>
function sayHello() {
  document.getElementById('output').textContent += 'Hello!\n';
}

sayHello();
sayHello();
</script>
</body>
</html>

Benefits of functions:


2. Function Declaration vs Function Expression

There are two main ways to create functions:

HTML
<script>
// Function declaration
function greet(name) {
  return `Hello, ${name}!`;
}

// Function expression
let greet2 = function(name) {
  return `Hello, ${name}!`;
};
</script>

Key difference: function declarations are hoisted — you can call them before they appear in the code. Function expressions are not hoisted; you must define them first.

HTML
<script>
// Function declaration: call before definition — works fine
hello();  // Runs without error
function hello() { console.log('hi'); }

// Function expression: call before definition — error
// hi();     // TypeError: hi is not a function
// let hi = function() { console.log('hi'); };
</script>
⚠️ Note: Accessing a let variable before its declaration triggers a "temporal dead zone" (TDZ) error — not undefined. So always define function expressions before using them.


3. Parameters and Default Parameters

Functions accept external data through parameters:

HTML
<script>
function add(a, b) {
  return a + b;
}
add(1, 2);  // 3
</script>

Parameters you don't pass are undefined. ES6 introduced default parameters:

HTML
<script>
function greet(name, greeting = 'Hello') {
  return `${greeting}, ${name}!`;
}

greet('Alice');           // 'Hello, Alice!'
greet('Alice', 'Hi');    // 'Hi, Alice!'
</script>
💡 Tip: Place default parameters at the end of the list. Putting them first is pointless — callers can't skip them to pass later ones.


4. Return Values

return sends a result back to the caller and immediately stops the function:

HTML
<script>
function square(n) {
  return n * n;
}

let result = square(5);  // 25
</script>

A function without return (or with just return;) returns undefined.

HTML
<script>
function doNothing() {
  // no return
}
doNothing();  // undefined
</script>
⚠️ Note: A newline after return causes automatic semicolon insertion, making it return undefined:

return     // becomes: return; undefined
  obj;     // this line never executes

Fix: keep the return value on the same line, or wrap it in parentheses.


5. Arrow Functions (=>)

Arrow functions are a shorter syntax introduced in ES6:

HTML
<script>
// Regular function
let double = function(n) {
  return n * 2;
};

// Arrow function
let double2 = (n) => n * 2;

// Multiple statements require braces and explicit return
let greet = (name) => {
  let msg = `Hello, ${name}!`;
  return msg;
};
</script>

Syntax rules:

▶ Example: Basic Function Usage

▶ Try it Yourself

▶ Example: Simple Calculator

▶ Try it Yourself

6. Function Scope

Variables declared inside a function are local — they only exist within that function. This is scope:

HTML
<script>
function test() {
  let x = 10;    // local variable
  const y = 20;
  var z = 30;
}
test();
// console.log(x);  // ReferenceError: x is not defined
</script>

Functions can access outer variables (the foundation of closures), but the outer code cannot access variables inside a function:

HTML
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Function Scope</title></head>
<body>
<pre id="output"></pre>
<script>
let global = 'Global variable';

function show() {
  let local = 'Local variable';
  document.getElementById('output').textContent +=
    'Inside function — global: ' + global + '\n' +
    'Inside function — local: ' + local + '\n';
}
show();
document.getElementById('output').textContent +=
  'Outside function — global: ' + global + '\n' +
  'Outside function — local: not accessible (local variable)';
</script>
</body>
</html>
⚠️ Note: Assigning a variable inside a function without let/const/var creates a global variable — a common source of bugs. Always declare variables with let or const.

▶ Example: Scope Demo

▶ Try it Yourself

7. Introduction to Callbacks

JavaScript lets you pass a function as an argument to another function — the passed-in function is called a callback:

HTML
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Callbacks</title></head>
<body>
<pre id="output"></pre>
<script>
function processArray(arr, callback) {
  for (let item of arr) {
    callback(item);
  }
}

let names = ['Alice', 'Bob', 'Charlie'];
processArray(names, function(name) {
  document.getElementById('output').textContent += 'Hello, ' + name + '\n';
});
</script>
</body>
</html>

You've already used callbacks — the arguments to forEach, map, and filter are all callback functions:

HTML
<script>
// The anonymous function here is a callback
[1, 2, 3].forEach(function(n) {
  console.log(n);
});

// Arrow functions make it more concise
[1, 2, 3].forEach(n => console.log(n));
</script>
💡 Tip: Callbacks are the soul of JavaScript. Event handlers, timers, and network requests all rely on the callback mechanism. For now, just remember: "a function can be passed as an argument." We'll go deeper later.

▶ Example: Callbacks in Action

▶ Try it Yourself

Related Statements:setTimeout forEach filter return const let var map

❓ FAQ

Q What's the difference between arrow functions and regular functions?
A Besides shorter syntax, arrow functions don't have their own this — they inherit it from the surrounding scope. When you need this to refer to the current object (in methods or event handlers), use a regular function. For simple utility functions, arrow syntax works great.
Q Can a function return multiple values?
A Not directly, but you can return an array or object and destructure it: function getInfo() { return [name, age]; } — then call with let [name, age] = getInfo().
Q What if I have too many parameters?
A When you have more than 3 parameters, consider using an object: function createUser({ name, age, city }) {} — call it with createUser({ name: 'Alice', age: 20, city: 'NYC' }). Order doesn't matter, and it's much more readable.

📖 Summary

📝 Exercises

  1. Write a function isEven(n) that returns true if a number is even, false otherwise. Test it with multiple values on the page.
  2. Write a function formatPrice(price) that takes a number and returns a formatted price string (e.g., formatPrice(9.9) returns "$9.90"). Use arrow function syntax.
  3. Build a "greeting generator": use a callback function that takes an array of names and a greeting function, then display personalized greetings for each person on the page.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏