Even More JavaScript

Joel Ross
Autumn 2026 (B)

View of the Day

  • Quiz 2 Frequently Missed Questions

  • Q&A

  • Functional Looping

  • Your choice!

    • Option 1: project draft work time!

    • Option 2: jump-start on more syntax

      • Arrow functions

      • Destructuring

Quiz 2: Frequently Missed Questions

Q&A

Functional Looping

Array Iteration

To iterate through each item in an array you can, use
the .forEach() method and pass it a callback to execute on each array item.

This function has a for loop in it already.

//Iterate through an array
const array = ['a','b','c'];
const printItem = function(item) {
   console.log(item);
}

array.forEach(printItem);

//more common to use anonymous function literal
array.forEach(function(item) {
   console.log(item);
});

callback

forEach() callbacks 

When using forEach() to loop through an array, the JavaScript interpreter will call the callback function passing it 3 arguments. (The last two are "optional", since all arguments in JavaScript can be ignored)

//Iterate through an array
const myArray = ['a','b','c'];

myArray.forEach(function(theItem, index, theArray) {
  //the item itself (e.g., `array[i]`` in a for loop)
  console.log(theItem); 

  //the index (e.g., `i` in a for loop). Rarely used.
  console.log(index); 

  //the array (e.g., `array` in a for loop). Never used.
  console.log(theArray);
});

Mapping

function square(n) { //a function that squares a number
    return n*n;
}

const numbers = [1,2,3,4,5];  //an initial array

//transform the numbers using the square() function
const squares = []; //the transformed array
for(let i=0; i<numbers.length; i++) {
   const transformed = square(numbers[i]);
   squares.push(transformed); //add transformed to array
}
console.log(squares); // [1, 4, 9, 16, 25]

The .map() function applies the given callback function to each element in an array and returns a new array of the transformed values.

This function has a for loop in it already.

function square(n) { //a function that squares a number
    return n*n;
}

const numbers = [1,2,3,4,5];  //an initial array

//map the numbers using the `square` transforming function
const squares = numbers.map(square);




console.log(squares); // [1, 4, 9, 16, 25]




const numbers = [1,2,3,4,5];  //an initial array

//map the numbers using function literal (anonymous callback)
const squares = numbers.map(function(n) {
    return n*n;
})


console.log(squares); // [1, 4, 9, 16, 25]

this function does the for loop!

Practice

Define an array peopleNames that contains the names of 3 people (e.g., you and your neighbors).

 

Use the map() function to create a new array peopleGreetings containing strings "Hi _____!", where the _____ is the name of each person in the peopleNames array.

Filtering

The .filter() function applies the given callback function to each element in an array and returns a new array containing only those elements for which the callback returns true.

This function has a for loop in it already.

const numberArray = [3,1,4,2,5];

const isACrowd = array.filter(function(n) { 
   return n >= 3; //keep if >= 3
}); //returns [3,4,5]

Reducing

The .reduce() function uses the given callback function to aggregate (combine) the elements in the list into a single value. Similar to the summarize() function in R.

function link(accumulation, newItem) { //combines two strings
    const newAccumulation = accumulation + "->" + newItem;
    return newAccumulation;
}

const letters = ['a','b','c','d','e'];  //an initial array

let linked = ""; //an accumulated aggregate, start at ""
for(let i=0; i<letters.length; i++){
    linked = link(linked, letters[i]);
}
console.log(linked); //"->a->b->c->d->e"

Reducing

The .reduce() function uses the given callback function to aggregate (combine) the elements in the list into a single value. Similar to the summarize() function in R.

function link(accumulation, newItem) { //combines two strings
    const newAccumulation = accumulation + "->" + newItem;
    return newAccumulation;
}

const letters = ['a','b','c','d','e'];  //an initial array

const linked = letters.reduce(link, ""); //pass func, starting value



console.log(linked); //"->a->b->c->d->e"

map, filter, and reduce
explained with emoji 😂

[🐮, 🥔, 🐔, 🌽].map(cook)
  => [🍔, 🍟, 🍗, 🍿]

[🍔, 🍟, 🍗, 🍿].filter(isVegetarian)
  => [🍟, 🍿]

[🍔, 🍟, 🍗, 🍿].reduce(eat)
  =>  💩

💩

(Option 1)

Work Time!

The policy for this course projects:

  • ❌ Don't use AI tools for problem sets
  • ✅ You can use AI tools for projects:
    1. ⚠️ AI can do the "first pass", but you do the debugging part
      • Don't put code into the generator!
    2. ⚠️ You need to distinguish what work is the AI and what work is yours
      • AI-supported code committed separately through git
      • Written explanation of your human work ("project mastery reflection" assignment)

For full details, see the syllabus and the Gen AI in Projects Guidelines

Reminder: AI Policy

Action Items!

Action Items!

  • Finish task list for Week 5

  • Read: Chapter 14

    • We're skipping chapter 13

  • Problem Set 05 due Friday​

  • Project Draft 1 due Sunday

 

Next: Alternative JavaScript syntax

(Option 2)

More Syntax!

Arrow Functions

A shortcut syntax for declaring functions using =>

//normal function declaration
const foo = function(params) {
  return 'foo '+params;
}
//arrow function declaration (block body)
const foo = (params) => {
  return 'foo '+params;
}
//arrow function declaration (concise body)
const foo = (params) => 'foo '+params;

single expression implies return

//arrow function declaration (concise, no params)
const sayHello = () => console.log('Hello world!');

anonymous function assigned to a variable

Arrow Functions

Arrow functions are particularly nice for anonymous callback functions (literals), and in fact should always be used.

const array = [1,2,3]; //an array to work with

//normal function
array.map(function(num) {
  return num*2; //multiply each item by 2
});

//arrow syntax
array.map((num) => {
  return num*2; //multiply each item by 2
});

//concise body - ONLY FOR TINY EXPRESSIONS
//(better to avoid entirely)
array.map((num) => num*2);

const doggy = {
  name: "Fido",
  bark: () => console.log("woof")
}

Check your understanding

/* function declaration */
function myFunction(param1, param2) {
  return param1 + param2;
}

/* function literal */
const myFunction = function(param1, param2) {
  return param1 + param2;
}

/* arrow function */
const myFunction = (param1, param2) => {
  return param1 + param2;
}

/* arrow function (concise body) */
const myFunction = (param1, param2) => param1 + param2;

We now have 4 different ways to write functions. They all have different syntax, but do the same work.

Function Syntax

What do you think?

Code Style

Recommendation: don't use concise body syntax. Always include the explicit block.

  • It's easier to read (more clearly a function)
  • It's easier to modify (can add additional statements)
  • It's easier to debug (can add console logs)
/* Do this */
const exclaimed = stringArray.map((aString) => {
  return aString + "!!" //add exclamation points
})

/* Do not do this */
const exclaimed = stringArray.map((aString) => aString + "!!")

Destructuring

Destructuring assignment lets you assign (unpack) each value of an array or object into into separate variables in a single operation.

//destructuring arrays
const myArray = [1, 2, 3];
const [x, y, z] = myArray; //myArray elements to `x`, `y`, `z`
console.log(x); //=> 1;
console.log(y); //=> 2;
console.log(z); //=> 3;

//destructuring objects
const myObject = {a: 1, b: 2, c: 3};
const {a, b, c} = myObject; //myObject.a to a, etc.
console.log(a); //=> 1
console.log(b); //=> 2;
console.log(c); //=> 3;

Check your understanding

Destructuring Params

It's possible to destructure function parameters. This is commonly used in React (with object params)... but can make code maintenance harder.

//an example person object
const person = {name: 'Ada', height: 64, weight: 135}

//a function that expects a person object
function getBMI(personObj) {
  const height = person.height;
  const weight = person.weight;
  return 703*weight/(height*height);
}




const adaBMI = getBMI(person);
//implicit
const personObj = {
   name: 'Ada', height: 64, weight: 135
}
//implicit - destructured
const {height, weight} = {
   name: 'Ada', height: 64, weight: 135
}
//an example person object
const person = {name: 'Ada', height: 64, weight: 135}

//a function that expects a person object
function getBMI({height, weight}) {

  
  return 703*weight/(height*height);
}




const adaBMI = getBMI(person);
/* standard argument */
function getFullName(personObj) {
  return personObj.first + " " + personObj.last;
}

/* destructured argument */
function getFullName({first, last}) {
  return first + " " + last;
}

We now have 2 different ways to write function arguments. They all have different syntax, but do the same work.

Function Syntax

What do you think?

The policy for this course projects:

  • ❌ Don't use AI tools for problem sets
  • ✅ You can use AI tools for projects:
    1. ⚠️ AI can do the "first pass", but you do the debugging part
      • Don't put code into the generator!
    2. ⚠️ You need to distinguish what work is the AI and what work is yours
      • AI-supported code committed separately through git
      • Written explanation of your human work ("project mastery reflection" assignment)

For full details, see the syllabus and the Gen AI in Projects Guidelines

Reminder: AI Policy

Action Items!

Action Items!

  • Finish task list for Week 5

  • Read: Chapter 14

    • We're skipping chapter 13

  • Problem Set 05 due Friday​

  • Project Draft 1 due Sunday

 

Next: More alternative JavaScript syntax
            (React prep)

info340au26b-javascript-iii

By Joel Ross

info340au26b-javascript-iii

  • 25