Why You Shouldn't Nest Your Code

And how to get rid of nested code

Arnold Abraham
CodeX

--

Image Made by the Author via Canva.com

While nested code has some advantages, it is often considered difficult to read and an anti-pattern: "Flat is better than nested."

Now you may wonder how to write non-nested code. Linus Torvalds, for example, is highly against nesting. Actually, you are allowed to nest, but only until level 3.

Read on to experience why nesting beyond level 3 is a flaw of hell and a step-by-step guide to sanitize your nested code.

The Levels of Nesting

The acceptance threshold is reached once you get to level 4 of nesting.

Nesting code is when you add more inner blocks to a function. Each opening brace adds one nesting level. Here is an example that tries to print out any positive numbers of an array.

function printPositives(nums){
console.log(nums)
}

printPositives([10, 15, -15, -21])

It is currently 1 level deep and fails the objective 💁

To get our function working, let's add a loop to get 2 levels deep:

function printPositives(nums){
for(let n of nums){
console.log(n)
}
}

printPositives([10, 15, -15, -21])

--

--

Arnold Abraham
CodeX
Writer for

JavaScript, TypeScript and C#/.NET Tutorials/News/Best Practices by a German Software Engineer - Fun helps you to learn on the fly --> arnoldcode.com