DEV Community

Cover image for Rediscovering the Power of JavaScript in the Browser
Daniel Feldroy for Feldroy

Posted on

Rediscovering the Power of JavaScript in the Browser

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');
Enter fullscreen mode Exit fullscreen mode

Then I get the select element from the DOM:

const select = document.getElementById('grid-zip');
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)