3 different ways to loop through arrays in JavaScript in 2023

There are at least 3 different ways to loop over arrays in JavaScript. The three we will go over in this article are the

  1. forEach
  2. for of
  3. for loop

Using forEach to loop through an array

The forEach takes a callback function that is executed for element of the array. The callback function’s first argument is the element of the array.

const myArray = ["First", "Second", "Third"]

myArray.forEach(function(myElement, index, array) {
  console.log(`My Element is ${myElement}, index is ${index}, and array is {$array}`
}

Couple things to note about forEach

  1. You can not break out of the loop, it has to go through every element in the array.
  2. It is a higher order function
  3. The first argument is the array element, the second is the index, and the 3rd is the array itself

Using for of to loop through an array

Using the for of loop, we can loop through the array with

const myArray = ["First", "Second", "Third"]

for (const [i, myElement] of myArray) {
  console.log(`My Element is ${myElement}, index is ${i}`)
}

Looping through an array with a for loop

And using just a simple for loop, we can do

const myArray = ["First", "Second", "Third"]

for (let i = 0; i < myArray.length; i++) {
  console.log(`My Element is ${myarray[i]}, index is ${i}`)
}

https://stackoverflow.com/questions/50844095/should-one-use-for-of-or-foreach-when-iterating-through-an-array

How to Display Pictures on NodeJS http Server

If you are using http for a NodeJS application, you may have run into an issue where none of your images are loading on a site. Instead you are greeted with nice little “no image” logos.

The issue is that our NodeJS server has not been instructed to load anything other than index.html. So other things like images, or even CSS from our style.css file wont work properly.

To fix the issue, we need to to tell NodeJS what to do when other files are requested. As a side note, the person browsing the site may not be requesting the resources directly, but index.html file requests the css file or images hence creating a new web request.

Let’s say we are starting with the following code as a starting point.

var http = require('http')
var fs = require('fs')
var path = require('path')
var url = require('url')

http
  .createServer(function (req, res) {
    let pathname = url.parse(req.url).pathname
    if (
      req.method === 'GET' &&
      (pathname === '/' || pathname === '/index.html')
    ) {
      res.setHeader('Content-Type', 'text/html')
      fs.createReadStream('./index.html').pipe(res)
      return
    }
    return res.end()
  })
  .listen(3000)

Our HTML code is very basic.

<html>
<head>Hello World!</head>
<br />
<body><img src="./image.png" width="128"></body>
</html>

When we launch our server with

$ node server.js

We get

The Fix

Essentially what we need to do is tell the server what to do when image.png is requested.

So we can add the following to our server code before the line “return res.end()”

    if (req.method === 'GET' && pathname === '/image.png') {
      res.setHeader('Content-Type', 'image/png')
      fs.createReadStream('./image.png').pipe(res)
      return
    }

And voila! it is fixed!

Taking it Further

We can improve on this and add a favicon, as well as our style sheet.

var http = require('http')
var fs = require('fs')
var path = require('path')
var url = require('url')

http
  .createServer(function (req, res) {
    let pathname = url.parse(req.url).pathname
    if (
      req.method === 'GET' &&
      (pathname === '/' || pathname === '/index.html')
    ) {
      res.setHeader('Content-Type', 'text/html')
      fs.createReadStream('./index.html').pipe(res)
      return
    }
    if (req.method === 'GET' && pathname === '/image.png') {
      res.setHeader('Content-Type', 'image/png')
      fs.createReadStream('./image.png').pipe(res)
      return
    }

    if (req.method === 'GET' && pathname === '/favicon.ico') {
      res.setHeader('Content-Type', 'image/x-icon')
      fs.createReadStream('./favicon.ico').pipe(res)
      return
    }

    if (req.method === 'GET' && pathname === '/style.css') {
      res.setHeader('Content-Type', 'text/css')
      fs.createReadStream('./style.css').pipe(res)
      return
    }
    return res.end()
  })
  .listen(3000)

This will let us put a favicon.ico image to use as a favicon it will use style.css to stylize the website.

We should note that while the above code does work, you will most likely want to use something like express.
https://github.com/expressjs/express

You can also find better code implementations others of done online.

https://stackoverflow.com/questions/5823722/how-to-serve-an-image-using-nodejs

How To do a simple Timer in JavaScript

https://www.freecodecamp.org/news/javascript-timers-everything-you-need-to-know-5f31eaa37162/

Here are a couple different ways to do timers in JavaScript

Every X seconds do

We can use the setInterval global function to run code (myFunc()) every second.

setInterval(() => {
  myfunc()
}, 1000)

Execute X after Y seconds

Replace console.log with the code you want to execute with a delay.

setTimeout(() => {   
  console.log("Hello World")
}, 1000)

JavaScript Functions

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

What is a function? A function is a block of code that does a particular task.

JavaScript has 3 different types of functions

  1. Function Declaration
  2. Function Expression
  3. Arrow Function Expression

Functions can also be named, or anonymous. There are a couple helpful things anonymous functions can help with.

Function Declaration

Function declaration’s are your standard functions. Syntax is as follows

function add(num1, num2) {
  return num1 + num2
}


console.log(add(1, 2));

Function Expression

A function expression can be thought of as a variable that is a function. We define function expressions like so

const add = function myFunction (num1, num2) {
  return num1 + num2;
}

console.log(add(1, 2));

Function expressions can be anonymous. To make the above function anonymous, remove “myFunction”. It would then read “function (num1, num2)”

Typically it is a good idea to name your function expressions as debugging anonymous functions can be a bit more difficult.

A warning about function expressions. They are not hoisted like function declarations. Just be sure that you define the function expression before you call it.

Arrow Function Expressions

Arrow functions are a compact version of function expressions that are always anonymous. They can be a bit tricky to get the syntax correct. Refer to the link below to get a better list of syntax and use. Arrow functions also have some other limitations. They do not have bindings to this, arguments or super.

const add = (num1, num2) => num1 + num2;

console.log(add(1, 2);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Anonymous Functions

Anonymous functions are functions that don’t have a name. For instance

function () {
  do something
}

Does not have a name and is therefore an anonymous function. Arrow functions are always anonymous.

When would you need to use an anonymous function?

One good example is when you want to call a named function from a timer, or when a button is clicked. For instance

// Find object id myButton
let buttonObject = document.getElementById('myButton')  

// Add an event listener, and run Log function when clicked.
buttonObject.addEventListener('click', Log) 
// If we call Log(), it will immediately trigger the function

function Log () {
  console.log("Hello World!")
}

But what if we want to pass in a variable to the Log function? We can’t run Log('some text') as the function will run before we click the object.

We can however wrap the Log function inside of an anonymous function like so

let buttonObject = document.getElementById('myButton')

// Now Log() function will be run with the variable getting passed.
buttonObject.addEventListener('click', function () {
  Log('Hello World!')
})

function Log (textVariable) {
  console.log(textVariable)
}

And our Log function gets triggered when the object is clicked, and the variable is passed properly. You can swap out function () with an arrow function () =>

How To Play an Audio file in JavaScript

Here is a quick and simple way to play an audio clip in JavaScript

const audio = new Audio('path/to/audio.mp3')
audio.play()

That is literally it.

You can set “audio.play()” to where ever you need in your code so it gets triggered when needed.

https://stackoverflow.com/questions/9419263/how-to-play-audio

JavaScript – The media resource indicated by the src attribute or assigned media provider object was not suitable.

If you receive the following error,

The media resource indicated by the src attribute or assigned media provider object was not suitable.

It could be because your media file is not supported. Try converting your audio file to a different format.

https://stackoverflow.com/questions/57246199/domexception-the-media-resource-indicated-by-the-src-attribute-or-assigned-med

JavaScript Basic Spread and Rest (…) usage

The Spread and Rest operators i.e. the three dots (…) can be used to make code cleaner and more concise.

Difference between Spread and Rest

Spread: Works on elements on the right side of the = operator, and breaks them out into individual elements.

Rest: Works on the left hand side of the = operator, and compresses them into an array.

Using Spread to Iterate over Arrays

Spread works on iterables like strings, arrays, maps and sets.

The spread operator operates similar to taking all the elements out of an array and operating on them or writing them to a new array. Say for instance we have an array of computers and we want to log each element to the console.

const computersA = ['Acer', 'Apple', 'ASUS']

We can log each element by running

console.log(computersA[0], computersA[1], computersA[2])

Or we can use the spread operator

console.log(...computersA)

The output is the same.

Joining Arrays

We can also use the spread operator to join two arrays together. Say we have two arrays

const computersA = ['Acer', 'Apple', 'ASUS']
const computersB = ['HP', 'Dell', 'Lenovo']

And we want to concatenate them together. We can do that simply by

const computerAll = [...computersA, ...computersB]

Rest Example

Rest is simply the opposite of spread. Spread take an item like an array and expands it out into elements we can use. Rest takes elements and packs them into an array. This can be extremely helpful if we want to pass in an unknown amount of elements into a function for processing.

const computersA = ['Acer', 'Apple', 'ASUS']
function writeToLog (...arr) {
  for (const element of arr) {
    console.log(element)
  }
}

Now we can call the function with as many elements in the array and they will all get logged to the console.

writeToLog('Razer', 'Alienware', 'Legion')

We could also use both the Spread and Rest functions

const gamingLaptops = ['Razer', 'Alienware', 'Legion']
writeToLog(...gamingLaptops)

Now as we add more laptops to the gamingLaptops array, the function will automatically process the line and write to console.

https://www.freecodecamp.org/news/three-dots-operator-in-javascript/

Send an Email with Node.JS

In this post, we will be using Node.JS and the nodemailer library to send email. We need to have an email account with an email provider to send email. Gmail or some other email provider should work.

Prerequisites

First lets install some tools

sudo apt install nodejs npm

Now lets install nodemailer

npm install nodemailer

Writing the Code to Send Email

Now that we have nodemailer installed, we can write or copy our code. Create a file called maill.js and make it look similar to the following.

// We can pass in the email text as an argument
const emailText = process.argv.slice(2);
// Or we can just have it as a variable
// const emailText = "NodeJS test email message."
console.log("args " + args)

const nodemailer = require("nodemailer");

const transporter = nodemailer.createTransport({
  host: "mail.emailserver.com",
  port: 465,    //  If your email server does not support TLS, change to 587
  secure: true, // If you are using port 587, change to false.  Upgrade later with STARTTLS
  auth: {
    user: "smtpuser@emailserver.com",
    pass: "notpassword)",
  },
});

const mailOptions = {
  from: 'user@emailserver.com',
  to: "touser@email.com",
  subject: 'Test Email using NodeJS',
  text: `${emailText}`
};

transporter.sendMail(mailOptions, function(error, info){
  if (error) {
    console.log(error);
  } else {
    console.log('Email sent: ' + info.response);
  }
});

Update the following variables

  • host: to your host email server
  • user: to the email user that is sending email. It should have an account on the email server
  • pass: password for your email user that is sending the email
  • from: email address that is sending the email
  • to: email account(s) you are sending email to
  • subject: subject of your email

Now we can proceed to send email

Sending Email

We can now run the code by saving our file and running it directly with NodeJS

nodejs ./mail.js "This is the body text for the email"

Hit Return and look for the email. If something went wrong, it should throw an error.

You can change the emailText variable if you would rather have the message body inside the code.

Code Explanation and Notes

A little explanation on the code.

The second line “const emailText = process.argv.slice(2);” is used to pass in a command line argument to use as the text for the body of the email. You can delete the line and uncomment line 4 if you would rather use a variable inside the code.

Your email server should support using SSL/TLS on port 465. If it does not, you may need to use STARTTLS which uses port 587, and then set secure to false. STARTTLS should upgrade the connection to be encrypted. But it’s opportunistic. You can read more about STARTTLS, SSL/TLS here https://mailtrap.io/blog/starttls-ssl-tls/

You can change the “to: ” in the mailOptions object to an array of email addresses to send the email to multiple people at once.

to: ["email1@email.com", "email2@email.com", "etc"],

JavaScript check if a string matches any element in an Array

In the following code we will be checking a string and check if any of the words in the string match some or any elements in an array.

We can imagine that our “stringToCheck” variable is an email or message response. We want to know if it contains a mention to afternoon, tomorrow, or evening. Presumably so we can automate something. Note that the matches are case sensitive.

// Check if any text in a string matches an element in an array

const stringToCheck = "Let's grab lunch tomorrow";
const arrayToCompareTo =["afternoon", "tomorrow", "evening"];

// We are checking to see if our string "stringToCheck" 
// Has any of the words in "arrayToCompareTo".
// If it does, then the result is true.  Otherwise false.
const resultsOfCompare = arrayToCompareTo.some(checkVariable => stringToCheck.includes(checkVariable));

if (resultsOfCompare == true){
    console.log(stringToCheck + " Contains a value in our Array " + arrayToCompareTo);
} else {
    console.log(stringToCheck + " Does NOT contain a value in our Array " + arrayToCompareTo);
}

More examples and ways to do it are available at the following link.

https://stackoverflow.com/questions/37428338/check-if-a-string-contains-any-element-of-an-array-in-javascript

Simple JavaScript Object – Code Example

Below is a code example for creating a basic object and using a function to calculate the fuel economy.

// New object Car
const car = {
    make: 'Honda',
    model: 'Civic',
    topSpeed: 100,
    tankCapacity: 10,
    range: 300,
    MPG: function() {
        this.mpg = this.range / this.tankCapacity;
        return this.mpg
    }
}

car.MPG();  // We need to call this to calculate the MPG, otherwise we get undefined

console.log(`My car is a ${car.make + " " + car.model }, can go ${car.topSpeed}/MPH, and gets ${car.mpg}/MPG `)

// Alternatively we can call the function car.MPG() directly.  
// This keeps us from having to run the function before logging.
console.log(`My car is a ${car.make + " " + car.model }, can go ${car.topSpeed}/MPH, and gets ${car.MPG()}/MPG `)