JavaScript tips

A collection of useful JavaScript functions and handy tips / study notes


// forEach
const x = [1,3,4,66,77];
x.forEach(v => {log (v*2)})


// Map
const x = [1,3,4,5,6,7,87]
let f =>x*2);


// Filter
const ages = [1,3,4,5,6,7,87];
let filteredAges = function(ages){
return (ages > 5);
let f = ages.filter(filteredAges);

Invoking a class

// Create Animal.js
export default class Animal{
constructor() {
console.log(“i am an animal”);
getClassType() {
return “Animal”;
// In Index.js
// import Animal from ‘./Animal’;
var animal = new Animal();

Clickable div – linked to a js function

Use a JavaScript function on a div – (flex)
function klik1() {

Use JavaScript to fetch data

Use Stringify to convert JSON to text

API – JS – HTML Demo

We use JavaScript to fetch from an API and create a new element in the html for each character in the API response

const fetchapi = fetch(“”)
.then(response => response.json())
.then(characters => showCharacters(characters.results));
const showCharacters = characters => {
const charactersDiv = document.querySelector(“#rmc”);
characters.forEach(character => {
const characterElement = document.createElement(‘p’);
characterElement.innerText = `Character Name: ${}`;
charactersDiv.append(characterElement); })};
<!DOCTYPE html>
<html lang=”en”>
<meta charset=”UTF-8″>
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<script src=””></script>
<script src=””></script>
<link rel=”stylesheet” href=”style.css”>
<div class=”container-fluid”>
<h1>My API Demo Page</h1>
<script src=”app.js” defer=”true”></script>
<div id=”rmc”></div>

Callback functions

Javascript callback functions explained.

As well as Python we’ll be adding semi regular tips and case studies of JavaScript code and features. In this article we’ll look at “callback” functions in JavaScript.

Let’s simplify them down to a very basic example which we show here:

    function cbdemo(a, b, callback){
    var callback = function(a,b){
        return a * b;
    var bx = cbdemo(2,3, callback);


The above will print to console.

We have a function calling another function inside itself.

Let’s use the response from the cbdemo function and display on the page

Now we get a nice bold “h2” number 6 viewable in our page in the browser!

Python Code

Creating a Python Package

Make your own python package and make it installable with pip install.

If you are wanting to create your own Python module for others to use and provide the best way to install it then is the way to go.

Watch how I learned to make a pip package and successfully created it

# Version of the gimdl package
__version__ = '0.0.2'
__author__ = 'DrPi'
__email__ = ''

from setuptools import setup

with open("", "r") as fh:
    long_description =

    description='Google Image Search Downloader - using API ',
    package_dir={'': 'src'},
        'Development Status :: 3 - Alpha',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: 3.9',
        'Operating System :: OS Independent',
    project_urls={  # Optional
        'GitHub': '',

    keywords='googleimages, images, search', 


$ python3 bdist_wheel sdist
$ sudo pip install python3-twine
$ twine register dist/gimdl-0.0.1.tar.gz
$ twine upload dist/gimdl-0.0.1.tar.gz
$ pip install gimdl

To upgrade package after change to source code:
$ python3 bdist_wheel sdist
$ twine –skip-existing dist/*


See also
Python Code

Google Image Search

And How To Use Python to automate it!

Step 1 – install Google-Images-Search
Step 2 – follow the installation instructions
env variables
Step 3 – set up the .env file with the API key and CX code you got when you generated your API credentials with Google.
Note : Make sure you enabled image search by setting it to “on”


from google_images_search import GoogleImagesSearch
from dotenv import load_dotenv
import os
# load the API key and CX code from .env file

# create an 'ims' sub directory if it doesn't already exists
if not os.path.exists('ims/'):
pathz = 'ims/'
# Get env variables
DK = os.environ.get('DEVELOPER_KEY')
CX = os.environ.get('CX')

# custom progressbar function
def my_progressbar(url, progress):
    print(url + " " + progress + "%")

# create google images search - object
gis = GoogleImagesSearch(DK, CX, progressbar_fn=my_progressbar)
# using contextual mode (Curses)
with GoogleImagesSearch(DK, CX) as gis:
    # define search params:
    _search_params = {"q": "tree", 
        "num": 3, 
        "safe": "off", 
        "fileType": "png"
        }, path_to_dir=pathz)

3 images of trees – here is one of them!

Limit Exceeded!

If you see “Error 429 when requesting…” or…


then you may have exceeded your daily allowance for API calls. So be careful when testing the code not to make too many requests.

Quota reached!

To install our code you can use pip:

pip install gimdl

Python Code

GitHub Support for password authentication

Support for password authentication was removed on August 13, 2021. Please use a personal access token instead.

This article shows you how to fix it!

remote: Support for password authentication was removed on August 13, 2021. Please use a personal access token instead.
remote: Please see for more information.

2 Steps to fix

(base) [rag@pipdem]$ git remote set-url origin

replace RGGH with your user (account) name

replace pipdem with your repo name

(base) [rag@pipdem]$ git commit -am "Update"
On branch main
nothing to commit, working tree clean

(base) [rag@pipdem]$ git push --set-upstream origin main

Enumerating objects: 16, done.
Counting objects: 100% (16/16), done.
Delta compression using up to 8 threads
Compressing objects: 100% (12/12), done.
Writing objects: 100% (16/16), 2.40 KiB | 1.20 MiB/s, done.
Total 16 (delta 1), reused 0 (delta 0)
remote: Resolving deltas: 100% (1/1), done.

$ ls -al ~/.ssh
# Lists the files in your .ssh directory, 
# (if they exist)

# By default, the filenames of the public keys # are one of the following: # If you don’t have an existing public # and private key pair then generate a # new SSH key

Check the GitHub instructions on how to generate a new SSH key:

Python Code

Remove non printable characters from text

import string

my_str = "htt😆, moon, boo, f🔥re "

def clean_words(my_str):
    for i in my_str.split():
        word = "" if (any([char not in string.printable for char in i])) else i