View : 0

12/04/2026 18:16pm

JS2GO EP.37 Recursion vs Iteration in JavaScript and Go

JS2GO EP.37 Recursion vs Iteration in JavaScript and Go

#JS2GO

#Golang

#Go

#JavaScript

#Iteration

#Recursion

Every programmer has faced repetitive tasks such as:

  • Summing up a list of numbers
  • Calculating a factorial
  • Or generating a Fibonacci sequence

 

There are two main techniques to handle repetition in programming:

  • Recursion — a function that calls itself repeatedly
  • Iteration — using loops like for or while to repeat actions

 

Although both methods can produce the same results, they differ in performance, memory usage, and readability.

 

Let’s explore how JavaScript and Go implement these two approaches 👇

 

1. Recursion — Function Calling Itself

 

🔹 JavaScript: Recursion

function factorial(n) {
  if (n === 0) return 1;
  return n * factorial(n - 1);
}

console.log(factorial(5)); // Output: 120

 

Explanation:
factorial(5) keeps calling itself until it reaches factorial(0),
then returns values back up the call stack by multiplying each level.

 

Advantages:
✅ Simple and elegant — mirrors mathematical logic
✅ Works well for problems with recursive structures (e.g., tree traversal)

 

Disadvantages:
❌ Uses a lot of stack memory — can cause “Stack Overflow” on deep recursion
❌ Slower than iteration in large-scale repetitive tasks

 

🔹 Go: Recursion

package main

import "fmt"

func factorial(n int) int {
	if n == 0 {
		return 1
	}
	return n * factorial(n-1)
}

func main() {
	fmt.Println(factorial(5)) // Output: 120
}

 

Explanation:
Similar to JavaScript, but Go handles the stack more efficiently.
Some Go compilers even perform Tail Recursion Optimization (TRO) in certain cases.

 

Summary:
Recursion in Go is suitable for problems that require repetitive breakdowns such as:

  • Tree Traversal
  • Depth-First Search (DFS)
  • Recursive Parsing

 

2. Iteration — Using Loops

 

🔹 JavaScript: Iteration

function factorialIterative(n) {
  let result = 1;
  for (let i = 1; i <= n; i++) {
    result *= i;
  }
  return result;
}

console.log(factorialIterative(5)); // Output: 120

 

Advantages:
✅ Uses less memory than recursion
✅ Faster for large repetitive tasks

 

Disadvantages:
❌ Code can be slightly longer or less elegant
❌ Not ideal for problems with naturally recursive structures (e.g., trees or graphs)

 

🔹 Go: Iteration

package main

import "fmt"

func factorialIterative(n int) int {
	result := 1
	for i := 1; i <= n; i++ {
		result *= i
	}
	return result
}

func main() {
	fmt.Println(factorialIterative(5)) // Output: 120
}

 

Advantages:
✅ High performance, ideal for production systems
✅ Uses minimal memory
✅ Go’s compiler optimizes loops effectively

 

3. Recursion vs Iteration — Comparison

 

FeatureRecursionIteration
ConceptFunction calls itselfRepeats using loops
ReadabilityEasier for complex problemsEasier for general tasks
PerformanceSlightly slowerMuch faster
Memory UsageHigher (stack memory)Lower
Best ForTree, Graph, Divide & ConquerLooping, Counting, Accumulation

 

4. Real-World Example — Tree Traversal (DFS)

 

🔹 JavaScript: Recursive Tree Traversal

const tree = {
  value: 1,
  children: [{ value: 2 }, { value: 3, children: [{ value: 4 }] }]
};

function traverse(node) {
  console.log(node.value);
  if (node.children) {
    node.children.forEach(traverse);
  }
}

traverse(tree);

 

🔹 Go: Recursive Tree Traversal

package main

import "fmt"

type Node struct {
	Value    int
	Children []*Node
}

func traverse(n *Node) {
	fmt.Println(n.Value)
	for _, child := range n.Children {
		traverse(child)
	}
}

func main() {
	tree := &Node{
		Value: 1,
		Children: []*Node{
			{Value: 2},
			{Value: 3, Children: []*Node{{Value: 4}}},
		},
	}
	traverse(tree)
}

 

Output:

1
2
3
4

 

5. Choosing the Right Approach

 

🧠 Use Recursion Best for problems with hierarchical or nested structures, such as:

  • Tree / Graph Traversal
  • Divide & Conquer algorithms (e.g., Merge Sort, Quick Sort)

 

⚙️ Use Iteration Best for common tasks such as:

  • Looping, Counting, or Summation
    Especially in production systems that require high performance and stability.

 

💡 In Go: Loops are generally better optimized than recursion.
💻 In JavaScript: Recursion is great for learning and conceptual examples,
but iteration tends to be more stable in production environments.

 


 

Conclusion

 

Both Recursion and Iteration are essential programming tools. Choosing the right one can make your code cleaner, faster, and more memory-efficient.

 

ScenarioRecommended Approach
Tree / Graph Problems🧠 Recursion
General Loops / Counting Tasks⚙️ Iteration
High Performance Systems⚡ Iteration (especially in Go)
Easy-to-Understand Code💡 Recursion

 

Next Episode

 

In EP.38 of JS2GO,
we’ll dive into Buffer and Stream Management in Node.js and Go
understanding how to handle large-scale data efficiently, from reading files and network transmissions to managing memory in production systems ⚙️

 

Read more

🔵 Facebook: Superdev Academy

🔴 YouTube: Superdev Academy

📸 Instagram: Superdev Academy

🎬 TikTok: https://www.tiktok.com/@superdevacademy?lang=th-TH

🌐 Website: https://www.superdevacademy.com/en