7 Tips for Taking Your SEO Strategy to the Next Level in 2024

Post pobrano z: 7 Tips for Taking Your SEO Strategy to the Next Level in 2024

Search engine optimization (SEO) is crucial for growing your online visibility and reaching more customers. With the constant changes in search algorithms and user behavior, you need to continually evolve your SEO strategy. Here are 7 tips to take your SEO to the next level in 2024.

Conduct an Audit of Your Current SEO

Before making major changes to your strategy, audit what you currently have in place. Analyze your website content, metadata, backlinks, and any technical issues. See what’s working and what can be improved. Identify keyword gaps and new opportunities. Use SEO tools to uncover site crawl errors, duplicate content issues, and ways to improve page speed. The audit gives you a baseline to build upon.

Focus on Optimizing for User Intent

In 2024, fulfilling user intent with your content will be crucial. Go beyond targeting generic keywords. Research the language real people use when searching for your products or services. Create content that answers their questions and solves their problems. For example, for a medical practice targeting the keyword “lower back pain”, create detailed content explaining back pain causes, treatments, remedies, and tips for prevention. Really dig into what users want to know.

Prioritize Quality Content

High-quality, useful content is vital for SEO success. Ensure you have a regular content schedule with blog posts, videos, and other formats. Expand your content to cover new topics and include more long-form guides and FAQs. Integrate keywords naturally while keeping the content engaging and valuable. Making your website a go-to resource builds trust and authority. User engagement metrics like time on page and bounce rate matter too.

Improve Site Speed and Mobile Optimization

With Google’s Mobile First Index, having a fast, mobile-friendly site is essential. Use tools like Google PageSpeed Insights and Pingdom to test your speed. Leverage browser caching, compress images, minimize redirects, and optimize code. Create a smooth mobile experience by avoiding interstitials and ensuring buttons are easy to tap. Faster load times improve user experience and SEO.

Build High Quality Backlinks

The quality of links pointing to your site still influences rankings. Focus on earning backlinks from reputable websites related to your industry, not spammy link networks. Guest posting on popular blogs and link inserts on relevant resource pages are effective tactics. Make sure the content you create provides value to the site linking to you. Promote your best content and be selective about link prospects.

Stay Up-to-Date on SEO News and Trends

SEO evolves constantly. Subscribe to blogs, newsletters, and Google’s Search Central to stay on top of algorithm updates, new features, tools, and changes to best practices. Learn how Google’s core updates impact search. Adjust your strategy based on the latest developments. Being informed ensures you make the most of new opportunities.

Make the Most of the Latest SEO Tools

Choosing the right SEO tools is key to maximizing the effectiveness of your search engine optimization efforts.

Useful tools include keyword research tools like SEMrush and Ahrefs to uncover high-value keyword targets and analyze the competition. Website crawlers like Screaming Frog identify technical SEO issues to fix. Rank-tracking software like SEMrush and Moz lets you monitor your keyword rankings over time. All-in-one suites and enterprise level solutions like Ahrefs and SEMrush combine keyword, competitor, and link analysis along with rank tracking for comprehensive SEO insights.

The best tools fit seamlessly into your workflow and provide the data you need to boost organic growth. Evaluating your needs and starting with the essential tools first is recommended when building your SEO tool stack.

Following these tips will put you ahead of the curve with SEO in 2024. As you build authority and trust through high-quality content, backlinks and optimizing for user intent, your rankings and traffic will steadily improve. Keep learning, track your results, and be nimble in adapting your strategy. With the right focus, your website will reach the next level.

The post 7 Tips for Taking Your SEO Strategy to the Next Level in 2024 appeared first on Designer Daily: graphic and web design blog.

Shopify Checkout Extensibility: Enhancing Your E-commerce Experience

Post pobrano z: Shopify Checkout Extensibility: Enhancing Your E-commerce Experience

In the ever-evolving world of e-commerce, Shopify continues to lead the way with innovative solutions for online retailers. Shopify checkout extensibility has emerged as a game-changer, giving merchants unprecedented control over their checkout process. This new feature has an impact on how businesses customize their customers’ purchasing experience, offering a level of flexibility that was previously unattainable.

Shopify checkout extensibility allows store owners to tailor their checkout pages to meet specific needs and preferences. This article will explore the ins and outs of this powerful tool, including how to implement checkout extensibility and upgrade from the traditional checkout.liquid system. Additionally, it will delve into the benefits of using Shopify app extensions to enhance the checkout process, providing insights into how these advancements are shaping the future of online shopping.

Understanding Shopify Checkout Extensibility

What is Checkout Extensibility?

Shopify Checkout Extensibility is a suite of powerful platform features that allows merchants to customize their checkout process in a way that’s app-based, upgrade-safe, and performant. This innovative solution has been designed to address the limitations of the traditional checkout.liquid system, offering a more flexible and efficient approach to tailoring the checkout experience.

Introduced in the summer of 2022, Checkout Extensibility provides a range of tools and capabilities that enable both code-free customizations and more advanced modifications. This new system integrates seamlessly with Shop Pay, which has been shown to convert up to 50% better than guest checkout options.

Key features and benefits

Checkout Extensibility offers several key components that enhance the customization possibilities for Shopify merchants:

  1. Checkout Editor: A visual tool that allows merchants to easily modify the look and feel of their checkout pages without coding. It includes options to add logos, change background colors, and update fonts.
  2. Shopify App Integration: Merchants can install and use various checkout apps directly from the Shopify App Store, adding new functionalities to their checkout process.
  3. Branding API: This feature enables developers to create a consistent brand experience by customizing the checkout’s appearance, including form fields, typography, and border radius.
  4. Checkout UI Extensions: Developers can create custom app blocks to add specific functionality or logic to different steps of the checkout process.
  5. Web Pixel App Extension: This tool allows for custom tracking of user behavior and customer events during the checkout process.
  6. Shopify Functions: Available for Shopify Plus users, this feature allows developers to modify Shopify’s backend logic, offering even more customization options.

Comparison with checkout.liquid

The transition from checkout.liquid to Checkout Extensibility brings several advantages:

Feature checkout.liquid Checkout Extensibility
Customization Method Complex code editing App-based and visual tools
Upgrade Process Manual upgrades required Automatic, no upgrades needed
Performance Standard 2X faster interactions
Integration with Shop Pay Limited Seamless integration
Security Standard Enhanced with sandboxed environment
Access to New Features Delayed Immediate access

Checkout Extensibility not only surpasses the limitations of checkout.liquid but also provides a more powerful solution for customizing the checkout process. It offers faster performance, with checkout interactions and page transitions that are twice as fast, leading to an average increase in conversion rates of over 1%.

Implementing Checkout Extensibility

Checkout Extensibility offers a suite of powerful features that enable merchants to customize their checkout process in a way that’s app-based, upgrade-safe, and performant. This innovative solution has been designed to address the limitations of the traditional checkout.liquid system, providing a more flexible and efficient approach to tailoring the checkout experience.

Checkout editor and branding tools

The Checkout Editor is a visual tool that allows merchants to easily modify the look and feel of their checkout pages without coding. It includes options to add logos, change background colors, and update fonts. Merchants can make no-code customizations using apps and branding tools to create a consistent brand experience throughout the checkout process.

To customize the checkout using the Checkout Editor:

  1. Go to Settings > Checkout in the Shopify admin.
  2. Click on “Customize” to access the drag-and-drop editor.
  3. Edit the logo, font, colors, and background of the checkout.
  4. Add new functionality by installing apps directly from the editor.

Checkout apps and extensions

Shopify’s App Store offers a wide range of checkout apps that can be easily integrated to enhance the functionality of the checkout process. These apps can add features such as upsells, custom fields, and post-purchase offers.

Some popular checkout extensions include:

  • Upsell apps that increase Average Order Value (AOV)
  • Free shipping bars to encourage higher spending
  • Custom fields for additional customer information
  • Post-purchase surveys and thank you page offers

Developers can also create custom app blocks to add specific functionality or logic to different steps of the checkout process using Checkout UI Extensions.

Pixels and customer events tracking

Checkout Extensibility provides enhanced capabilities for tracking customer events and implementing custom pixels. The Web Pixel App Extension allows for custom tracking of user behavior and customer events during the checkout process.

To implement custom pixel tracking:

  1. Create the code for your custom pixel.
  2. Go to Settings > Customer events in the Shopify admin.
  3. Click on “Add pixel” to open the event editor.
  4. Paste your custom JavaScript pixel code into the Code window.
  5. Save and connect the pixel to start tracking events.

This centralized approach to pixel management ensures secure tracking for both the online store and checkout from a single location.

By leveraging these tools and features, merchants can create a highly customized and efficient checkout experience that aligns with their brand and business needs. Checkout Extensibility not only surpasses the limitations of the previous system but also provides a more powerful solution for optimizing the crucial final step of the e-commerce journey.

Upgrading from checkout.liquid

Deprecation timeline

Shopify has announced a phased approach to discontinue the use of checkout.liquid. The timeline for this transition is as follows:

  • August 13, 2024: Shutdown of checkout.liquid for Information, Shipping, and Payment pages
  • August 28, 2025: Deadline for Plus merchants to upgrade Thank you and Order status pages

After these dates, customizations made using checkout.liquid will cease to function, and Shopify will no longer provide support for updating or fixing these customizations. It’s crucial for merchants to upgrade to Checkout Extensibility before these deadlines to ensure uninterrupted e-commerce operations.

Steps to migrate

To facilitate a smooth transition from checkout.liquid to Checkout Extensibility, merchants can follow these steps:

  1. Review existing customizations:
    1. Go to Settings > Checkout in the Shopify admin
    2. Click “Review customizations” to access a report detailing current checkout modifications
  2. Analyze the customization report:
    1. Identify categories of customizations (e.g., Branding, Validations)
    2. Note the source files and code lines for each customization
    3. Review guidance provided for recreating customizations in Checkout Extensibility
  3. Create a draft configuration:
    1. Navigate to Settings > Checkout
    2. Click “Create draft” in the Configurations section
  4. Customize the new checkout:
    1. Add apps or edit branding as needed
    2. Set up Pixels or additional first-party features
  5. Review changes and publish:
    1. When ready, click “Publish”
    2. Choose which pages to publish and confirm the replacement of existing customizations

Potential challenges and solutions

Migrating from checkout.liquid to Checkout Extensibility may present some challenges:

  1. App compatibility: Ensure all apps are compatible with the new Extensibility Checkout. Contact app developers for updates if necessary.
  2. Custom code migration: Manually rebuild customizations using Shopify’s API or develop a custom app. Consider seeking assistance from a Shopify Plus partner for complex migrations.
  3. Performance testing: After migration, conduct live checkout tests to verify functionality. Monitor key performance indicators such as order volumes and upsells to identify areas for optimization.
  4. Learning curve: Familiarize yourself with the new Checkout Editor and Branding API to effectively customize the checkout experience.

By addressing these challenges proactively and following Shopify’s guidance, merchants can successfully transition to the more secure and feature-rich Checkout Extensibility system.

Conclusion

Shopify’s Checkout Extensibility has a significant impact on the e-commerce landscape, offering merchants powerful tools to tailor their checkout process. This new system brings a host of benefits, including faster performance, seamless integration with Shop Pay, and enhanced customization options. By moving away from the limitations of checkout.liquid, store owners can now create a more personalized and efficient purchasing experience for their customers.

As the deadline for transitioning to Checkout Extensibility approaches, it’s crucial for merchants to start planning their migration strategy. The shift to this new system not only ensures compliance with Shopify’s updates but also opens up new possibilities to improve conversion rates and customer satisfaction. With its app-based approach and user-friendly tools, Checkout Extensibility is set to shape the future of online shopping, giving businesses the flexibility they need to thrive in the competitive e-commerce market.

The post Shopify Checkout Extensibility: Enhancing Your E-commerce Experience appeared first on Designer Daily: graphic and web design blog.

Street Art by Rone in Perth’s Historic Centenary Galleries

Post pobrano z: Street Art by Rone in Perth’s Historic Centenary Galleries

Have you ever wondered what stories lie hidden beneath the layers of peeling paint and cracked ceilings? The groundbreaking multi-sensory installation, TIME • RONE, invites you to explore just that. This extraordinary exhibit, now showing in AGWA’s Centenary Galleries in Perth, offers a unique and immersive experience that will challenge your perceptions of beauty, time, and memory.

Created by the ingenious multi-disciplinary artist Rone, TIME • RONE is a grand-scale excavation of meaning from the everyday. It transforms the historic Centenary Galleries into a haunting tableau of mid-century Australia, where visitors can walk, breathe, and live among the remnants of a bygone era.

As you step into this meticulously crafted world, you’ll find yourself surrounded by the ghostly echoes of the past. Faces frozen in time search eternally for something just out of reach, while mirrors blend illusions of history with glimpses of the future. The installation is a poignant reminder of the relentless march of time and the beauty that can be found in decay.

Rone’s masterful blend of soundscape, mural, and installation art creates a truly immersive experience. Each element works in harmony to pose profound questions about what we leave behind and to honor the often-forgotten aspects of our shared history.

Following a sell-out season in Melbourne, the Perth exhibition features expanded staging and an exclusive new room, making it a must-see event for art enthusiasts and curious minds alike.

Don’t miss this opportunity to experience TIME • RONE and lose yourself in a world where time stands still, yet life persists. This thought-provoking installation promises to leave you with a new appreciation for the beauty hidden in the overlooked corners of our world.

The post Street Art by Rone in Perth’s Historic Centenary Galleries appeared first on Designer Daily: graphic and web design blog.

Breaking Language Barriers in Education with Video and Audio Translators

Post pobrano z: Breaking Language Barriers in Education with Video and Audio Translators

Educational institutions across the globe are seeing a more diverse student population, with learners speaking a multitude of languages. This diversity enriches the educational environment but also poses significant challenges. One of the most effective solutions to these challenges is the use of video and audio translators. These tools not only facilitate communication but also enhance the learning experience for students from different linguistic backgrounds. In this blog post, we will explore how video and audio translators are breaking language barriers in education and revolutionizing the way we teach and learn.

The Challenge of Language Barriers in Education

Language barriers in education can lead to numerous issues, including misunderstanding of course material, reduced student participation, and lower academic performance. For non-native speakers, the struggle to comprehend lectures, textbooks, and other educational materials can be daunting. Teachers, on the other hand, face the challenge of effectively communicating complex concepts to students who may not fully understand the language of instruction. This gap can hinder the educational progress of students and create an uneven playing field.

The Role of Video Translators in Education

Video translators have emerged as powerful tools to address these challenges. By providing subtitles or voice-over translations for educational videos, they make content accessible to students who speak different languages. Here are some ways an AI video translator will make a difference:

  1. Enhanced Comprehension of Lectures
    Educational videos, whether pre-recorded lectures or supplementary materials, are integral to modern education. Video translators can add subtitles in multiple languages, enabling students to follow along and understand the content better. This is particularly useful in subjects that involve complex terminology or concepts, such as science and mathematics.
  2. Inclusive Learning Environment
    By offering translated videos, educators can create a more inclusive learning environment. Students who might otherwise feel excluded due to language barriers can participate more actively in class discussions and group activities. This inclusivity fosters a sense of belonging and encourages diverse perspectives.
  3. Accessibility for Hearing-Impaired Students
    Video translators also benefit students with hearing impairments. Translated subtitles not only cater to different languages but also provide a text-based option for students who rely on visual content. This dual benefit makes video translators a versatile tool in promoting accessibility.
  4. Supplementary Learning Materials
    Teachers can use video translators to create supplementary learning materials in various languages. These materials can be shared with students to reinforce learning and ensure they grasp key concepts outside the classroom. This additional support can be crucial for non-native speakers who need extra time to process information.

The Impact of Audio Translators in Education

Audio translators complement video translators by focusing on audio content, such as lectures, podcasts, and audiobooks. Here’s how they contribute to breaking language barriers:

  1. Real-Time Translation of Lectures
    One of the most significant advancements in audio translation is real-time translation. During live lectures, audio translators can provide simultaneous translation, allowing students to hear the lecture in their native language. This real-time accessibility ensures that all students can follow along without delay, making the learning experience more cohesive.
  2. Multilingual Audiobooks and Podcasts
    Audiobooks and educational podcasts are valuable resources for students. An audio translator can convert these resources into multiple languages, broadening their accessibility. Students can listen to educational content in their preferred language, making learning more engaging and effective.
  3. Support for Language Learning
    Audio translators are also beneficial for language learning classes. Students learning a new language can listen to translations and compare them with the original content, helping them improve their language skills. This immersive experience enhances their understanding and retention of the new language.

Practical Implementation of Translation Tools in Education

For educational institutions looking to implement video and audio translators, here are some practical steps:

  1. Choosing the Right Tools
    There are various translation tools available, each with different features and capabilities. Schools and universities should choose tools that best meet their needs. Key factors to consider include the range of languages supported, the accuracy of translations, and ease of integration with existing educational platforms.
  2. Training Educators
    Educators need to be trained on how to use translation tools effectively. This includes understanding how to integrate subtitles into videos, using real-time audio translation during lectures, and creating multilingual learning materials. Training ensures that teachers can maximize the benefits of these tools.
  3. Engaging Students
    Students should be encouraged to use translated resources and provide feedback on their effectiveness. This feedback can help educators refine their use of translation tools and address any issues that arise. Engaging students in the process also promotes a collaborative learning environment.
  4. Continuous Evaluation
    The use of translation tools should be continuously evaluated to measure their impact on student performance and engagement. Regular assessments can help identify areas for improvement and ensure that the tools are meeting the needs of all students.

The Future of Translation in Education

The future of education is likely to see even more sophisticated translation tools powered by artificial intelligence and machine learning. These advancements will further improve the accuracy and efficiency of translations, making them an indispensable part of the educational landscape. Additionally, as more educational institutions recognize the benefits of these tools, their adoption will become more widespread, promoting greater inclusivity and accessibility.

The post Breaking Language Barriers in Education with Video and Audio Translators appeared first on Designer Daily: graphic and web design blog.

CSSWG Minutes Telecon (2024-08-14)

Post pobrano z: CSSWG Minutes Telecon (2024-08-14)

I was just going over the latest CSSWG minutes (you can subscribe to them at W3C.org) and came across a few interesting nuggets I wanted to jot down for another time. The group discussed the CSS Values, CSS Easing, and Selectors modules, but what really caught my eye was adding triggered delays to CSS for things like hover, long taps, and focus states.

The idea stems from an OpenUI proposal, the same group we can thank for raising things like the Popover API and customizable select element. The concept, if I understand it right, is that anytime someone hovers, taps, or focuses on, say, a <button> for a certain amount of time, we can invoke some sort of thing. A tooltip is the perfect illustration. Hovering over the trigger element, the reasoning goes, is an expression of interest and as web authors, we can do something with that interest, like displaying a tooltip.

A mouse cursor hovering an info button with an hourglass next to it indicating time passed before showing a tooltip.

Whoa, right?! There’s long been chatter about CSS encroaching on JavaScript territory (isn’t it ironic, don’t you think?). Firing events in response to interaction is quite literally the only thing I use JavaScript for. There’s no mistake about that in the CSSWG, as documented in the minutes:

So. Does this belong in CSS? Or should it be elsewhere? Does the approach make sense? Are there better ideas? Most interested in the last.

[…]

Other question; does this belong in CSS or HTML… maybe this is just a javascript feature? In JS you can determine MQ state and change things so it wouldn’t necessarily be in CSS.

And shortly later:

As you were talking; one thing that I kept thinking of; should developers be customizing the delay at all? Original use case for delay is that hover shouldn’t be instant. But if we don’t allow for customizing we can align to platform delay lengths.

But there’s an excellent point to be made about the way many of us are already doing this with CSS animations (animation-delay) and transitions (transition-delay). Sometimes even applying those globally with the Universal Selector or a prefers-* query.

Things get even hairier when considering how values are defined for this. Are they explicit delays (800ms), generic keywords (none/short/medium/long), a custom property, a pseudo-class… something else? I’m glad there’re incredibly smart folks noodling on this stuff.

I think here it would be good to go with time values. CSS is a good place to put it. We have all the ergonomics. The right declarative place to put it.

Whatever the eventual case may be:

I think this sounds reasonable and I’d like to explore it. Unsure if this is the exact shape, but this space seems useful to me.


CSSWG Minutes Telecon (2024-08-14) originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

How are the `colspan` and `rowspan` attributes different?

Post pobrano z: How are the `colspan` and `rowspan` attributes different?

Yes, yes. Functionally, they are different. But heck if I didn’t know about the wacky thresholds until Jens Oliver Meiert tooted a pair of quick polls.

According to the HTML Standard:

  1. If the current cell has a colspan attribute, then parse that attribute’s value, and let colspan be the result.
    If parsing that value failed, or returned zero, or if the attribute is absent, then let colspan be 1, instead.
    If colspan is greater than 1000, let it be 1000 instead.
  2. If the current cell has a rowspan attribute, then parse that attribute’s value, and let rowspan be the result.
    If parsing that value failed or if the attribute is absent, then let rowspan be 1, instead.
    If rowspan is greater than 65534, let it be 65534 instead.

I saw the answers in advance and know I’d have flubbed rowspan. Apparently, 1000 table columns are plenty of columns to span at once, while 65534 is the magic number for clamping how many rows we can span at a time. Why is the sweet spot for rowspan 6,4543 spans greater than colspan? There are usually good reasons for these things.

What that reason is, darned if I know, but now I have a little nugget for cocktail chatter in my back pocket.


How are the `colspan` and `rowspan` attributes different? originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

On the Ground at Frostapalooza

Post pobrano z: On the Ground at Frostapalooza

I can’t say I would have ever expected to see Jeremy Keith performing the Yeah Yeah Yeahs song “Maps”, but then again, I don’t know what I expected to happen at Frostapalooza.

The Event

Brad Frost, web designer, author of Atomic Design, and an absolute maniac on the bass, celebrated his birthday by putting together a one-night-only benefit concert featuring musical performances by himself and his talented family and friends.

Frostapalooza, held at Mr. Smalls Theatre in Pittsburgh, PA, was an all-ages event where 100% of the proceeds are headed towards two great causes:

  • NextStep Pittsburgh: Helping provide accessible rehabilitation for folks with spinal cord injuries and paralysis in Pittsburgh.
  • Project Healthy Minds: Providing research and resources to help tackle mental health.

Performances

The variation of musical performances sprawled across the night, covering tracks by Fleetwood Mac, Radiohead, David Bowie and so much more, check out this setlist of all 31 tracks on Spotify.

I loved the performance of Pink Floyd’s classic song, “Money.” As a Floyd fan who will never get to see them live, this was easily the best rendition I could ask for, which included the full lineup of instrumental sections.

Brad was joined on stage by none other than CSS-Tricks founder, Chris Coyier. Chris picked banjo on a few songs, such as Johnny Cash’s “Folsom Prison Blues” and The Band’s “The Weight,” both fantastic.

The stage background prominently displayed visuals out of CodePen demos made by CodePen community members during the set. Check out the Frostapalooza tag on CodePen to see everything that was projected.

Another favorite moment was Brad’s version of “Wake Up” by Arcade Fire, which felt like a perfectly matched song for the evening.

Musicians

If you haven’t caught on yet, many of the folks lending their musical talents to Frostapalooza also happen to be web designers and developers Brad has met and worked with during his career. At times it felt like the Wu-Tang Clan of CSS on stage.

Brad’s family and musicians from his other bands pitched in, such as Elby Brass. Ridiculously impressive! I had never seen a tuba-playing lead vocalist until this night.

You can see the full lineup on the event’s website. But I’ll drop a screenshot in here just for posterity.

Full lineup of musicians who performed at Frostapalooza.

Photos! Videos!

Mike Aparicio captured a great video of a group jam on Queen’s “Bohemian Rhapsody” that you’ve got to watch on YouTube. Brian Kardell nabbed this gem of Chris pickin’ on “The Weight”:

Party boy Brad Frost shared a bunch of other photos from the event in a Google Photos album.

The end

Plain and simple, this was a super fun night celebrating music and friends. Happy birthday, Brad, and thanks for putting on an awesome show!


On the Ground at Frostapalooza originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

All About JavaScript Loops

Post pobrano z: All About JavaScript Loops

Every programming language has loops. Loops perform an operation (i.e., a chunk of work) a number of times, usually once for every item in an array or list, or to simply repeat an operation until a certain condition is met.

JavaScript in particular has quite a few different types of loops. I haven’t even used all of them, so for my own curiosity, I thought I’d do a high-level overview of them. And as it turns out, there are pretty good reasons I haven’t used at least a couple of the different types.

So, for now let’s spend a while exploring the different types of loops, what we can do with each of one, and why you might use one over another. (You’ll think that little play on words is absolutely hilarious by the end.)

The while and do...while loops

First up is the while loop. It’s the most basic type of loop and has the potential to be the easiest to read and the fastest in many cases. It’s usually used for doing something until a certain condition is met. It’s also the easiest way to make an infinite loop or a loop that never stops. There is also the do...while statement. Really, the only difference is that the condition is checked at the end versus the beginning of each iteration.

// remove the first item from an array and log it until the array is empty
let queue1 = ["a", "b", "c"];

while (queue1.length) {
  let item = queue1.shift();

  console.log(item);
}

// same as above but also log when the array is empty
let queue2 = [];

do {
  let item = queue2.shift() ?? "empty";

  console.log(item);
} while (queue2.length);

The for loop

Next is the for loop. It should be the go to way to do something a certain number of times. If you need to repeat an operation, say, 10 times, then use a for loop instead. This particular loop may be intimidating to those new to programming, but rewriting the same loop in the while-style loop can help illustrate the syntax make it easier to stick in your mind.

// log the numbers 1 to 5
for (let i = 1; i <= 5; i++) {
  console.log(i);
}

// same thing but as a while loop
let i = 1; // the first part of a for loop

// the second
while (i <= 5) {
  console.log(i);

  i++; // the third
}

("end");

The for...of and for await...of loops

A for...of loop is the easiest way to loop through an array.

let myList = ["a", "b", "c"];

for (let item of myList) {
  console.log(item);
}

They aren’t limited to arrays though. Technically they can iterate through anything that implements what is called an iterable protocol. There are a few built-in types that implement the protocol: arrays, maps, set, and string, to mention the most common ones, but you can implement the protocol in your own code. What you’d do is add a [Symbol.iterator] method to any object and that method should return an iterator. It’s a bit confusing, but the gist is that iterables are things with a special method that returns iterators; a factory method for iterators if you will. A special type of function called a generator is a function that returns both a iterable and iterator.

let myList = {
  *[Symbol.iterator]() {
    yield "a";
    yield "b";
    yield "c";
  },
};

for (let item of myList) {
  console.log(item);
}

There is the async version of all the things I just mentioned: async iterables, async iterators, and async generators. You’d use an async iterable with for await...of.

async function delay(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

// this time we're not making an iterable, but a generator
async function* aNumberAMinute() {
  let i = 0;

  while (true) {
    // an infinite loop
    yield i++;

    // pause a minute
    await delay(60_000);
  }
}

// it's a generator, so we need to call it ourselves
for await (let i of aNumberAMinute()) {
  console.log(i);

  // stop after one hour
  if (i >= 59) {
    break;
  }
}

One unobvious thing about for await...of statement is that you can use it with non-async iterables and it will work just fine. The reverse, however, is not true; you can’t use async iterables with the for...of statement.

The forEach and map loops

While these are not technically loops per se, you can use them to iterate over a list.

Here is the thing about the forEach method. Historically it was much slower than using a for loop. I think in some cases that may not be true anymore, but if performance is a concern, then I would avoid using it. And now that we have for...of I’m not sure there is much reason to use it. I guess the only reason that it still may come up is if you have a function ready to use as the callback, but you could easily just call that same function from inside the body of for...of.

forEach also receives the index for each item though, so that may be a thing you need too. Ultimately, the decision to use it will probably come down to whether any other code you’re working with uses it, but I personally would avoid using it if I’m writing something new.

let myList = ["a", "b", "c"];

for (let item of myList) {
	console.log(item);
}

// but maybe if I need the index use forEach
["a", "b", "c"].forEach((item, index) => {
  console.log(`${index}: ${item}`);
});

Meanwhile, map essentially converts one array into another. It still has the same performance impact that forEach has, but it is a bit nicer to read than the alternative. It’s certainly subjective though, and just like with forEach you’ll want to do what the rest of your other code is doing. You see it a ton in React and React-inspired libraries as the primary way to loop through an array and output a list of items within JSX.

function MyList({items}) {
  return (
    <ul>
      {items.map((item) => {
        return <li>{item}</li>;
      })}
    </ul>
  );
}

The for...in loop

This list of loops in JavaScript wouldn’t be complete without mentioning the for...in statement because it can loop through the fields of an object. It visits fields that are inherited through the object’s prototype chain too, though, and I’ve honestly always avoided it for that reason.

That said, if you have an object literal, then for...in might be a viable way to iterate through the keys of that object. Also it’s worth noting that if you’ve been programming JavaScript for a long time, you may remember that the order of keys use to be inconsistent between browsers, but now the order is consistent. Any key that could be an array index (i.e., positive integers) will be first in ascending order, and then everything else in the order as authored.

let myObject = {
  a: 1,
  b: 2,
  c: 3,
};

for (let k in myObject) {
  console.log(myObject[k]);
}

Wrapping up

Loops are something that many programmers use every day, though we may take them for granted and not think about them too much.

But when you step back and look at all of the ways we have to loop through things in JavaScript, it turns out there are several ways to do it. Not only that, but there are significant — if not nuanced — differences between them that can and will influence your approach to scripts.


All About JavaScript Loops originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.