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
/**
- Returns a formatted status string for a student record.
- @param {Object} s - The student object.
- @param {string} s.name - Full name of the student.
- @param {number} s.gpa - Grade point average.
- @returns {string} Formatted status string.
*/
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:
- Save frequently and use version control. Lost code due to a crash is a real productivity hazard. Commit to Git before major changes.
- Never run untrusted code in your browser console or Node.js — malicious scripts can access local files or credentials.
- Protect sensitive data. Do not place real personal information (SSNs, passwords) in exercise files or public repositories. Use placeholder data in all labs.
- Ergonomics. Position your monitor at eye level, keep wrists neutral, and take short breaks to avoid repetitive strain injury — a recognized occupational hazard for programmers.
- Screen time. Follow the 20-20-20 rule: every 20 minutes, look at something 20 feet away for 20 seconds to reduce eye strain.
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.
- Recall the formula: F = (C × 9/5) + 32.
- Declare a function with one parameter (celsius) and compute the result inside the body.
- Add an explicit return statement so the caller receives the converted value.
- Test: celsiusToFahrenheit(0) → (0 × 9/5) + 32 = 0 + 32 = 32.
- Test: celsiusToFahrenheit(100) → (100 × 9/5) + 32 = 180 + 32 = 212.
- 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%.
- The discounted price = price × (1 - discount/100).
- Declare a function with parameters price and discountPercent.
- Compute: discounted = price * (1 - discountPercent / 100).
- Return the result rounded to two decimal places using .toFixed(2) — note toFixed returns a string, which is acceptable for display.
- Test: discountPrice(200, 10) → 200 × 0.90 = 180.00.
- Test: discountPrice(50, 25) → 50 × 0.75 = 37.50.
- 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.
- Start with the array: [{ name: 'Keyboard', price: 45 }, { name: 'Monitor', price: 320 }, { name: 'Mouse', price: 25 }].
- Call .filter() with an arrow function that returns true when p.price < 50.
- Filter result: [{ name: 'Keyboard', price: 45 }, { name: 'Mouse', price: 25 }].
- Chain .map() — or call it on the filtered array — with an arrow function that returns p.name.
- Map result: ['Keyboard', 'Mouse'].
- 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.
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.