Javascript Destructing issue within a traditional for loop and a for of loop differences

Let say I have an array of points = [[1,3],[-2,2] which represent x, y coordinates.

I want to access these values (distances of two points) at the points [x,y]. I just can’t get my mind wrapped on how these two approaches are different.

Why do I have access to one hash maps value, and the next I received undefined?

function getDistances1(points) {
  const lookup = new Map(); 
  // Destructing with a for of
  for (const [x, y] of points) {
    let distance = Math.sqrt((x**2) + (y**2))
    lookup.set([x,y], distance)
  }

  // I won't have access to the value of the array when I try to retrieve the value from the hash map
  return lookup; 
}

function getDistances2(points) {
  const lookup = new Map(); 
  // Destructing with a traditional for loop
  for (let i = 0; i < points.length; i++) {
    // Destruct this way 
    const [x, y] = [...points[i]]
    let distance = Math.sqrt((x**2) + (y**2))
    lookup.set(points[i], distance)
  }
  // I have access to this points value 
  return lookup; // 
}
const coordinates = [[1,3],[-2,2]]
const distance1 = getDistances1(coordinates); 
const distance2 = getDistances2(coordinates);

console.log(distance2.get(coordinates[0])) //-> 3.1622776601683795  ; 
console.log(distance1.get(coordinates[0])) // undefined

Answer

The reason that getDistances1 doesn’t work is that you’re creating separate x and y variables here:

for (const [x, y] of points) {

and then creating a new array here:

lookup.set([x,y], distance)

But you’re trying to look up the information using the array that was in points. The information isn’t stored under that array, you’ve stored it under a new array instead.

You could do this (see *** comments):

function getDistances1(points) {
    const lookup = new Map(); 
    // Destructing with a for of
    for (const point of points) {    // *** Use the array from `points
        const [x, y] = point;        // *** Convenient destructuring
        let distance = Math.sqrt((x**2) + (y**2))
        lookup.set(point, distance); // *** Store keyed by the array
    }
  
    return lookup; 
}

Leave a Reply

Your email address will not be published. Required fields are marked *