Welcome, fellow web developers, to a thrilling expedition into the realm of code quality! In this adventure-packed article, we’ll unravel a treasure trove of best practices and clever techniques to enhance your website’s code. Get ready to level up your HTML, CSS, JavaScript skills, and earn brownie points from your teammates for making their lives easier. My ultimate aim is to make you say and believe this - “clean code is not a compulsion, it’s an addiction!“.

Let’s dive right in…


HTML: Fix the Building Blocks🧱


1. BEM Naming Convention: Sensible Classes Pursuit

In Phil Karlton’s words, “there are only two hard things in Computer Science: cache invalidation and naming things”. Don’t worry, I got your back(we will talk about cache invalidation some other day). For now, embark on a noble quest guided by the Block Element Modifier (BEM) naming convention. This structured approach bestows order upon chaos and empowers you to create maintainable, scalable HTML.

BEM naming .block__element—modifier


2. Responsive Images: Visual Adaptation Journey

Embark on a thrilling journey through the land of responsive images. Discover the secrets of resolution switching, density switching, and art direction. Your images will seamlessly adapt to different devices, enchanting users far and wide.

table showing differences

  • In Resolution Switching, the browser determines the appropriate resolution of the image based on the screen size. The decision is made by the browser based on the available image resources and the display capabilities of the device.

  • Density Switching is a technique where the developer defines multiple versions of an image at different resolutions using the srcset attribute in HTML. The browser then selects the most appropriate image based on the device’s pixel density or resolution.

  • Art Direction allows developers to provide different images or media resources using the element. This technique enables the developer to define specific rules for different devices or conditions, ensuring that the browser displays the appropriate image as specified by the developer.


3. Semantic HTML: Empower Accessibility and SEO

Unleash the true potential of HTML by utilizing semantic elements. Opt for <header>, <nav>, <main>, <section>, and other semantic tags to provide meaningful structure to your web pages. Improve accessibility for assistive technologies and enhance search engine optimization(SEO). Always write appropriate ‘alt’ content for images. Also, make sure every page of yours on web has a title and description to it.


4. Meta Tags: Optimize Page Metadata

Enhance your website’s visibility and optimize its appearance in search engine results by utilizing meta tags. Use OpenGraph, Twitter, and other available meta tags. Craft compelling meta descriptions, specify character encoding with the <meta charset> tag, and define viewport settings for responsive design with the <meta name="viewport"> tag.


CSS: Unleash the Style Wizard🧙


1. Universal Reset: Banish Browser Quirks

css reset

Imagine donning a magical cloak that shields your website from unpredictable browser styles. By adding a universal reset code to the HTML {}, you ensure a consistent appearance across browsers and user settings. You can also use Josh Comeau’s reset(a simple google search would take you there).


2. Box-sizing: Taming the Sizing Dragon

box sizing in css

Harness the power of the box model! Embrace “box-sizing: border-box;” in the body {} to effortlessly handle element sizing with borders and padding. It tells the browser to account for any border and padding in the values you specify for an element’s width and height. If you set an element’s width to 100 pixels, that 100 pixels will include any border or padding you added, and the content box will shrink to absorb that extra width. Your layout puzzles will become a breeze!


3. Battle of background-color vs. background:

Enter the arena where “background” reigns supreme! Be cautious, though, as this shorthand property resets all other background-related specifibations. If color alone is your aim, favor the noble “background-color” to prevent unexpected surprises.


4. The % Chronicles: Responsive Design Made Easy

Bid farewell to stubborn pixels and embrace the fluidity of percentages. From images to widths, using ’%’ instead of pixels unlocks a world of responsive design possibilities. Let your creations adapt gracefully to different screen sizes.

get rid of px

Here, we do also accessibility to a degree. For instance, we use percentage instead of px when defining the root font-size, so as not to interfere with custom user settings concerning font-size, allowing visually impaired individuals, or those who simply wish to avoid eye-strain, to retain their higher browser font-size settings.


5. CSS Variables: Masters of Color Alchemy

css variables

Unleash the power of CSS variables to control colors like a true sorcerer. Set color variables within the root and witness the magic as your styles transform with ease. Combine Sass and CSS variables for a truly enchanting experience!


6. Mixins: The Code-Wizard’s Elixir

mixins in css

Tired of repeating the same incantations? Fear not! Embrace the power of mixins to create reusable code blocks. From modals to other repetitive snippets, mixins will save you from the clutches of code duplication.


7. Flexbox: Embrace Flexible Layouts

Discover the power of Flexbox to create flexible and responsive layouts effortlessly. Use properties like “display: flex” and “justify-content” to align and distribute items within a container. Say goodbye to complex float-based layouts and embrace the magic of Flexbox.


8. CSS Grid: Master the Art of Grid-based Designs

Level up your layout skills with CSS Grid. Create complex, grid-based designs that adapt to different screen sizes and devices. Utilize features like grid lines, tracks, and areas to craft visually stunning and responsive web layouts.


JavaScript: The Magic Wand ✨


1. Native Attributes/Methods: The Power Within

Harness the innate strength of native attributes and methods whenever possible. Your code will become leaner, faster, and more elegant. Feel the thrill of efficiency as you tap into the true potential of JavaScript.

native js methods

It looks similar, but uses native DOM attributes to grab the value instead of invoking the jQuery object. With modern browsers this optimization won’t be noticeable to the end user, but it’s still a simple tweak that will cut down on overhead


2. Function Expressions: Spells of Order & Structure

fn expression vs declaration

Always prefer ‘function expression over function declaration’. Embrace the art of function expressions, where the order of spells truly matters. With organized code structures, your functions will work in harmony, paving the way for cleaner, more maintainable JavaScript. With function expressions, I cannot call a function before I’ve expressed it, so my code has a nice, neat structure to it. Functions that call other functions are written in a specific order every time, because they won’t work otherwise. And, any code I run to kick things off happens at the end of the file.


3. Code Safety with Closures: Encapsulation Shield

code closures

Enchant your code with the protective shield of closures. Dive into the depths of Immediately Invoked Function Expressions (IIFE) and the Module Pattern. Watch as your code becomes encapsulated, organized, and resistant to variable clashes.


4. ES6 and Beyond: A Dive into Modern JavaScript

ES6

Embark on a quest to harness the power of ES6! With ‘const’ and ‘let’ at your command, you’ll wield the latest JavaScript features and conquer compatibility challenges. Remember, Babel is your trusted companion for backward compatibility!


5. Deferred JavaScript Execution: Lightning Speed

Unleash the power of the “defer” attribute! Allow your HTML to load swiftly, while JavaScript awaits its turn to take the stage. Witness the blazing-fast performance of your web pages as you optimize their loading speed. The defer attribute tells the browser to only execute the script file once the HTML document has been fully parsed. Like an asynchronously loaded script, the file can be downloaded while the HTML document is still parsing. However, even if the file is fully downloaded long before the document is finished parsing, the script is not executed until the parsing is complete.


6. Dynamic Imports: Spells of On-Demand Magic

dynamic import

Discover the enchantment of dynamic imports! Cast a spell upon your JavaScript, loading code on-demand and shrinking your initial bundle size. Watch as your web application’s performance soars to new heights!


7. Promises: Mastering Asynchronous JavaScript

async-await

Dive into the world of Promises to conquer asynchronous JavaScript. Replace nested callbacks with clean and readable code structures. Utilize Promise.all() to execute multiple asynchronous operations simultaneously, unlocking the true power of async programming.


8. Error Handling: Embrace Graceful Failure

try catch JS

Adopt a proactive approach to error handling in JavaScript. Implement try-catch blocks to gracefully handle exceptions and prevent application crashes. Leverage tools like error logging services to capture and analyze errors in production environments.


Additional Tips: The Hidden Truths


1. JSON.stringify(): Mastering Data Manipulation

json stringify

Unlock the secret of JSON data manipulation with JavaScript’s JSON.stringify(). Wave goodbye to hardcoded data and embrace the power of dynamic transformations. JSON will bow to your command!


2. Performance Optimization: Cache & Compress

Boost your website’s performance by implementing caching and compression techniques. Utilize HTTP caching headers to store and retrieve static assets efficiently. Employ GZIP or Brotli compression to reduce file sizes and improve page load times.


3. Code Documentation: Clarity & Collaboration

Document your code to enhance clarity and facilitate collaboration among developers. Use tools like JSDoc or Markdown to provide detailed explanations of functions, classes, and modules. Clear and well-documented code is a gift to your future self and fellow developers.


partyyy GIF!

That’s all for today, folks! Congratulations & thank you so much for staying with me till here. We made good progress, together! 🥳

Armed with these extraordinary best practices, you’re now equipped to embark on an epic adventure to enhance your code quality and conquer the web development kingdom. May your code be clean, your designs be responsive, and your JavaScript be enchanting! Happy coding, brave developers! 💪