Open-Source JavaScript Programming • Intermediate • Estimated study time: 45 minutes.
A function packages a computation or operation into a callable value. JavaScript functions can be assigned to variables, supplied to another function and returned from a function. The preceding objects lesson established how values and references behave; functions extend those concepts to reusable behavior and controlled state.
Prerequisites and learning objectives
Install a supported Node.js release and review variables and scope, control flow and arrays. By completion, learners can declare functions and supply arguments, use default parameters and return values, distinguish declarations from arrow expressions, pass a callback to an array operation, and create closures with independent state. All laboratory measurements are synthetic; do not use the exercise to control electrical equipment.
Parameters, arguments and return values
The MDN JavaScript functions guide distinguishes a function definition from a call. Parameters name inputs in the definition; arguments supply values at invocation. The return statement ends a call and supplies its result. A function without an explicit returned value produces undefined. Default parameters are applied when an argument is omitted or explicitly undefined, not when the argument is zero or null. A declaration can be available before its textual definition in an ordinary function or script scope, while a const-bound function expression cannot be used before initialization.
Arrow expressions and callbacks
An arrow expression produces a callable function value. An expression-bodied arrow implicitly returns its expression, while a brace-delimited body needs an explicit return to produce a result. Arrow functions also inherit the surrounding receiver binding rather than creating their own; they are not constructors and should not replace ordinary methods indiscriminately. See the arrow-function reference. A callback is a function supplied to other code for invocation. Array.filter invokes its callback for existing elements and returns a new array containing those for which the callback returns a truthy value. Callback invocation need not be asynchronous.
Lexical scope and closures
A closure retains access to bindings in its surrounding lexical environment. For example, a factory can create a local counter and return a function that increments it. The returned function continues accessing the same binding after the factory call ends. Separate calls to the factory create separate bindings. The MDN closures guide describes the relationship between functions and lexical environments. Capturing a binding does not automatically make a snapshot of its value; later updates can be observed by functions sharing the binding.
Laboratory: power calculation, filtering and state
The laboratory models ideal DC electrical power using the product of voltage and current, filters synthetic readings, and creates two independent counters. The finite-number guard rejects numeric strings rather than silently coercing them. It is a teaching example, not a complete electrical validation model; finite negative inputs remain permitted, and the function does not check whether the product overflows. Save the following complete program as lab.cjs:
'use strict';const assert = require('node:assert/strict');function watts(volts, amps = 1) { if (!Number.isFinite(volts) || !Number.isFinite(amps)) { throw new TypeError('Finite numbers required'); } return volts * amps;}const isAbove = (value, limit) => value > limit;function makeCounter(start = 0) { let count = start; return () => ++count;}const a = makeCounter();const b = makeCounter(10);assert.equal(watts(12, 2), 24);assert.equal(watts(12), 12);assert.equal(watts(12, 0), 0);assert.throws(() => watts('12', 2), TypeError);assert.deepEqual([20, 35, 40].filter(n => isAbove(n, 30)), [35, 40]);assert.deepEqual([a(), a(), b(), a(), b()], [1, 2, 11, 3, 12]);console.log('PASS 6 assertions');
Run the syntax check and then execute the CommonJS script using the following commands:
node --check lab.cjsnode lab.cjs
Node.js v22.16.0 completed the syntax check and produced the following output:
PASS 6 assertions
Engineering interpretation
The six assertions establish multiplication, default-argument behavior, preservation of zero, rejection of a string argument, callback filtering and counter independence. In the final assertion, counter A returns 1, 2 and 3 while counter B returns 11 and 12. Each call to makeCounter owns a different count binding. No global counter is needed. Functions can isolate calculations and state, but closures that retain large objects can extend their lifetime. Keep captured data limited to what the operation needs. For telemetry, define units and acceptable ranges explicitly; validate inputs and outputs, including overflow and missing values, before relying on calculated results.
Exercises and answer key
Exercise 1: Predict watts(12, undefined). Exercise 2: Predict watts(12, 0). Exercise 3: Explain why watts(’12’, 2) throws. Exercise 4: Modify the filter threshold to 35 and predict the resulting array. Exercise 5: Explain why two calls to makeCounter do not share count.
Answers: 1. 12 because the default current is 1. 2. 0 because zero is a supplied argument. 3. Number.isFinite rejects a string. 4. Only 40 remains because the comparison is strictly greater than 35. 5. Each factory invocation creates its own lexical environment with a separate local binding.
Conclusion
Functions make computational behavior reusable, callbacks compose operations, and closures enable controlled state without shared global variables. Choose explicit parameters, verify return values, avoid accidental coercion and test state isolation independently.
Editor’s Note: We volunteer daily to ensure the credibility of the information on this platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiatives, please scan the QR code below

For mobile scanning, open the article on another display and scan the QR code with a Bitcoin wallet. The voluntary donation amount is 5,000 sats. Verify the receiving address 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb before sending.
BitcoinVersus.Tech publishes technology and financial journalism for informational purposes and does not provide financial, investment, or legal advice.

Leave a Reply