This thread will demonstrate an easy way to write recursive functions
The recursion will so be compared to a for loop for familiarity
Tail Calls and Performance discussed later, Syntax Only!
gist/theme at end 👇
#javascript
![](https://pbs.twimg.com/media/ENnzDM2UcAAPAl-.jpg)
In recursion, it can be easier to set a default value. Pass `i` again when calling `loop` on the `return` line
#javascript #code #dev #es6
![](https://pbs.twimg.com/media/ENnzDeHUwAAkghu.jpg)
Like a for loop, add the break before you write your code. This will prevent infinite looping.
Notice how the for loop is a "continue" and the recursion uses a "break". That means the condition must be flipped for recursion
#javascript #nodejs
![](https://pbs.twimg.com/media/ENnzDzFUcAAlPSb.jpg)
Like the for loop, this is considered the base for recursion. This should be completed before writing your code.
Instead of `i++` (mutation), the increment happens in the `return loop(i + 1)`.
#javascript #nodejs #es6
![](https://pbs.twimg.com/media/ENnzEEDVAAA--3h.jpg)
A for loops inputs are available in the scope. A recursions inputs should be function arguments.
These "input" function arguments should be added to the left of the `i`
Remember to pass them in the `return`
#javascript #dev #nodejs #es6
![](https://pbs.twimg.com/media/ENnzEWOUwAAKUSb.jpg)
A for loop's output will mutate a variable in the scope
A recursive function will return a new value
The output should be added between the inputs and `i`
Be sure to add `output` to both `return` statements!
#javascript #nodejs #es6 #dev #code #development
![](https://pbs.twimg.com/media/ENnzEqwVAAEvRbT.jpg)
Functions can be expressed in many ways. This code shows the function written as a function expression.
The code is using `concat`, which is fine for small arrays and concise code, but won't work well for large arrays.
#javascript #nodejs #dev #es6 #code
![](https://pbs.twimg.com/media/ENnzE_JUEAAZtWw.jpg)
When concise code AND performance are important, consider using an immutable library
This will let you write immutable code in a way that is also has performance
#javascript #nodejs #code #dev #es6 #development
![](https://pbs.twimg.com/media/ENnzFSJUcAAwx96.jpg)
![](https://pbs.twimg.com/media/ENnzFSIVUAEA9fi.png)
Editor: VSCode
Font: FiraCode (with ligatures)
Theme: marketplace.visualstudio.com/items?itemName…
Cheers!🍻🍻🍻
#javascript #es6 #nodejs #code #dev #development #programming
Cheers! 🍻