How to Write Beautiful JavaScript Code

In the realm of programming, particularly when diving into the vibrant world of JavaScript, crafting code that's both functional and aesthetically pleasing is akin to an art form. When we speak of "beautiful" code, we're referring to code that's clean, easy to understand, maintain, and modify.

This article aims to guide you through the practices that will help you write JavaScript code that is as beautiful to read as it is to execute.

1. Embrace Readability

Readable code is beautiful code. Aim for clarity over cleverness. Use descriptive variable and function names that clearly state their purpose or the value they hold.

Example 1: Managing a Student List

Let's consider a simple JavaScript example involving a function that adds a student's name to a list of students in a classroom.

Less Descriptive:

let list = [];

function add(n) 
{
  list.push(n);
}

In the example above, list and add(n) are vague. Without context, it's unclear what type of items are in the list or what n represents.

More Descriptive:

let studentNames = [];

function addStudentName(name) 
{
  studentNames.push(name);
}

By using studentNames and addStudentName(name), the code immediately becomes more understandable, indicating that we are dealing with a list of student names and adding a name to this list.

Example 2: Checking if the score is eligible for high score list

In a scenario where you need to check if a score is a new high score, descriptive naming can make the logic much clearer.

Less Descriptive:

function check(a) 
{
  return a >= 100;
}

More Descriptive:

function isHighScore(score) 
{
  return score >= 100;
}

Using isHighScore(score) as the function name and score as the parameter makes it immediately clear that the function is checking if a score qualifies for the high score board.

2. Keep It DRY (Don't Repeat Yourself)

The DRY principle is about reducing the repetition of software patterns. Instead of copying and pasting the same code, use functions to encapsulate reusable code.

Let's see an example:

Repetitive:

rect(175, 140, 223, 54);
rect(108, 194, 362, 74);
circle(168, 268, 32);
circle(408, 268, 32);

rect(175, 340, 223, 54);
rect(108, 394, 362, 74);
circle(168, 468, 32);
circle(408, 468, 32);

DRY:

car(100, 100);
car(100, 300);

function car(x, y) 
{
    const w = 200;
    const h = 50;
    const rp = 0.3;
    
    // Calculate the width and height of top part
    let wt = (2 / 3) * w;
    let ht = (2 / 3) * h;
    
    // Coordinates of top rectangle
    let side = (w - wt) / 2;
    let xt = x + side;
    let yt = y;
    
    // Coordinates of bottom rectangle
    let xb = x;
    let yb = y + ht;
    
    // Coordinates of wheels
    let xw1 = x + side;
    let xw2 = x + w - side;
    let yw = y + ht + h;
    let rw = h * rp;
    
    rect(xt, yt, wt, ht);
    rect(xb, yb, w, h);
    
    circle(xw1, yw, rw);
    circle(xw2, yw, rw);
}

Although we spent a little bit of time to write the function car, now it is much faster to draw a car at any position on the screen without having to duplicate the code.

In the future if we want to upgrade the look of our cars, we can easily fix that by doing the change in only one place.

3. Comment Wisely

Comments are important for explaining why something is done a certain way, not what is done. Your code should be self-explanatory for the "what" part. Use comments to provide context or explain complex logic.

// Bad: Explaining what is obvious
// Draw a circle
circle(50, 50, 80);

// Good: Providing context
// Draw the sun in the top-left corner
circle(50, 50, 80);

4. Format Consistently

Consistent formatting makes your code easier to read and understand. Stick to a style guide (Allman or K&R style) and use it consistently. This includes consistent use of indentation, spaces, and semicolons.

Note: for coding education purposes we recommend the Allman style with your JavaScript projects.

Example:

// Inconsistent
function draw() {
ellipse(50, 50, 80, 80);
	circle(400,300, 100);
  }

// Consistent
function draw() 
{
	ellipse(50, 50, 80, 80);
	circle(400,300, 100);
}

5. Simplify and Refactor

Always look for ways to simplify your code without sacrificing readability. If a piece of code feels too complex, it probably is. Break down complex functions into smaller, manageable ones.

Complex logic:

// Complex
function draw() 
{
	let x = 100;
	let y = 100;
	
	circle(x, y, 10);
	...
	
	if ( car.visible )
	{
		const w = 100;
		const h = 50;
		
		rect(x, y, w, h);
		...
	}
}

Simplified logic:

function draw() 
{
	let x = 100;
	let y = 100;
	
	drawPlayer(x, y);
	
	if ( car.visible )
		drawCar(x, y);
}

function drawPlayer(x, y)
{
	circle(x, y, 10);
	...
}

function drawCar(x, y, color) 
{
	const w = 100;
	const h = 50;
	
    rect(x, y, w, h);
	...
}

Conclusion

Writing beautiful JavaScript code is a skill that develops over time, with practice and attention to detail.

By focusing on readability, DRY principles, wise commenting, consistent formatting, and simplification, you can elevate the quality of your code.

Remember, the goal is to write code that your future self, and others, can understand and work with easily.

Read more blog articles Browse JavaScript projects

About codeguppy

CodeGuppy is a FREE coding platform for schools and intependent learners. If you don't have yet an account with codeguppy.com, you can start by visiting the registration page and sign-up for a free account. Registered users can access tons of fun projects!


Follow @codeguppy on Twitter for coding tips and news about codeguppy platform. For more information, please feel free to contact us.