Close

How to Write JavaScript

Have you ever tried a coding problem, but ended up staring at a blank editor? After spending months working on JavaScript’s basics, a simple function still somehow eludes you.

It’s frustrating. Especially when the interviewer is waiting for you to write something.

You’ve learned all there is to know about variables, arrays and functions. Yet when it comes to coding on your own, you struggle to write a single line. You know JavaScript. You’re fully capable of reading code. But when standing behind a clean whiteboard, you don’t know where to start.

How do you get past the blank editor?

First, it’s important not to get discouraged. Starting another course is not the answer. What you need is a method to break down your ideas and translate them to code.

Below is my system to solve coding problems: a step-by-step guide on going from ideas to code. As an example, I’ll take you through the method to write the Fibonacci sequence.

How to break down problems

I refer to English, but naturally use the language of your interview. Speaking helps the interviewer understand your approach, giving them a chance to provide feedback. Outside an interview, use whatever language you feel comfortable with.

A flawed approach is trying to solve the problem in JavaScript. This seems like a stupid statement, so I’ll say it another way: you need to solve the problem in English first.

When we teach JavaScript, we show you the building blocks of the language. We don’t however explain how to express ideas in JavaScript.

Express your ideas in English first and then translate into JavaScript. You do this in the following four steps:

  • Define your problem in English
  • Define a solution in English
  • Write your solution in pseudo-code
  • Translate your solution to JavaScript

This won’t be easy the first time — it can take some getting used to. Spoken languages don’t force you to clarify your ideas at the level required for coding.

As you do it more, you’ll gain an understanding of what you can and can’t do with code. You’ll gain an innate sense for how to express your ideas in a way that translates easily.

Writing in Pseudo-code

Pseudo-code is a mix of code and English. There’s no correct way to write pseudo-code. As long as it looks a little like code, you’re doing well.

We write pseudo-code to express ideas in a language-agnostic way. We use it to skip details that convert easily to code.

The beauty of pseudo-code is the freedom to choose whatever level of detail we like. We can use magic statements to sketch our ideas without having to worry about implementation details. We can even write pseudo-code in full sentences.

//Both of these functions are valid pseudo-code
printSortedArray(array):
	sort array
	print each item in array
	
printSortedArray(array):
	// Bubble sort
	while array is not sorted:
		for each item in array:
			if item+1 is less than item
				swap item and item+1

	for each item in array:
		print item

Example: The Fibonacci sequence

I will run through an example of breaking down a problem and writing pseudo-code. We will create a function which returns the nth value of the Fibonacci sequence.

Note these two things throughout this process:

  • It is highly personal. What I come up with may differ from you.
  • It takes longer than it looks. Here, you don’t get to see the time I spent thinking about the problem.

Plain English

Our goal in this step is clarification. The more specific we can be, the better. Initially, it’s a good idea to define everything, and then state facts about your definitions.

We define the Fibonacci sequence problem:

  • The Fibonacci sequence is the sequence 1, 1, 2, 3, 5, 8, ...
  • To calculate any value of the Fibonacci sequence, I have to know the two previous values in the series.
  • If I want to know a specific value in the sequence, I need to know every prior value in the chain.

This may not seem like much, but it gives us enough to define a simple solution:

  • To get the value for n, I need to generate the entire Fibonacci sequence up to n.

If you’re able to, you can think up multiple solutions, and choose one. If it doesn’t work out, you can come back and try a different path.

Pseudo-code

We now have a specific way to get the nth value of the Fibonacci series: create all the numbers up until n. At this stage, we want to broadly think about how we will code this.

As I mentioned, the beauty of pseudo-code is the flexibility to use different levels of detail. It’s helpful to solve the problem using magic the first time around and add detail as we need it.

This is how I’d devise a magic solution:

fibonacci (n):
	loop between 0 and n
		sum two previous fibonacci numbers
		when n, return value

I used the magic statement “two previous fibonacci numbers”. It isn’t detailed enough to turn directly into code, but the approach is solid. We could use this as a blueprint to code from, but we will do one more round of pseudo-code to add detail.

In this round, we want a little less magic. How do we get the two previous Fibonacci numbers?

function fibonacci(n):
	// We can’t get n-2 for 0 and 1, so return them directly
	if n is 0 or 1, return 1

	// Set these to the first two numbers of the fibonacci sequence
	prev1 = 1
	prev2 = 1

	// use 2 here because we’ve already done when n is 0 and 1
	loop from 2 until n:
		current = prev1 + prev2

		// Update the previous numbers, so we’re ready for the next loop
		prev2 = prev1
		prev1 = current

   return current

Though this looks different to our previous solution, it is the same. We’ve only clarified how we will store the previous Fibonacci values.

This is a complete solution. While there are some minor details that I may need to add when coding, it translates into JavaScript almost 1:1.

JavaScript

Take the pseudo-code code you have, and turn it into the final JavaScript.

You must make some final decisions, like choosing <= inside of the for loop, but the result should look similar to your pseudo-code.

function fibonacci(n) {
	// We can’t get n-2 for 0 and 1, so return them directly
	if (n === 0 || n === 1) { return 1; }

	let prev1 = 1;
	let prev2 = 1;
	let current;

	// use 2 here because we’ve already done when n is 0 and 1
	for (let i = 2; i <= n; i++) {
		current = prev1 + prev2;
						  
		// Update the previous numbers, so we’re ready for the next loop
		prev2 = prev1;
		prev1 = current;
	}
		
	return current;
}

While perhaps not the most concise solution to the Fibonacci sequence, it is valid. And it will pass a coding interview.

This process may not come naturally to you. It takes time, and it takes practice. Try it out on one of the many practice sites or on a practice project.

Carl Anderson

Carl is a professional web developer with 7 years of experience. He enjoys writing about JavaScript. https://carlanderson.xyz/