🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Web & Software Development › HTML, CSS, and JavaScript for Web Development › Lesson 8
TEC-WEB46-02 · Lesson 8 · 14 clock hours · lab

JavaScript Functions, Arrays, and Objects

Objective. Students declare and invoke functions with parameters and return values, iterate over arrays using for loops and array methods, and create and access object properties to model structured data.

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

JavaScript Functions

A function is a named, reusable block of code that performs a specific task. Defining a function does not run it; you must invoke (call) it separately. The most common syntax uses the `function` keyword:

```js

function greet(name) {

return 'Hello, ' + name + '!';

}

console.log(greet('Maria')); // Hello, Maria!

```

The value inside the parentheses is a parameter — a placeholder for data the function receives. When you call the function and supply an actual value, that value is called an argument. The `return` statement sends a result back to wherever the function was called; without it the function returns `undefined`.

Arrow Functions

ES6 introduced a shorter syntax called an arrow function:

```js

const double = (n) => n * 2;

console.log(double(5)); // 10

```

Arrow functions work the same way for most everyday uses. If the body is a single expression, the result is returned automatically (implicit return). For multi-line bodies, use curly braces and an explicit `return`.

Parameters, Arguments, and Return Values

Functions can accept multiple parameters separated by commas. Always include an explicit `return` statement when you expect a value back — this is a habit that prevents hard-to-find bugs. Test every function with at least three different inputs in the browser console before considering it complete.

---

JavaScript Arrays

An array is an ordered list of values stored in a single variable. Each item has a numeric index starting at zero.

```js

const fruits = ['apple', 'banana', 'cherry'];

console.log(fruits[1]); // banana

```

Arrays have a `.length` property and many built-in methods that make common tasks easier.

Iterating with a for Loop

A classic `for` loop gives you full control:

```js

for (let i = 0; i < fruits.length; i++) {

console.log(fruits[i]);

}

```

Key Array Methods

| Method | What it does | Returns |

|---|---|---|

| `forEach` | Runs a function on each element; used for side effects | `undefined` |

| `map` | Transforms each element | New array, same length |

| `filter` | Keeps elements that pass a test | New array, same or shorter |

| `find` | Returns the first element that passes a test | Single element or `undefined` |

Example using a product dataset:

```js

const products = [

{ name: 'Keyboard', price: 45 },

{ name: 'Monitor', price: 320 },

{ name: 'Mouse', price: 25 }

];

// Filter products under $50

const budget = products.filter(p => p.price < 50);

// Map to a list of names only

const names = products.map(p => p.name);

// Find a specific item

const monitor = products.find(p => p.name === 'Monitor');

```

None of these methods modify the original array — they return a new one (except `forEach`). Always consult the MDN Array reference when you are unsure of a method's exact behavior; MDN is the authoritative, free documentation for web APIs.

---

JavaScript Objects

An object groups related data and behavior under one name. You define an object literal using curly braces, with key–value pairs (also called properties):

```js

const student = {

name: 'Jordan Lee',

courses: ['HTML', 'CSS', 'JavaScript'],

gpa: 3.7,

isEnrolled: true

};

```

Access a property with dot notation (`student.name`) or bracket notation (`student['name']`). Bracket notation is required when the key is stored in a variable or contains special characters.

Getter-Style Functions

A getter-style function reads object data and formats it for output. It is a regular function — not a built-in JavaScript getter — that accepts an object as an argument and returns a formatted string or computed value:

```js

function getStatus(s) {

return s.name + ' — GPA: ' + s.gpa + ', Enrolled: ' + s.isEnrolled;

}

console.log(getStatus(student));

```

JSDoc Comments

JSDoc is a standard comment format that describes what a function does, its parameters, and its return value. It improves readability and is recognized by many editors for auto-complete hints:

```js

/**

*/

function getStatus(s) {

return s.name + ' — GPA: ' + s.gpa;

}

```

---

Working Safely in a Development Environment

Although web development does not involve heavy physical hazards, professional practices still protect you and your work:

Keeping these habits from day one builds professionalism that employers notice.

Key terms10

FunctionA named, reusable block of code that can accept input through parameters and return a value using the return statement.
ParameterA named placeholder declared in a function definition that receives the value passed in when the function is called.
Return statementThe JavaScript keyword that ends a function's execution and sends a value back to the caller; without it a function returns undefined.
ArrayAn ordered, zero-indexed list of values stored in a single variable, with built-in methods for iteration and transformation.
Array methodA built-in function attached to every array, such as map, filter, forEach, and find, used to process or transform array elements.
Object literalA JavaScript value defined with curly braces containing key–value pairs (properties) that group related data under one name.
Dot notationThe syntax object.property used to read or write a specific property of a JavaScript object.
JSDocA standard comment format using /** */ blocks that documents a function's purpose, parameters, and return value for developers and editor tools.
Arrow functionA compact ES6 function syntax written with => that implicitly returns a single expression or uses a block body with an explicit return.
IndexThe zero-based numeric position of an element within an array, used to access that element with bracket notation (e.g., arr[0]).

Worked examples3

1. Write a function that converts a temperature in Celsius to Fahrenheit and test it with 0 °C, 100 °C, and -40 °C.
  1. Recall the formula: F = (C × 9/5) + 32.
  2. Declare a function with one parameter (celsius) and compute the result inside the body.
  3. Add an explicit return statement so the caller receives the converted value.
  4. Test: celsiusToFahrenheit(0) → (0 × 9/5) + 32 = 0 + 32 = 32.
  5. Test: celsiusToFahrenheit(100) → (100 × 9/5) + 32 = 180 + 32 = 212.
  6. Test: celsiusToFahrenheit(-40) → (-40 × 9/5) + 32 = -72 + 32 = -40.
Answer: function celsiusToFahrenheit(celsius) { return (celsius * 9 / 5) + 32; } // Results: 32, 212, -40
2. Write a function that applies a percentage discount to a price and returns the discounted price rounded to two decimal places. Test with $200 at 10%, $50 at 25%, and $99 at 0%.
  1. The discounted price = price × (1 - discount/100).
  2. Declare a function with parameters price and discountPercent.
  3. Compute: discounted = price * (1 - discountPercent / 100).
  4. Return the result rounded to two decimal places using .toFixed(2) — note toFixed returns a string, which is acceptable for display.
  5. Test: discountPrice(200, 10) → 200 × 0.90 = 180.00.
  6. Test: discountPrice(50, 25) → 50 × 0.75 = 37.50.
  7. Test: discountPrice(99, 0) → 99 × 1.00 = 99.00.
Answer: function discountPrice(price, discountPercent) { return (price * (1 - discountPercent / 100)).toFixed(2); } // Results: '180.00', '37.50', '99.00'
3. Given an array of product objects, use filter to find all products with a price less than $50, then use map on the filtered result to produce an array of just the product names.
  1. Start with the array: [{ name: 'Keyboard', price: 45 }, { name: 'Monitor', price: 320 }, { name: 'Mouse', price: 25 }].
  2. Call .filter() with an arrow function that returns true when p.price < 50.
  3. Filter result: [{ name: 'Keyboard', price: 45 }, { name: 'Mouse', price: 25 }].
  4. Chain .map() — or call it on the filtered array — with an arrow function that returns p.name.
  5. Map result: ['Keyboard', 'Mouse'].
  6. Log the result to confirm it matches the expected output.
Answer: const products = [ { name: 'Keyboard', price: 45 }, { name: 'Monitor', price: 320 }, { name: 'Mouse', price: 25 } ]; const budgetNames = products .filter(p => p.price < 50) .map(p => p.name); // Result: ['Keyboard', 'Mouse']

The math in this lesson1

Learners code and test F = (C x 9/5) + 32, checking 0 C = 32 F and 100 C = 212 F.
F-IF.2
In class: Function-writing lab: students write eight functions of increasing complexity (e.g., Celsius-to-Fahrenheit converter, word-count checker, discount calculator) with explicit return statements and test each in the browser console. · Array methods workshop: working from MDN reference documentation, students use forEach, map, filter, and find to transform a provided array of product objects — filtering by price, mapping to a name list, and finding a specific item — then log results. · Object modeling exercise: students design a JavaScript object literal representing a student record (name, courses array, GPA, isEnrolled boolean), write getter-style functions to format and return data from it, and explain the structure in inline JSDoc comments.
Materials: VS Code, Chrome DevTools console, MDN Array reference, MDN Functions guide, provided product dataset as a JS array literal, JSDoc reference
Check: Instructor runs the submitted JS file in Node.js or the browser console; all eight functions return correct values for three test inputs each, and array method results match expected output; pass mark 80% of all test cases correct.

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

CompTIA ITF+ — Software Development Concepts
1. What does a JavaScript function return when no return statement is present?
PCEP Python — Programming Essentials (JavaScript analogue: data structures and iteration)
2. Which array method creates and returns a NEW array of the same length by applying a transformation function to every element?
PCEP Python — Programming Essentials (string and collection operations)
3. A student writes the function below. What value does calling wordCount('hello world') return? function wordCount(str) { const words = str.split(' '); return words.length; }
CompTIA ITF+ — Software Development Concepts
4. In the object literal below, which line of code correctly reads the student's GPA using dot notation? const student = { name: 'Alex', gpa: 3.5, isEnrolled: true };
PCEP Python — Programming Essentials (data structures and iteration concepts)
5. Which array method should you use when you want to retrieve only the FIRST element in an array that satisfies a condition, not all matching elements?
PCEP Python — Programming Essentials (arithmetic and functions)
6. A developer runs discountPrice(150, 20) using this function: function discountPrice(price, discountPercent) { return (price * (1 - discountPercent / 100)).toFixed(2); } What is the return value?
CompTIA ITF+ — Software Development Concepts
7. What is the primary purpose of a JSDoc comment block written above a function?
CompTIA Linux+ — System Operations and Maintenance
8. On a Linux system, a developer wants to run a JavaScript file called lab.js using Node.js from the terminal. Which command is correct?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.