RapidTech1898 RapidTech1898
  • Home
  • Solutions
    • Portfolios
      • Webscraping
      • Excel Automation
      • AI Solutions
      • Auto Searching
      • Application
      • Automate PDF
      • Finance Worksheets
      • Word Automation
    • Ready To Use
    • Gigs
    • Datasets
  • FAQ
  • Feedback
  • Technic Help
  • WebDev
About me
More than 20 years experience in IT and Finance. I will automate your business with python tools, make excel templates and collect all the data you need from the internet!
Book me on Fiverr
Table of Contents
    1. OPERATOR, INPUT, OUTPUT
    2. STRING
    3. ARRAY
    4. CONTROL STRUCTURE AND ITERATION
    5. FUNCTION
    6. OBJECT
    7. CONSTRUCTOR, CLASS
    8. OBJECT ORIENTATION - 4 PILLARS OOP
    9. DOCUMENT, QUERYSELECTOR, EVENTLISTENER
    10. CSS VARIABLE HANDLING
    11. API ACCESS
    12. JQUERY
    13. DATE
    14. MATH
    15. LOCAL STORAGE
    16. MODULE EXPORTS
    17. ASYNCHRONOUS HANDLING
    18. REQUESTS
    19. NODE.JS
    20. TOOLS OVERVIEW
    21. EXAMPLE FULL STACK
  1. Current Rappers
    1. Add A Rapper:
    2. AZURE AUTHENTICATION
    3. PKG (create executable from node.js)
    4. HEROKU (hosting web-apps, running scripts in the cloud)
    5. NODEMAILER (send mails)
  • Send me a mail
  • Facebook
  • YouTube
  • GitHub
  • Gumroad
  • Eloquens
  • Book me on Fiverr
  • Send me an email
  • Buy me a coffee
  • Subscribe to updates
RapidTech1898 RapidTech1898
  • Mail
  • Facebook
  • YouTube
  • GitHub
  • Gumroad
  • Eloquens
  • Fiverr
RapidTech1898 RapidTech1898
  • Home
  • Solutions
    • Portfolios
      • Webscraping
      • Excel Automation
      • AI Solutions
      • Auto Searching
      • Application
      • Automate PDF
      • Finance Worksheets
      • Word Automation
    • Ready To Use
    • Gigs
    • Datasets
  • FAQ
  • Feedback
  • Technic Help
  • WebDev
  • Technic Help

Javascript Cheatsheet

text
Photo by Gabriel Heinzer on Unsplash

OPERATOR, INPUT, OUTPUT

Comments in Javascript

// Comment something

Multiline comments

/*Text xzy*/

Declare and assign string (possible with “” or ”) – “var” was the earlier version in the past for that

let intStr = "7"

Linebreak and Tab should not used – is morely css-stuff for formating

"/n /t"

Declare a variable and assign int (also signed int like -36)

let age = 24

Defining without assigning (var gets value undefined)

let var

Define 2 variables (one without value and one with value)

let var, age = 25

Define and assign 3 variables (a=5, b=8, c=12)

let [a, b, c] = [5, 8, 12]

Declare a constant and assign int (constant can not be changed like variables)

const age = 25

Declare and assign float (also signed float like +4.5763

let float = 5.14876

Change String to Int with base 10

let intNum = parseInt(intStr,10);

Declare and assign string

let floatStr = "5.14673"

Change String to Float

let floatNum = parseFloat(floatStr);

Defines+Assigns a variable (if user exists/has a value use that – otherwise initialize with “guest”

let v = user || "guest"

Open windows for entering something and store in const inp

const inp = prompt("Enter:")

Convert numeric value to string

num.toString()

2nd method to convert numeric value to string

num + ""

3rd method to convert number / int to a String

String(n)

Converts String to Number / Int

Number(s)

Shows the type of the variable as string (eg. “number”, “string”, “boolean”)

typeof (x)

Modulo / Rest of the division (=> 1)

7 % 2

Check 2 values / variables (result in true / false)

x == y

Equal value and equal type

x === y

Not equal

x != y

Not equal value and not equal type

x !== y

Greater, lesser, greater + equal , lesser + equal

>,<,>=,<=

Check if value is NaN (NotANumber) - eg. when converting with Number() and the value is no number

isNaN(x)

Check if n is a integer

Number.isInteger(n)

Makes variable +1

num++;

Outputs variable num in console

console.log(num)

Outputs element as table (eg. for objects, arrays)

console.table(object)

Alert information in a window

alert("Text!")

Alert some text with outputing the variable "name" between (using backticks "`"

alert(`Bla ${name} bla`)

Round to 2 decimal digits

n = n.toFixed(2)

Swap 2 variables

[x, y] = [y, x]

Exit javascript node program

process.exit(1)

STRING

Define a string

let s = "this is a test"

String with linebreak \n

let s = "this \n text"

extract only the first character

s.slice(0,1)

last char of a string

s.slice(-1)

slicing 2 chars from pos 3 and 4

s.slice[3,5]

slice from pos 3 to the end

s.slice[3]

shows the length of the string

s.length

Lowercase the whole string

s = s.toLowerCase()

Uppercase the whole string

s = s.toUpperCase()

Returns the second char of a string

s.charAt(1)

Search if "xyz" is int the string - returns the position where found - when not found returns -1

s.search("xyz")

Check if string/chars are in

s.includes("ee")

Replace "abc" with "xyz" for any occurrences in the string (only working for new browsers!)

sNew = s.replaceAll("abc","xyy)

2nd method for replacing everything (works for more browsers!)

sNew = s.replace(/abc/g,"xyz")

Concatenate 2 strings

sNew = s1.concat(s2)

Delete all whitespaces at the beginning and the end

s.trim()

Repeat string 3 times

s.repeat(3)

Split the words in a array

s.split(" ")

Delete all whitespaces at the beginning and the end

s.trim()

Fills leading zero in a string with allways 3 chars - eg. 006

s.padstart(3,"0")

Find Index of first occurence of this string

s.indexOf("ee")

Outputs the x character in the string => second char of the string (same as s[1])

s.charAt(1)

Get the last 3 chars of the string

s.slice(-3)

2nd variant: Get the last 3 chars of the string

s.substr(s.length-3)

Return Ascii-Code of the first character of the string

s.charCodeAt(0)

Returns True if the string end with "?"

s.endsWith("?")

Returns char for specific ascii-code

char = String.fromCharCode(65)

Check if char is in A-Z

char.match(/[A-Z]i)

Spread-Operator for string (=> build array with each character)

[...s]

Convert object-element to string

s = JSON.stringify(obj)

Convert datetime-object to string in format "yyyy-mm-dd"

calcDate.toISOString().split('T')[0]

ARRAY

Define an array

let arr = [];

Define an array and initialize it

let arr = [6,7,8];

Define multidim array

let mat= [[1,2,3],[4,5,6],[7,8,9]]

Get second element => 7

arr[1]

Access last element in array

arr[arr.length-1]

Get element in the matrix => 5

mat[1][1]

Replace the third element

arr[2] = 9

Returns list as a string => "6,7,8"

String(Arr)

Must allways be compared with triple = (only == would be wrong)

a1 === a2

Total count of the elemets in the array

arr.length

Extracts and delete element at the end (fast!)

arr.pop()

Extracts and delete element at the begin (slow!)

arr.shift()

Append new elements to the array at the end (fast!)

arr.push("X","Y")

Add new elements to the array at the beginning (slow!)

arr.unshift("Y","Z")

Copy elements from index 2 to index 3 => result is one char at index 2

ergArr = arr.slice(2,3)

Copy the last 2 elements of the array

ergArr = arr.slice(-2)

Delete 1 element beginning from index 2

arr.splice(2,1)

Delete 2 elements beginning from the index 0 - and insert the elements 10 and 11

arr.splice(0,2,10,11)

From index -1 delete 0 elements and add 3 and 4

arr.splice(-1,0,3,4)

Delete 2 elements beginning from the index 0 - and assign them to ergArr

ergArr = arr.splice(0,2)

x > 0) => Return true if all elements are bigger than 0

arr.every(x

Concatenate 2 arrays to one

ergArr = arr1.concat(arr2)

Returns first index position of element "xyz" (if not exists result is -1)

arr.indexOf("xyz")

Return the last index position of the element "xyz"

arr.lastIndexOf("xyz")

Check if string exists in the array

arr.includes("xyz")

Reverse the entire array

arr.reverse()

Split the words in a array

arr = varStr.split(" ")

Join the elements from the array in a string with ", " as seperator

varStr = arr.join(", ")

Check if object is an array (if array = true)

Array.isArray(arr)

Iterate through index of the array

for (let i=0; i < arr.lenth; i++) {do smth.}

Iterate through array elements

for (let elem of arr) {alert(arr)}

Convert a node-list to an array

arr=Array.from(document.querySelectorAll("a"))

2nd method for converting node-list to an array

arr=[...document.querySelectorAll("a")]

Concatenate the array to a string seperated by " "

arr.join(" ")

a > b ? 1 : -1) => Order array ascending

arr.sort((a,b)

a > b ? -1 : 1) => Order array descending

arr.sort((a,b)

Ordering long method with function

arr.sort(function(a,b) {return a > b ? 1 : -1}

Find max value in an array with spread operator

Math.max(...arr)

Find min value in an array with spread operator

Math.min(...arr)

Array Destrucuring Expl1 (a will be "Ha" and b will be "Ho"

let [a,b] = ["Ha","Ho","Hi","He"]

Array Destrucuring Expl2 (a will be "Ha" and d will be "He"

let [a,,,d] = ["Ha","Ho","Hi","He"]

Array Destrucuring Expl3 (a will be "Ha" and rest will be ["Ho","Hi","He"]

let [a,...rest] = ["Ha","Ho","Hi","He"]

Swapping values (a will be b and b will be a)

[a,b] = [b,a]

Iterate trough array by index and element (with shortform)

Outputs index and Outputs element of array
(return is not working here - forEach loops are allways running for all elements)

arr.forEach((elem,idx) => {
console.log(idx)
console.log(elem)
})

Iterate through array by elements and index (with longform)

Outputs index and Outputs element of array
(return is not working here - forEach loops are allways running for all elements)

arr.forEach(function(elem,idx) {
console.log(idx)
console.log(elem)
})

Iterate trough an array with 1sec pause at every element

names.forEach((name, i) => {
setTimeout(() => {
display(name);
}, i * 1000);
});

Map Method - Short Method (Maps a functionality to all elements of the array - every element multiplicated by 2)

    let newarr = arr.map(x => x * 2);

Map Method - Long Method (for more code)

    let newarr = arr.map (function(x) {
x = x * 2
}

Filter Method - Long Method (Filters all values which are > 6 eg. in a new array)

let newarr = arr.filter (function(x){
if (x > 6) {
return true
}
})

Filter Method - Short Method in one line

let newarr = arr.filter(x => x > 6);

Reduce Method - for doing something with the array and output / calculate something
"total" is the new calculation element - result of this is the sum of all elements of the array
every element is added to total - 0 is the default value of "total"

erg = arr.reduce ((total, elem) => {
return total + elem
},0)

FindIndex Method - find the index-location of an element in the array (if nothing is found it returns -1)

let idx = arr.findIndex(x => {
return x < 10;
})

Some Method - checks whether at least one element in the array passes the test - returns boolean answer
1st line defines the check function - 2nd line checks the array with the function

const even = (element) => element % 2 === 0;
arr.some(even)

Every Method - checks whether all elements in the array passed the test by the defined function - return boolean answer
1st line defines the check function - 2nd line checks the array with the function

const isLower = (elem) => elem < 40;
arr.every(isLower)

example for a setTimeout
the first and second message will appear immediately - the middle message only after 2 seconds

console.log('First message!');
setTimeout(() => {
console.log('This message will always run last...');
}, 2000);
console.log('Second message!');

CONTROL STRUCTURE AND ITERATION

if (condition is true) {
=>Do something
}else if (condition is true){
=>Do something else
}else{
=>Default else
}

If structure with logical and

if (a == 9) && (b == 7) { c = "Hurra!" }

If structure with logical or

if (a == 9) || (b == 7) { c = "Hurra!" }

If structure with logical not

if !(a > 13)

switch (expression) {           // Switch expression for multiple options
case value1: case value 4 // Do something when expression is value1 or value4
// Do something
break; // Break necessary for any case / value
case value2: // Do something when expression is value2
// Do something
break;
default: // When no case is mathing - then do this
=> Do something
break;
}

Iteration from 1 to 5 with for-loop

for (let i=1; i<=5; i++) {}

Iteration backwards from 3 to 0 with for-loop

for (let i=3; i>=0; i--) {}

Iterate through an array

for (let i=0; i

Iterate through a string

for (let char of text) {}

Iterate through the keys of an object

for (let key in obj) {}

For loop with pause at any iteration

for (let i = 0; i < 5; i++) {
setTimeout(() => { // Pause at any iteration for 5 seconds / 5000 ms
console.log("hey");
}, i * 5000);
}

While loop with break condition

while (x < 4) {
if xyz === "abc" {break}
}

Do While loop with break condition

do {} while (x < 4)

Endless while loop - has to be exited somewhere

while (true) {}

Iterate through array by elements (x)

arr.forEach((x) => {
console.log(x)
})

Are all falsy values - can checked with if (xyz)...

0,"",'',null,undefined,NaN

Ternary Operator for if - if isNight=true then s=Night - else s=Day

isNight ? s="Night" : s="Day"

FUNCTION

Normal Function Decleration

function addFunc(x=0,y=0) {    // Define a function    - with default value 0 if no input is given
let erg = x+y // Calculate erg
return erg} // Return erg value
addFunc(3,5) // Function Call

Function Expression (used for anonymous functions)

const add = function(x,y) {...}     // Define a function expression (function is assigned to an variable
add(3,5) // Function Call

Anonymous Function with Fat Arrow syntax

const add = (x,y) => {...}
add(3,5) // Function Call
let h = a => a % 3 // Even shorter without parentees

return-statement with "?" or "||"

return (age > 18) ? true : console.log('Did parents allow');    // When age > 18 returns true - otherwise output something in the console
return (age > 18) || console.log('Did parents allow'); // Same logic with "||"

Use Rest Parameters to accept any number of arguments

function max(...numbers) {                // Any numbers of arguments
=> do something with a loop
}

AddEventListener with parameters in the function

document.querySelector("#dayToday").addEventListener("click",function() {   // define addEventListener as normal but use "function ()"
toggleBackground("today", 6) // call the function with parameters inside
}, false);

OBJECT

Define an object (literal syntax)

let obj = {}

2nd method to define object (construtor syntax)

let obj = new Object()

properties = attributes of the object (eg. color, shape, minutes, seconds)

Define an object and initialize it

let obj = {
name: "John",
age: 30, // last "," i allowed and called trailing / hanging (its easier so to add/remove/move properties of the object)
shout() { // Defines a method for the object
return "Hurra!"
}
}

Access property / shows value of the key "name" (1st method) => John (dot.notation)

obj.name

Shows value of the key "name" (2nd method) => John (bracket notation)

obj["name"]

Shows key "age" of the object => 30 (dot notation)

obj.age

Add a new propertie to the object

obj.newOne = "xyz"

Add a new method to the object

obj.newMethod = function(var) {...do someth...}

Call the new method

obj.newMethod(25)

Check if key is in the object

age in obj

Delete a property of an object (dot notation)

delete obj.age

Delete a property of an object (bracket notation)

delete obj["age nr"]

Check if a property / method is in an object

if ("property" in obj) {...}

Read the keys of an object into an array

arr = Object.keys(obj)

Read the values of an object into an array

arr = Object.values(obj)

Read alle key / value pairs of an object into an (nested) array

arr = Object.entries(obj)

Check if xyz i part of the object

obj.hasOwnProperty("xyz")

Check if Object is empty

Object.keys(obj).length === 0 && obj.constructor === Object

Iterate through the keys of the object and outputs key and value

for (let key in obj) {
console.log(key, obj[key]
}

Other example for an object
teacher count must have quotations cause it contains a space character

var school = {
name: 'The Starter League',
location: 'Merchandise Mart',
"teacher count": 10
students: 120,
teachers: ['Jeff', 'Raghu', 'Carolyn', 'Shay']
};

CONSTRUCTOR, CLASS

4 Pillars of Object Orientation
Make a Object with the old method

function MakeCar (carMake,carModel,carColor){       // Define the constructor function
this.make = carMake, // Define properties for the constructor
this.carModel = carModel, // "this" is referencing to the actual object
this.carColor = carColor,
this.honk = function(){ // Define a mtehod for the constructor
alert(`BEEP ${this.carModel} BEEP`) // Alert something when the method is called (with prop this.carModel)
}
}
let car1 = new MakeCar("Honda","Civic","black") // Create a new car1 (with codeword "new")
let car2 = new MakeCar("Tesla","Roadster","red") // Create a new car1

Make a Object with the shorthand

let robotFactory = (model, mobile) => {             // Define constructor with two parameters
return {
model: model, // property1
mobile: mobile, // property2
beep(){ // method
console.log("Beep Boop")
}
}
}

Make a Object with the new class method (longhand)

class MakeCar{                                      // Define the classs
constructor (carMake,carModel,carColor){ // Define properties for the class
this.make = carMake // Assign the properties of the class to the concrete individual object
this._carModel = carModel // "this" is referencing to the actual object (use "_" to indicate that this properties should only changed with getters)
this.carColor = carColor
}
honk(){ // Define a method for the class
alert("BEEP ${this.carModel} BEEP") // Alert something when the method is called (with prop this.carModel)
}
}
let car1 = new MakeCar("Honda","Civic","black") // Create a new car1 (with codeword "new")
let car2 = new MakeCar("Tesla","Roadster","red") // Create a new car1

Give new property and function

MakeCar.prototype.wash = true                       // Give all the created cars from the class "MakeCar" a new property "wash"
MakeCar.prototype.newFunc = function () { // Give all the created cars from the class "MakeCar" a new function "newFunc"
console.log("We have a new function!"
}

Define a getter in the class (returns the name-property of the class-element
So when somebody is requesting for obj.name - the return will be for _name
When somebody is changing with obj.name = "xzy" - nothing happens, cause the property is named _name
Of course with obj._name there would be a change possible - but this is very bad practice cause due the "_" the variable should not be touched

  get name() {
return this._name;
}

Inherit a class from another class
The class Cat inherits from the class Animal with the keyword "extends"
With super - the attributes name and age will be taken / inherit from the class Animal

class Animal {
constructor(name, age){
this.name = name
this.age = age
}
speak() {
console.log("Blablabla")
}
}

class Cat extends Animal {
constructor(name, age, usesLitter) {
super(name, age);
this._usesLitter = usesLitter;
}
}

Define static function - this can only be done for the class itself (or for the instances of the class)

    static generateName() {...}

OBJECT ORIENTATION - 4 PILLARS OOP

DOCUMENT, QUERYSELECTOR, EVENTLISTENER

4 pillars of object orientation in practice
Add Eventlistener

document.querySelector('#check').addEventListener('click',func1)        // New Method / create an Event Listener / execute function "func1" when mouse is clicked
...'onmouseenter'... // New Method / create an Event Listener / exceute function "func2" when mouse-cursor is over the element
...'input'... // Event Listener with trigger input
...'change'... // Event Listener with trigger every change in the element
...'mousemove'... // Event Listener with trigger when mouse is moved over the element
...'transitionend'... // Event Listener with trigger when the transistion ends
document.getElementById("green").onclick = funcGreen // Old Method / Waiting for click on this element (by ID) as a "event-listener"

E.G. document.querySelector('idBlue').addEventListener('click',changeToBlue)

function funcGreen() {                                      // Define function
document.querySelector("body")
.style.backgroundColor = "rgba(241,63,247,1)" // Change BackGroundColor-Style to rgba-color green (as inlinecode in the rendering - not in the html-code)
document.querySelector("body").style.color = "white" // Change Fontcolor to white (as inlinecode in the rendering - not in the html-code)
}

Use EventListner for alle elements with a specific class

let elements = document.querySelectorAll(".panel");             // Select all elements with class "panel"
elements.forEach(elem => elem.addEventListener("click",func1)) // Iterate trough every element and create EventListener - when clicked start func1 for the element
function func1() { // Function is run with the activated Element for the EventListener
this.classlist.toggle("newClass")}

Old Method / Select an element by ID

document.getElementById

New Method / Select (first) a or .class or =>id

document.querySelector("xyz")

Select all elements which have h2 and store it in the constante c

const c = document.querySelectorAll("h2")

Element-Listener waiting for a click7

.onclick

Change BackgroundColor

.style.backgroundColor

Change Font Color

.style.color

Hide element in DOM

.style.display = "none"

Change Text of the selected element

.innerText = "xyz"

Concatenate 3 variables with space between (old method)

.innerText = v1 + " " + v2 + " " + v3

Concatenate 3 variables with space between (new method with the "`"-char called template string)

.innerText = `${v1} ${v2} ${v3}`

Read the value/text of the field

.value

Show the ID of the selected element

.id

Set the src of a image

.src

Change class of the element to "MyClass"

.className = "MyClass";

Manipulate classes informations

.classList

Toggle the class hidden (when triggered class is deleted OR added (when the next click occured)

.classList.toggle("hidden")

Add the class hidden

.classList.add("hidden")

Check if element contains class "cl"

.classList.contains("cl")

Remove the class from the element

.classList.remove("wiggle")

Call function "func1" every second (1000ms)

setInterval(func1, 1000)

{do something},10000) => Do something any 10 seconds

setInterval(()

Func1 is running with a delay of at least 2 seconds (with own seperate function)

setTimeout(func1, 2000)

{do something},1000) => Do something and wait 1 second (function direct in the statement)

setTimeout(()

Add some elments to an ul-element

var li = document.createElement("li")           // create new li-element
li.textContent = "new text" // add text to the new element
document.querySelector("ul").appendChild(li) // append the new li-element to the ul-element

CSS VARIABLE HANDLING

Read all control- and input-elements

let inputs = document.querySelectorAll(".controls input");

input.addEventListener("change", handleUpdate)); => Wait for change in any element and call the function "handleUpdate"

inputs.forEach(input

Handle Update

function handleUpdate() {
const suffix = this.dataset.sizing || ''; // read the sizing-parameter for the triggered element (used data-sizing in html)
document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix);
// set the variable in css (name according to --name in css)
// use the value from the read element from the adventlistener
// and use the suffix which is read above
// full property looks eg. like "--spacing: 10px"
}

API ACCESS

request data from API get data back in JSON format
Reading / Fetching the informations from an API-url
Request the API-content and output as JSON-information
alle the information is stored in data
last part is the error handling when something wrong happens

fetch(url)
.then(res => res.json())
.then(data => {
console.log(data)
})
.catch(err => {
console.log("error ${err}")
});

Using a API using async / await

async function getSomethingFromAPI() {
const res = await fetch("url").catch(e => {
console.log("Error - Fetch not possible...")
})
if (!data) {
console.log("Error - Data / JSON wrong...")
} else {
const data = await res.json()
console.log(data)
}
}
getSomethingFromAPI()

JQUERY

ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"> => include before body-tag