JavaScript + Node.js track

Lesson 05 · Part 1: Basics

Function Fundamentals

Declarations, expressions, parameters, return values, scope and default values

Part 1: Basics3 min readFree lesson

Step: Basics | Player: 04_Control statement

Learning Objectives

  • You can write function declarations, function expressions, and arrow functions.
  • The default value of the parameter and the remaining parameters (rest) can be used.
  • Can explain the difference between argument and parameter.
  • Distinguish between function scope and block scope.
  • Understand the concept of pure function.

1. Function declaration vs expression vs arrow

Function declarations can be hoisted and called from above. Expressions and arrow functions can be used after they are assigned to variables. Arrow functions are short and do not have their own this , making them suitable for callbacks.

function add(a, b) { return a + b; }     //declaration
const sub = function (a, b) { return a - b; }; //expression
const mul = (a, b) => a * b;             //arrow

2. Parameters and arguments

You can specify default values for parameters and receive variable arguments with ...rest.

function greet(name = "friend") {
  return `Hello, ${name}!`;
}
function sum(...nums) {
  return nums.reduce((a, b) => a + b, 0);
}

3. Return and side effects

The function explicitly returns a value of return; if not, it is undefined. A function that always returns the same result given the same input and does not change the external state is called a "pure function."

//pure
const square = (x) => x * x;

//Impure: change of external state
let counter = 0;
const tick = () => { counter += 1; };

4. Scope

Variables are visible only within the block in which they are declared. let/const is a block scope and var is a function scope. Referencing an outer variable inside a function is called a closure (more on this in the next step).

function outer() {
  const a = 1;
  if (true) {
    const b = 2;
    console.log(a, b); // 1 2
  }
  // console.log(b); // ReferenceError
}

Core example

file Contents covered
01_declaration.js Function declarations and hoisting
02_expression.js Function expressions and arrow functions
03_params.js Defaults, remaining parameters, destructuring
04_scope.js Block/Function Scope and variable access range

⚠️ Common Mistakes

  1. In an arrow function, a bug is created by forgetting that this is an external this and defining it as a method.
  2. When passing null, forgetting that the default parameter value is applied only to undefined.
  3. If you omit return and do not know that undefined is returned.
  4. Missing parentheses when returning an object literal directly from an arrow function (() => ({ a: 1 })).
  5. When a function secretly changes external variables, creating a bug that is difficult to trace.

❓ Frequently Asked Questions (FAQ)

Q1. Which should I use: a declaration or an expression? A. The declaration for the utility defined at the top of the module is easy to read, and the callback/local function has concise arrows.

Q2. What if there are too many arguments? A. Bundle them into an object. Like function create({ name, age, role }) { ... }, it utilizes structural decomposition.

Q3. Are functions also values? A. Yes. You can assign it to a variable, pass it as an argument to another function, and return it as a result. These are called "first-class functions".

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

src/01_declaration.jsJavaScript
/** Function declarations are hoisted and can be called even before definition.*/
console.log("3 + 4 =", add(3, 4));

function add(a, b) {
  return a + b;
}

/** Find the area of the square.*/
function area(w, h) {
  return w * h;
}
console.log("area(5,6) =", area(5, 6));
src/02_expression.jsJavaScript
/** Compare function expressions and arrow functions.*/
const sub = function (a, b) {
  return a - b;
};

const mul = (a, b) => a * b;

//When returning an object in a single line body, surround it with parentheses.
const wrap = (x) => ({ value: x });

console.log(sub(10, 3));
console.log(mul(4, 5));
console.log(wrap(42));
src/03_params.jsJavaScript
/** Use default values, remaining parameters, and destructuring together.*/
function greet(name = "friend", greeting = "hello") {
  return `${greeting}, ${name}!`;
}

function sum(...nums) {
  return nums.reduce((acc, n) => acc + n, 0);
}

function describe({ name, age = "?" } = {}) {
  return `${name} (${age} years old)`;
}

console.log(greet());
console.log(greet("Ada", "Hi"));
console.log(sum(1, 2, 3, 4, 5));
console.log(describe({ name: "Linus" }));
src/04_scope.jsJavaScript
/** Check the difference between block scope and function scope.*/
function demo() {
  const outer = "outside";
  if (true) {
    const inner = "inside";
    console.log(outer, inner);
  }
  // console.log(inner); // ReferenceError
}
demo();

//A taste of closures: functions remember variables in the environment in which they are declared
function makeCounter() {
  let count = 0;
  return () => (count += 1);
}
const next = makeCounter();
console.log(next(), next(), next()); // 1 2 3

Assignment

homework_01.js

  • Write a function that takes the radius r and returns a { area, perimeter } object.
  • Use Math.PI, rounding to 2 decimal places (Number(x.toFixed(2))).

homework_02.js

  • Write a function average(...nums) that takes a random number of numbers and calculates the average.
  • If there are no arguments, 0 must be returned.
Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

homework_01.jsJavaScript
/** Returns the area and perimeter of the circle.*/
function circle(r) {
  const area = Math.PI * r * r;
  const perimeter = 2 * Math.PI * r;
  return {
    area: Number(area.toFixed(2)),
    perimeter: Number(perimeter.toFixed(2)),
  };
}

console.log(circle(1));
console.log(circle(5));
console.log(circle(10));
homework_02.jsJavaScript
/** Calculate the average of the numbers received as variable arguments.*/
function average(...nums) {
  if (nums.length === 0) return 0;
  const total = nums.reduce((acc, n) => acc + n, 0);
  return total / nums.length;
}

console.log(average());                  // 0
console.log(average(10));                // 10
console.log(average(1, 2, 3, 4, 5));     // 3
console.log(average(90, 80, 70));        // 80

Learn this lesson with a mentor

Work through the JavaScript + Node.js track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now