-1

the MDN page for the flatten() method has this snippet of code

(function flattenDeep(arr1){
   return arr1.reduce((acc, val) =>
    Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
})(arr1);

What I'd like to know is

  1. Why is the entire function encapsulated in ()?
  2. What does (arr1) after the function do?
  3. What is the name for the something ? doThis : orDoThis algorithm?
Optiq
  • 1,982
  • 1
  • 20
  • 49
  • https://developer.mozilla.org/en-US/docs/Glossary/IIFE & https://en.wikipedia.org/wiki/Immediately-invoked_function_expression – Mark May 20 '18 at 22:10
  • Please don't ask two questions at once. *Both* of these quesions have been asked here numerous times before. – Alnitak May 20 '18 at 22:13
  • And [Question mark and colon in JavaScript](https://stackoverflow.com/q/1771786/4642212), [What does this symbol mean in JavaScript?](https://stackoverflow.com/q/9549780/4642212) and [Expressions and operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators). Don’t ask multiple questions per post. – Sebastian Simon May 20 '18 at 22:13

1 Answers1

1

1.Why is the entire function encapsulated in ()?

Because it's a self-invoking function or an Immediately-Invoked Function Expression, or IIFE for short. It executes immediately after it’s created. A self-invoking expression is invoked (started) automatically, without being called.

2.What does (arr1) after the function do?

It's the parameter for your self-invoking function.

3.What is the name for the something ? doThis : orDoThis algorithm?

It's just ternary operator.

Mihai Alexandru-Ionut
  • 41,021
  • 10
  • 77
  • 103