Smallest Common Multiple smallestCommons returns undefined

Tell us what’s happening:

Hi, I expect smallestCommons to return the value of the variable after the return statement, lcm. However, it returns undefined. The line before it executes and says that lcm is type number and has a value. Why is the function returning undefined despite it having a return statement and following expression?

Thanks!

Your code so far


function range(a, b) {
/* return an array of the numbers between a and b, inclusive */
const low = a < b ? a : b;
const high = a > b ? a : b;
let nums = [];
for (let i = low; i <= high; i++) {
  nums.push(i);
}
return nums;
}

function multiples_lt_n(x, n) {
let multiples = [];
for (let i = 1; ; i++) {
  let multiple = x * i;
  if (multiple > n) {
    break;
  }
  multiples.push(multiple)
}
return multiples;
}

function smallestCommons(arr) {
const divisors = range(arr[0], arr[1]);
const comMult = divisors.reduce((acc, n) => acc * n);
const allMults = divisors.map(n => multiples_lt_n(n, comMult));
let noSubArrs = allMults.reduce((acc, n) => acc.concat(n), []);
let comMults = new Set();
for (let i in noSubArrs) {
  if (allMults.every(arr => arr.includes(noSubArrs[i]))) {
    comMults.add(noSubArrs[i]);
  }
}
let comMultsArr = Array.from(comMults);
const lcm = comMultsArr.shift();
console.log(typeof lcm, lcm);
return lcm;
}

smallestCommons([1,5]);

Your browser information:

User Agent is: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:80.0) Gecko/20100101 Firefox/80.0.

Challenge: Smallest Common Multiple

Link to the challenge:

Hi, it doesn’t look like there is a return statement in your function smalestCommons. By default, if there is no return statement, then a function returns undefined.

I thought return is in the function scope. I have three left brackets { and three right ones }. The return statement is after the second and before the third bracket.

Ah, you are correct. I see it now. I always get confused when people don’t indent the function contents.

It looks defined to me?

Jeremy, you’re right. It is returning the number value. I misposted. It times out in other places. So I’m going to rework my solution. Thank you!