loading...
Cover image for Rediscovering the Power of JavaScript in the Browser
Feldroy

Rediscovering the Power of JavaScript in the Browser

danielfeldroy profile image Daniel Feldroy ・2 min read

I've been doing JavaScript off-and-on for a long time, over 20 years. Periodically I forget that JavaScript is very powerful. That it's not the too-quickly-built language stapled into browsers anymore, that forces DOM hackery mitigated by jQuery. That I must use tools like Vue.js, React, etc. to make it work in the browser.

So when I rediscover yet again for the umpteenth time that JavaScript is powerful and works great natively with the DOM without frameworks, it's fun and exciting.

Let's explore a snippet of code I just wrote. I received a list of zip codes to be displayed in a dropdown list. First, I convert the zip codes to an array:

const zipCodes = `90004
90005
90006
90007
90008
<snipped for brevity>
`.split('\n');

Then I get the select element from the DOM:

const select = document.getElementById('grid-zip');

With the zipCodes array and select element ready, I construct the loop that adds the available zip codes to the form. Each line is commented t explain what I'm doing:

// Loop over the `zipCodes`, assigning each value to `zipCode`
// Python users take note I'm using a `for...of` loop to iterate
//   because `for...in` doesn't work as you would expect.
for (let zipCode of zipCodes) {
  // Create new option element, value and displayed text set to zip code.
  let option = new Option(zipCode, zipCode);
  // Inject the new option element into the select element.
  select.appendChild(option);
}

Altogether it looks like this:

// Convert the zip codes from a multiline string to an array
const zipCodes = `90004
90005
90006
90007
90008
<snipped for brevity>
`.split('\n');

// Get the select element from the DOM
const select = document.getElementById('grid-zip');

// Loop over the `zipCodes`, assigning each value to `zipCode`
// Python users take note I'm using a `for...of` loop to iterate
//   because `for...in` doesn't work as you would expect.
for (let zipCode of zipCodes) {
  // Create new option element, value and displayed text set to zip code.
  let option = new Option(zipCode, zipCode);
  // Inject the new option element into the select element.
  select.appendChild(option);
}

Posted on Apr 24 by:

danielfeldroy profile

Daniel Feldroy

@danielfeldroy

Engineer and writer. Co-author of Django Crash Course & Two Scoops of Django, Husband of @audreyfeldroy πŸ’˜, father of Uma 🍼

Feldroy

The little creative company behind Two Scoops Press, Impossible Hero Books, Fuzzy Rainbow, and an upcoming SaaS product.

Discussion

markdown guide