HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to JavaScriptVariables (let / const)Data TypesOperatorsStringsArraysObjectsConditions (if / else)Loops (for / while)FunctionsArrow Functions (=>)Array Methods (map / filter / reduce)
REFERENCE
📖 Overview
🖥️ Output & Console
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array
🗂️ Object
🔁 Condition & Loop
🧩 Function
🔄 Type & Conversion
JavaScript›Functions

Functions

Defining functions with function, parameters, returning values with return, and default parameters.

Simple enough for a 5-year-old to understand

function and return

Example code
1
function square(x) {
Function that takes the input "x".
FunctionFunction that takes the input "x".
2
return x * x;
Return the result.
FunctionReturn the result.
3
}
End of function.
FunctionEnd of function.
4
console.log(square(5));
Call → 25
Output / InputCall → 25
FunctionOutput / Input
💡 Hint: If you don't write return, the function returns undefined.

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Write a function named addUp that adds two numbers and RETURNS the result; print the result of addUp(8, 9).

🎯 Expected output: 17

Loading editor…

About this topic

A function is giving a name to a piece of code that performs a task. It prevents repetition, makes code readable, and creates testable units. In JavaScript, functions are first-class values: they can be assigned to a variable, passed as a parameter to another function, and returned from a function.

This feature defines the character of JavaScript. You pass the code to run when a button is clicked as a function; when transforming an array, you provide the transformation as a function. Passing functions around like data is central to the daily use of the language.

What you will learn

  • defining a function with the function keyword
  • passing parameters and setting default values
  • returning values with return
  • the difference between a function declaration and a function expression
  • the concept of a callback function
  • the basics of closure logic

When to use?

If you are about to write a block of code for the second time, it is time to extract it into a function. Additionally, event listeners, timers, and array methods already expect functions; these make up a large portion of everyday code.

A function should do a single job and its name should describe that job. If its name contains "and", it should probably be split into two functions.

Common mistakes

Wrong

function add(a, b) {
  const sum = a + b;
}
console.log(add(2, 3) * 2);

The function calculates the result but does NOT RETURN IT; because there is no return, it returns undefined and the multiplication operation produces NaN. Every function that performs a calculation must return its result.

Correct

function add(a, b) {
  return a + b;
}
console.log(add(2, 3) * 2);

Wrong

function makeTag() {
  return
    "<p>text</p>";
}

JavaScript automatically adds a semicolon at the end of the return line; the value on the next line is never returned and the function gives undefined. The value to be returned must start on the SAME line as return.

Correct

function makeTag() {
  return "<p>text</p>";
}

Wrong

greet("Ada");
const greet = function (n) {
  return "Hello " + n;
};

A function expression defined with const cannot be called before definition; you get "ReferenceError: Cannot access 'greet' before initialization". Declarations made with the function keyword are hoisted, function expressions are not.

Correct

function greet(n) {
  return "Hello " + n;
}
greet("Ada");

Frequently asked questions

What is the difference between a function declaration and a function expression?

A declaration made with the function keyword is hoisted to the top of the file and can be called before the definition. A function expression assigned to a variable cannot be used until that line is reached. This difference is why people prefer using declarations to keep code readable from top to bottom.

What is a callback function?

It is a function passed as a parameter to another function and called by that function at an appropriate time. Code to run when a button is clicked, code to run when a request response arrives — these are all callbacks. It is the foundation of JavaScript's event-driven nature.

What is a closure?

It is a function's ability to access variables from its lexical scope even when it is called elsewhere. It is used to keep counters, store private state, and generate configurable functions. It seems abstract at first, but you use it constantly without realizing it while writing event listeners.

Summary

In JavaScript, functions can be passed around like data, which is the foundation of the language's event-driven nature. The two most common mistakes: forgetting to write return and putting the value to be returned on the next line — the second one silently returns undefined.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code