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

JavaScript – How To Execute a Function with Variables when Button is Clicked

If we take the following code, we call the Log function without the (). This calls the Log function every time the buttonObject is clicked.

// 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', () => {
  Log('Hello World!')
})

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

Our Log function gets triggered when the object is clicked, and the variable is passed properly. You can swap out thy arrow function with a nameless function ()

17 Must Know Git Commands

Quick and dirty cheat sheet for using git

Configure user

git config --global user.name "Username"

git config --global user.email "email@email.com"

Initialize git

git init

Check log of commits

git log

Check status

git status

Add all files to staging to be committed

git add -A

Setup .gitignore, to ignore files and directories

Example to add .DS_Store files to the ignore file.

echo ".DS_Store" >> .gitignore

Undo commits

git reset --hard

https://stackoverflow.com/questions/927358/how-do-i-undo-the-most-recent-local-commits-in-git

Branches

Setup a branch

git branch branch_name

Switch to a branch

git checkout branch_name

Merge branch to master

git checkout master
git merge branch_name

Remote Repository (GitHub)

https://docs.github.com/en/get-started/getting-started-with-git/managing-remote-repositories

You’ll can setup SSH keys to connect to GitHub.

https://docs.github.com/en/authentication/connecting-to-github-with-ssh/adding-a-new-ssh-key-to-your-github-account

git remote add origin git@github.com:OWNER/REPO.git

Setup origin

git push --set-upstream origin master

Upload files to GitHub

git push origin master

Verify remote origin

git remote -v

Set origin URL (Helpful if it has already been added)

git remote set-url origin git@github.com:OWNER/REPO.git

Install Guide for Pangolin Whisper Web Interface on Linux

Pangolin is a simple web interface for OpenAI’s Whisper system. Very easy and simple to use.

https://github.com/incredig33k/pangolin/

Add User

We’ll setup a new unprivileged user called pangolin.

sudo useradd -m pangolin
sudo passwd pangolin
su pangolin
cd
pip3 install whisper-ctranslate2
  or 
pip3.9 install whisper-ctranslate2
npm install https formidable@2.1.1 fs path url
wget https://github.com/incredig33k/pangolin/releases/download/pre-release/pangolin-web.zip
unzip ./pangolin_web.zip
cd pangolin_web
mkdir uploads

Change default port to 8443. It is possible to use 443, but we would need to run privileged

sed -i "s/443/8443/g" ./pangolin_server.js

Setup SSL Certificate

This assumes you already have Let’s Encrypt setup. We’ll create a certificate directory for Pangolin to use and then copy the certs there.

mkdir /home/pangolin/ssl
sudo cp /etc/letsencrypt/live/DOMAINNAME.COM/fullchain.pem /home/pangolin/ssl/
sudo cp /etc/letsencrypt/live/DOMAINNAME.COM/privkey.pem /home/pangolin/ssl/
sudo chown pangolin:pangolin /home/pangolin/ssl/fullchain.pem
sudo chown pangolin:pangolin /home/pangolin/ssl/privkey.pem

Now back in our web directory we can update the vars.js file like the following.
Note that we do need the full file path. Can’t use ~/

module.exports = {
key: '/home/pangolin/ssl/privkey.pem',
cert: '/home/pangolin/ssl/fullchain.pem'
}

Firewall rules

We can change the port Pangolin runs on by editing the listen port at the bottom of the pangolin_server.js file.

sudo firewall-cmd --add-port=443/tcp

Setting up systemd Service

Now we need to copy our service file and enable the Pangolin service.

sudo cp /home/pangolin/pangolin_web/pangolin.service /usr/lib/systemd/system/pangolin.service
sudo systemctl enable pangolin.service

Start the service

sudo systemctl start pangolin

CSS Tips

Here is some simple CSS code snippets that I have found useful.

Disable over scroll effect

html {
  overscroll-behavior: none
}

https://developer.mozilla.org/en-US/docs/Web/CSS/overscroll-behavior

Radial gradient to cover all of the background

html {
  width: 100vw;
  min-height: 100vh;
  background: radial-gradient(#676767, #232323);
}

Overlay that blurs and dims background

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.6);
  backdrop-filter: blur(5px);
  z-index: 7;
}

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