JS Startup

Challenges, Tips & Tricks & Tutorials

JavaScript Quiz – Find out the array length after flat method

JavaScript Quiz – Find out the array length after flat method

Array flat method –

Array.flat([depth]) allows us to flatten a nested array up to defined depth in an array flat method. So, an array that stores multiple types of elements in which array is one of them.

So, Array inside an array as an element is called a nested array. To bring them on one level. The Array.flat() is used. The parameter is also passed to the flat method, to define the depth.

Want to know more about JavaScript Array flat method.

Question –

In this javascript quiz, you need to find out the javascript array length after using the javascript Arra.flat() method to flatten a nested array.

Let’s begin with declaring an javascript array using let keyword.

And array contain a some numeric element and array element too.

Then, we check the length of the array before using a javascript Array.flat() to an array variable. So, it’s output is 3.

Now, we create another variable flatArray. In which we assign array with applying a flat(1) and passing 1 as a parameter.

Fun part begin here, as array is an reference type.

So, what should be the array length of the array and flatArray variable after using the javascript array.flat(1)?

Find out the array length after a javascript array flat method

Answer – 3, 6

Click To Run code

Explanation –

Now, you know the answer is 3, 6. But Why ?

So, we are passing an array with Array.flat(1) to flatArray variable. And the important thing, we are passing 1 to flat method as depth.

So, it only flatten an array one level nested mean. It work only on

[2, 3, [4], 5]

But not on – [4].

After flatten an array one level nested. The flatArray value be like –

[1, 2, 3, [4], 5, 6]

So, it’s length increases and becomes 6. Now, as the Array.flat(1) creates a new array with sub-element. So, no referenced pass to flatArray variable.

That’s why array variable still the same. which is 3.

Check out our other javascript quiz – 

  1. DOES DELETE OPERATOR REALLY WORK ON THE PRIMITIVES
  2. DID THE OBJECT ASSIGN METHOD REALLY PASS REFERENCE

Conclusion

To participate in our javascript quiz or challenges, tutorial, tips & tricks make sure to join our jsstartup newsletter. So, you can able to participate in our daily challenges & learn the javascript concept.

And last but not the least, don’t forget to like, comment and share. It gives us a morale boost to remain to continue. Also, join our Facebook Page

If you have any questions, please feel free to ask me in the comment section and also let me know if you have any suggestions. As suggestions are always welcome.

Leave a Reply

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

Back to top
7 Shares
Share via
Copy link