The Future of AI Chips: Leaders, Dark Horses and Rising Stars

Featured Imgs 26

The interest and investment in AI is skyrocketing, and generative AI is fueling it. Over one-third of CxOs have reportedly already embraced GenAI in their operations, with nearly half preparing to invest in it. 

What’s powering it all, AI chips used to receive less attention. Up to the moment, OpenAI’s Sam Altman claimed he wants to raise up to $7 trillion for a “wildly ambitious” tech project to boost the world’s chip capacity. Geopolitics and sensationalism aside, however, keeping an eye on AI chips means being aware of today’s blockers and tomorrow’s opportunities.

Font Finder from Image: Essential Tools and Resources You Need to Know

Featured Imgs 23

Fonts play a crucial role in the design and branding of any project, from websites to advertisements. But what happens when you come across a font in an image and want to identify it? Luckily, there are several tools available that can help you find the exact or similar fonts quickly and easily. In this blog post, we will explore the best free font finder from image tools and resources that you need to know about. Whether you are a graphic designer, a web developer, or just someone who loves typography, this guide will help you identify fonts with ease.

Why Use a Font Finder from Image?

Before diving into the tools, it’s important to understand why a font finder from image is beneficial:

Efficiency : Saves time by quickly identifying fonts without manual searching.

Accuracy : Provides precise matches or similar fonts, ensuring design consistency.

Inspiration : Helps discover new fonts and design styles that can be incorporated into your projects.

Top Free Font Finder from Image Tools

WhatTheFont

WhatTheFont

WhatTheFont is one of the most popular font identification tools available. Simply upload an image containing the font, and WhatTheFont will analyze it to find a match from its extensive database.

Pros : Easy to use, extensive font library, supports various image formats.

Cons : Sometimes struggles with cursive or heavily stylized fonts.

Source

Font Matcherator

Font Matcherator

Similar to FontSquirrel, Fontspring Matcherator allows you to upload an image to find a matching font. It’s known for its robust matching algorithm and user-friendly interface.

Pros : Accurate results, easy to use, no account needed.

Cons : Some premium fonts might require purchase.

Source

WhatFontIs

WhatFontIs

WhatFontis.com is a versatile font identification tool that allows you to upload images or provide URLs to identify fonts. It has a large database of both free and commercial fonts.

Pros : Supports both free and commercial fonts, user-friendly interface, detailed results.

Cons : Requires a paid subscription for some features.

Source

Font Identifier

Font Identifier

FontSquirrel Matcherator is another excellent tool that allows you to upload images to find matching fonts. It specializes in free fonts, making it a great resource for designers on a budget.

Pros : Focuses on free fonts, user-friendly interface, accurate results.

Cons : Limited database compared to some paid tools.

Source

Artwork Flow

Artwork Flow

Artwork Flow provides a font finder tool as part of its suite of design and workflow management tools. It offers a straightforward way to identify fonts from images.

Pros : Integrated with other design tools, easy to use, accurate results.

Cons : Primarily part of a larger suite, which might be more than some users need.

Source

LikeFont

LikeFont

LikeFont is a simple and efficient font finder tool that allows users to upload images and get font matches quickly. It’s known for its ease of use and fast results.

Pros : Quick identification, easy to use, supports various image formats.

Cons : Limited database, primarily focused on Chinese fonts.

Source

Adobe Fonts

Adobe Fonts

Adobe Fonts offers a comprehensive font finder tool integrated with Adobe’s Creative Cloud. While not entirely free, you can use it with a free Adobe account to identify fonts from images.

Pros : High accuracy, integrates with other Adobe tools, extensive font library.

Cons : Requires an Adobe account, limited free features.

Source

Find My Font

Find My Font

Find My Font offers both an online tool and desktop software for font identification. It’s known for its accuracy and the ability to find both free and commercial fonts.

Pros : High accuracy, available as desktop software, supports offline use.

Cons : Desktop software requires purchase, online tool has some limitations.

Source

Font Ninja (Browser Extension)

 Font Ninja

Font Ninja is a browser extension that allows you to identify fonts directly from websites. It’s perfect for designers who want to explore fonts used on live websites.

Pros : Identifies fonts directly from websites, easy to use, provides font details and purchase links.

Cons : Requires installation, may not identify all custom fonts.

Source

Fontanello

fontanello

Fontanello is another browser extension that provides quick font identification on websites. It gives detailed information about the font used, including size, weight, and family.

Pros : Easy to use, provides detailed font information, works on various browsers.

Cons : Requires installation, limited to web fonts.

Source

Fount

Fount

Source

The post Font Finder from Image: Essential Tools and Resources You Need to Know appeared first on CSS Author.

How to Bulk Edit Featured Images in WordPress

Wp Plugins

Do you want to bulk edit featured images in WordPress?

It’s easy to add, change, and remove featured images from your WordPress posts and pages. However, changing the featured images for multiple pages can take a lot of time and effort.

In this article, we will show you how you can save time by bulk editing featured images in WordPress.

How to bulk edit featured images in WordPress

Why You Might Need to Bulk Edit Featured Images in WordPress

Featured images, also known as post thumbnails, are an important part of many websites.

Almost all modern WordPress themes come with built-in support for featured images and display them across different areas of your WordPress website including your blog archives.

As an important part of your WordPress blog or website, you’ll want to make sure your featured images look good and represent your brand.

With that in mind, at some point you may need to bulk edit your featured images in WordPress. For example, you might install a new WordPress theme and decide to design new featured images that better compliment your new theme.

You can change the featured image for an individual page or post in the standard WordPress editor. However, changing the featured image for lots of different pages and posts can be frustrating and time-consuming.

With that in mind, let’s see how you can bulk edit featured images in WordPress.

How to Bulk Edit Featured Images in WordPress

The easiest way to bulk edit featured images in WordPress is by using the Quick Featured Images plugin.

This plugin makes it easy to change every single featured image across your website. It also has detailed filters that allow you to change the featured images for specific categories, tags, post types, and more.

Before you start using the Quick Featured Images plugin, just be aware that this plugin doesn’t allow you to undo your bulk edits. This can cause problems if you change your featured images and are unhappy with the results.

With this in mind, it’s a good idea to backup your WordPress website before using this plugin. If you don’t already have a backup solution, then there are several great WordPress backup plugins that allow you to automatically backup your website.

After creating a backup, you’ll need to install and activate the Quick Featured Images plugin. If you need help, then please see our guide on how to install a WordPress plugin.

Upon activation, go to Featured Images » Overview in the left-hand menu. On this screen, click on the following link: ‘Bulk set, replace and remove featured images for existing posts.’

How to bulk edit featured images in WordPress

This screen allows you to bulk edit your featured images in a few different ways.

Your first option is the ‘Set the selected image as a new featured image’ radio button.

This setting finds all of the posts and pages that don’t currently have a featured image. You can then choose a new featured image and apply it to all of these pages and posts.

Bulk editing WordPress featured images

Another option is ‘Replace featured images by the selected image.’ You can use this to replace any existing featured images with a new image.

Next up is ‘Remove the selected image as featured image.’ This lets you choose a specific image, and then remove that featured image wherever it appears on your website. This is perfect for removing an outdated featured image, such as any image that features your site’s old logo.

After selecting one of these radio buttons, click on the Choose Image button.

Choosing a bulk edit action for your WordPress featured images

You can now choose the image that you want to use in the bulk edit. You can either select an image from your WordPress media library or upload a new file.

Once you’ve done that, scroll to the bottom of the screen and click on the ‘Next’ button.

Bulk editing featured images in WordPress

On this screen, you’ll be able to configure how WordPress performs the bulk edit.

The options you see may vary depending on whether you’re adding, changing, or removing a featured image. For example, if you selected the ‘Set the selected image as new featured image’ radio button then you can choose whether to override all existing featured images, or ignore them.

Override featured images in WordPress

To select which posts your bulk changes will apply to, scroll to the ‘Add a filter’ section.

By default, Quick Featured Images will apply its bulk edit to all pages and posts, across all of your site’s categories and tags.

If you don’t want to bulk edit every page and post, then you can create filters. These filters let you bulk edit featured images that meet a specific criteria.

Creating a filter for bulk editing featured images in WordPress

You can check more than one box. For example, you might check the ‘Post Type Filter’ and ‘Tag Filter’ boxes if you want to bulk edit posts that have a specific tag.

After checking one or more boxes, go ahead and click on the ‘Next’ button.

You will now see some settings that you can use to create your filter. For example, if you checked the ‘Post Type Filter’ box then you can choose between the ‘Posts’ or ‘Pages’ box.

The Quick Featured Images WordPress plugin

If you checked either the ‘Category Filter’ or ‘Tag Filter’ box, then you’ll have access to a dropdown menu.

You can open this dropdown and then choose the category or tag where you want to make the bulk edit.

Bulk editing WordPress featured images using filters

When you’re happy with how your filter is set up, scroll to the bottom of the screen.

You can then go ahead and click on the ‘Preview filtering’ button.

The Quick Featured Images plugin will now show a preview of all the pages and posts that will be affected by the bulk edit.

Previewing a bulk edit action

If you’re happy with the preview, then you can go ahead and click on the ‘Apply’ button.

Quick Featured Images will now bulk edit all of the relevant featured images across your WordPress website.

How to Set Multiple Images Randomly as Featured Images

When you bulk edit featured images in WordPress, you can sometimes end up using the same featured image for lots of different posts. These duplicate images can make your website look boring and repetitive.

With that in mind, you may want to set your featured images at random. You can use the Quick Featured Images plugin to select different images from your WordPress media library. The plugin will then add these featured images to your pages and posts at random.

In this way, you can bulk edit your images without creating lots of duplicate featured images.

To set your featured images at random, go to Featured Images » Overview and again click on ‘Bulk set, replace and remove featured images for existing posts’.

Once you’re here, click on ‘Set multiple images randomly as featured images.’

You can then click on the ‘Choose Images’ button to open the WordPress media library.

Replacing WordPress featured images at random

Here, hold down the Shift key and then click all the images that you want to randomly use as your featured images.

Once you’ve done that, click on the ‘Choose Images’ button. Then, scroll to the bottom of the screen and click on ‘Next.’

Bulk replacing multiple featured images in WordPress

By default, Quick Featured Images will apply these images to all your WordPress pages and posts at random.

Do you just want to use these images for certain content types, categories, or tags? Then you can create a filter by following the same process described above.

After adding a filter, Quick Featured Images will show a preview of all the pages and posts that it plans to update. You can check the thumbnail to see which image the plugin has randomly assigned to each page or post.

Replacing WordPress features images at random

If you’re happy with the preview, go ahead and click on ‘Apply.’ Quick Featured Images will now add the new images to your pages and posts.

How to Bulk Remove Featured Images in WordPress

Sometimes you may prefer not to use featured images on your website. For example, you might be trying to speed up your WordPress performance, or you may be using a theme that simply doesn’t look good with featured images.

You can use Quick Featured Images to easily remove all the featured images from your pages and posts.

You can also use filters to remove the featured images from pages, posts, or content that has a particular tag or category.

To bulk remove featured images in WordPress, simply click on the ‘Remove all featured images without existing image files’ radio button. You can then go ahead and click on ‘Next.’

Removing featured images from WordPress in bulk

Now, you can apply filters by following the instructions above.

Once you’ve created one or more filters, go ahead and click on the ‘Next’ button.

Building a bulk editor feature in WordPress

As always, the plugin will show a preview of all the pages and posts that it will change as part of this bulk edit. Since you’re deleting the featured image, it will show ‘No image set’ in the ‘Future Featured Image’ column, rather than a thumbnail preview.

If you’re happy to go ahead and remove the featured image for these pages and posts, then just click on the ‘Apply’ button.

Applying the bulk edit to your featured image in WordPress

We hope this article helped you learn how to bulk edit featured images in WordPress. You may also want to see our guide on the best Instagram WordPress plugins, and how to create automated workflows in WordPress to save time.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

The post How to Bulk Edit Featured Images in WordPress first appeared on WPBeginner.

Deep Learning in Image Recognition: Techniques and Challenges

Featured Imgs 26

In the vast realm of artificial intelligence, deep learning has emerged as a game-changer, especially in the field of image recognition. The ability of machines to recognize and categorize images, much like the human brain, has opened up a plethora of opportunities and challenges. Let's delve into the techniques deep learning offers for image recognition and the hurdles that come with them.

Convolutional Neural Networks (CNNs)

Technique: CNNs are the backbone of most modern image recognition systems. They consist of multiple layers of small neuron collections that process portions of the input image, called receptive fields. The results from these collections are then tiled so that they overlap, to obtain a better representation of the original image; this is a distinctive feature of CNNs.

Chris’ Corner: More Surprising Powers of CSS

Category Image 052

Kilian Valkhof has a good one this week, You don’t need JavaScript for that, as part of the HTMLHell yearly Advent Calendar (of blog posts). He opens with the rule of least power:

Choose the least powerful language suitable for a given purpose.

That’s fun for us CSS nerds, because CSS is a pretty low language when it comes to building websites. (It doesn’t mean you should try to write an accordion component in Assembly.) It means, as he puts it:

On the web this means preferring HTML over CSS, and then CSS over JS.

If you’re at the JS level already, it means preferring JS over a JS framework or meta language. It’s not that those things aren’t valuable (Heck, one of the purposes of CodePen is making using language abstractions and library easier) it’s that, well, it’s just a better idea to go lower level. There is less to download, less to break, higher chances of the browser optimizing it, higher chances it will be accessible, higher chances it will last over time. That stuff matters.

Killian opens with a custom “toggle” component, and really, component is probably too strong a word. It’s just a styled HTML checkbox. It’s not even all that much CSS, and no JS is used at all, to make this:

While I was reading, where I thought Killian was going was using an <input type="checkbox"> actually turn on and off features on a website. That’s the kind of thing that feels like definite-JavaScript territory, and yet, because of the classic “Checkbox Hack” (e.g. using the :checked selector and selector combinators) we actually can control a lot of a website with just a checkbox.

The ability to do that, control a website with a checkbox, has increased dramatically now that we have :has() in CSS. For instance:

<body>
  ... literally anywhere deep in the bowels of the DOM ...
  <input class="feature" type="checkbox">

We don’t have to worry about where in the DOM this checkbox is anymore, we can style anything there like this now:

body:has([.feature:checked]) .literally-anything {
  /* do styles */
}

We can start the styling choices way up at the body level with :has(), looking for that checkbox (essentially a toggle), and style anything on the page on if it is checked or not. That feels extraordinarily powerful to me.


Speaking of the mental crossover between CSS and JavaScript, Yaphi Berhanu’s Write Better CSS By Borrowing Ideas From JavaScript Functions was interesting. CSS doesn’t actually have functions (but just wait for it!) but that doesn’t mean we can’t consider how our thinking about the code can relate. I liked the bit about considering too many parameters vs not enough parameters. Yaphi connects that idea too too many selectors with too many repeat declarations, and yeah I can get behind that.

But where my mind goes is taking that lesson and trying to apply it to Custom Properties. I have seen (and written!) CSS that just takes Custom Property usage just too far — to the point where the code feels harder to reason about and maintain, not easier.

Like if you were going to make a variable for an animation…

.do-animation {
  animation: 3s ease-in 1s infinite reverse both running slidein;
}

You could decide that the right way to make this controllable and re-suable is something like:

:root {
  --animation-duration: 3s;
  --animation-easing: ease-in;
  --animation-delay: 1s;
  --animation-direction: reverse;
  --animation-fill-mode: both;
  --animation-play-state: running;
  --animation-name: slidein;
}

.do-animation {
  animation: var(--animation-duration) var(--animation-easing) var(--animation-delay) var(--animation-direction) var(--animation-fill-mode) var(--animation-play-state) var(--animation-name);
}

Maybe you love that? But I think it’s already going too far. And it could easily go further, since you could have another whole set of variables that set default fallbacks, for example.

It depends on what you want to do, but if your goal is simply “reusability” then doing like…

:root {
  --brandAnimation: 3s ease-in 1s infinite reverse both running slidein;
}

And then using it when you needed it is closer to baby bear’s porridge.


Little reminder: don’t sleep on View Transitions.

We won’t know what Interop 2024 will do until January, but based on the amount of upvotes from the proposals, I think it stands a good chance.

Jeremy Keith has a well measured take in Add view transitions to your website. It’s got links to good resources and examples on using it, like Tyler’s Gaw’s great post. It ends with an update and warning about how maybe it’s not such a great idea because it may “poison the feature with legacy content”. Meaning if too many people do this, the powers that be will be hesitant to change anything, even for the better. I agree that would suck if such a choice is made, as I do think there is room for improvement (e.g. transition groups). I dunno though, I think because this stuff is literally behind a feature flag, that’s enough of an at your own risk warning. If they want to change something that breaks any code I’ve shipped, I’m cool with that. I know the stakes.

I think we’ll start seeing more interesting examples and experiences soon. And! Gotchas! Like Nic Chan’s View transitions and stacking context: Why does my CSS View Transition ignore z-index? It is confusing. It’s like the elements kinda stop being elements when that are being transitioned. They look like elements, but they are really temporary rasterized ghosts. You can still select them with special pseudo element selectors though, so you should be able to get done what you need.


There is this inherit complexity with doing the whole Dark Mode / Light Mode thing on websites. There is both a system-wide preference that you can choose to honor, and that’s a good idea. And it’s likely that a site implementing this also offers a UI toggle to set the theme. So that’s two separate bits of preference you need to deal with, and the code likely handles them separately.

Christopher Kirk-Nielsen’s A Future of Themes with CSS Container Style Queries gives us a good taste of this. Let’s jump right to code:

/* No theme has been set, or override set to light mode */
html:where(:not([data-theme])),
:root[data-theme=light] {
  --color: black;
  --background: antiquewhite;
  /* … and all your other "variables" */
}

/* Apply dark mode if user preferences call for it, and if the user hasn't selected a theme override */
@media (prefers-color-scheme: dark) {
  html:where(:not([data-theme])) {
    --color: ghostwhite;
    --background: midnightblue;
    /* … and all your other "variables" */
  }
}

/* Explicitly set the properties for the selected theme */
:root[data-theme=dark] {
  --color: ghostwhite;
  --background: midnightblue;
  /* … and all your other "variables" */
}

If you read though that I think you’ll see, you need @media to deal with system preferences, then the HTML attributes to deal with a direct-set preference, and one needs to overlap the other.

Enter Style Queries. What they really are is: “when an element has a certain custom property and value, also do this other stuff.” Christopher’s “future approach” using them is more code, but I’d agree that’s more clean and readable.

/* Optionally, we can define the theme variable */
@property --theme {
  syntax: '<custom-ident>'; /* We could list all the themes separated by a pipe character but this will do! */
  inherits: true;
  initial-value: light;
}

/* Assign the --theme property accordingly */
html:where(:not([data-theme])),
:root[data-theme=light] {
  --theme: light;
}

@media (prefers-color-scheme: dark) {
  html:where(:not([data-theme])) {
    --theme: dark;
  }
}

:root[data-theme=dark] {
  --theme: dark;
}

/* Then assign the custom properties based on the active theme */
@container style(--theme: light) {
  body {
    --color: black;
    --background: antiquewhite;
    /* … and all your other "variables" */
  }
}

@container style(--theme: dark) {
  body {
    --color: ghostwhite;
    --background: midnightblue;
    /* … and all your other "variables" */
  }
}

Check out Christopher’s article though, there is a lot more to go over.


Let’s end with a little good ol’ fashioned CSS enthusiasm.

For many, many years, creating high-quality websites largely meant that designers had to fight what felt like an uphill battle to somehow make their ideas work in browsers. At the same time, sentences like “I’m really sorry, but this solution you designed just can’t be done with CSS” […]

This has now changed to the opposite.

Want to emulate and confidently design a layout that leverages the potential of CSS Grid in any of the major design tools like Figma, Adobe XD, or Sketch? Not possible. 

Matthias Ott, The New CSS

And:

I still keep Sass around, as well as PostCSS, for things that CSS just wont ever be able to do (nor should it), but they’re fading into the background, rather than being at the forefront of my mind when writing styles. And for small, simple projects, I don’t use them at all. Just pure CSS. I haven’t found it lacking.

Jeff Sandberg, CSS is fun again

How many users return to your site?

Featured Imgs 20

I have been working on my site for a long time now and I noticed something different. Back in 2019 when I started a campaign on Google Ads to promote my site the traffic kept going up day after day. Although it was a small increment it was going up nonetheless. Today, may website users are not coming back. I am losing traffic instead. The website is much better than before and I don't know what is wrong. are platforms like Tik-Tok stealing all the traffic?

Have you noticed stuff like this now or in the past?

And what is the normal retention rate for a memes website?

Thank you,
Farris

What ChatGPT Needs Is Context

Category Image 062

As part of my involvement at LeadDev NYC, I had the opportunity a short video message that would be part of a montage played for folks between the live talks. I decided to speak about the way engineers are enabling the future of products (you can watch it here).

It seems to me that questions like “how can engineers affect the future of (whatever)” sometimes come from a place of anxiety. And these days, there’s no greater source of that anxiety than the advances — and the impacts we imagine coming from those advances — in large language models (LLM), more broadly billed as artificial intelligence (AI).

Chris’ Corner: Little Useful Websites

Category Image 052

I came across Alexey Ardov’s work the other day. Looks like the color bug hit him pretty hard. I first saw this playground:

It’s awfully cool. I like seeing color palettes presented in the context of UI like that. Sometimes it’s hard to picture how it all might come together if colors are looked at too abstractly. It doesn’t exactly have an export tool, but a bunch of CSS custom properties are barfed out into a style attribute on the <body> if you were so inclined to use them for something.

Of course I thought: HSL is nicely used here, but what about the HDR color formats?! Seems like a good opportunity to set up P3 colors and non-P3 color fallbacks. I don’t think this fact is lost on Alexey, as they have lots more color experiments they have built. For example, this visualizer for looking at color models, which then it looks like got an upgrade to visualize more models (and gamuts).

I like looking at those things as they are a reminder of just how designed these color spaces are and how deep the rabbit hole can go. Before you know it, you’re designing extremely sophisticated accessible color palette generation tools.


Looking at these one-off single-purpose websites always puts me in the mood to share more. Aren’t you lucky that I save links to new ones that I see just for times like this.

CSS-Pattern

Temani Afif’s pattern site has some pretty sophisticated backgrounds that are done just with CSS backgrounds. Reminds me of Lea’s take on this from years ago. A grand tradition of CSS wizards.

Very easy to paste on into a Pen.

SpaceBadgers

Those little badge graphics that are super common at the top of GitHub repos, created with a super clean URL format.

Oh and hey they look great small but you can make them as big as you want and because they are SVG they scale up nicely.


Theme Toggles

Need a neat little animated toggle for Light Mode / Dark Mode? This site has a whole bunch of them:

Wasn’t much to pluck one over to a Pen, in case you need a reference there. I saw a little controversy on this as one of the usage options is as a <div>, which of course is not an interactive element. I’m not sure that’s fair, as you might use this as a visual adornment next to an interactive button, for example. And the React exports use <button> nicely.


Tree

I’m sorry I can’t explain it, but sometimes you have to update intended text to have a bunch of extra special ASCII characters that better represent a file tree.


Custom Shape Dividers

In the rectangular world of web design, sometimes just what you need is something… not rectangular.

The site provides SVG, HTML, and CSS for you to copy out, which, I’m sure you’re aware, plunking over to CodePen to play with is a snap. Gosh, isn’t CodePen useful? You should go PRO.

All About JavaScript Loops

Category Image 080

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.