DEV Community

loading...

Discussion on: Keeping Your Code Simple

Collapse
joelnet profile image
JavaScript Joel • Edited

In your example let lenX = str1.length; is confusing to me because it is declared outside of the reduce where str1 is not accessible.

was your intent to write it like this?

const longest = strs.reduce((str1, str2) => {
  const lenX = str1.length;
  const lenY = str2.length;

  return lenX >= lenY ? str1 : str2
}, '');

I also like how Nested Software broke out the reducer into it's own function.

Collapse
themightyt_v3 profile image
theMightiestT

it's accessible because of scope. a variable declared inside the reduce wouldn't be accessable outside its scope; however, the other way around is fine(ish). depends if it should be mutable or not

Collapse
joelnet profile image
JavaScript Joel

No. What i am saying is let lenX = str1.length will produce a null reference exception because str1 is not available outside the reducer.

Thread Thread
themightyt_v3 profile image
theMightiestT

yes sorry you're right... I misread it

Thread Thread
fc250152 profile image
Nando • Edited

imho the external assignment cannot however work ... i think that it isn't evaluated at each cycle of reduce ... or am I wrong ?