Quick Index
Overview


A coder's favorite word: simplify

We'll demo how a basic return statement can be used to simplify code.

Example


In this example we'll use pseudocode for the logic to determine if a number is prime.

We'll call the algorithm "isPrime".

We'll start an algorithm that favors variables and only has one return statement at end of logic.

We'll then simplify the method by adding simple return statements.

Demo


One Return Statement at End of Logic
Here we take the approach of keeping a "result" variable.

We can work to get this to give the correct results.

However, the logic is complex. This is a welcoming environment for bugs.

Also, as we'll learn below, that this is very inefficient.

Generally coders try to shy away from deep, nested bracing.
static isPrime(n) {
	let result;
	if (n <= 1) {
		result = false;
	} else {
		if (n == 2) {
			result = true;
		} else {
			if (n % 2 == 0) {
				result = false;
			} else {
				if (n <= 7) {
					result = true;
				} else {
					result = true
					let max = Math.sqrt(n)
					let factor = 3
					while (factor <= max) {
						if (n % factor == 0) {
							result = false;
						}
						factor += 2;
					}
				}
			}
		}
	}
	return result;
}
Simplified with Return Statements
The main things that we do differently in this try are:

  • Look for special conditions at the start of the logic and return when they are found
  • When we find the result (e.g., when we find a factor, we return immediately

Benefits:

  • The code is so much simpler. The main logic is now just a very short while loop.
  • Much more efficient than the previous because when a result is known it is returned and the logic ends its work.
static isPrime(n) {
	// Special Cases
	if (n <= 1) return false;
	if (n == 2) return true;
	if (n % 2 == 0) return false;
	if (n <= 7) return true;
	let max = Math.sqrt(n)
	let factor = 3
	// "Return" if we find result
	while (factor <= max) {
		if (n % factor == 0)
			return false;
		factor += 2;
	}
	return true;
}
Side-by-Side Comparison
One Return Statement at End of Logic
static isPrime(n) {
	let result;
	if (n <= 1) {
		result = false;
	} else {
		if (n == 2) {
			result = true;
		} else {
			if (n % 2 == 0) {
				result = false;
			} else {
				if (n <= 7) {
					result = true;
				} else {
					result = true
					let max = Math.sqrt(n)
					let factor = 3
					while (factor <= max) {
						if (n % factor == 0) {
							result = false;
						}
						factor += 2;
					}
				}
			}
		}
	}
	return result;
}



Simplified with Return Statements
static isPrime(n) {
	// Special Cases
	if (n <= 1) return false;
	if (n == 2) return true;
	if (n % 2 == 0) return false;
	if (n <= 7) return true;
	let max = Math.sqrt(n)
	let factor = 3
	// "Return" if we find result
	while (factor <= max) {
		if (n % factor == 0)
			return false;
		factor += 2;
	}
	return true;
}