Index

Javascript

basics

check if variable exists
if(typeof selenium === 'undefined') {
if(typeof selenium !== 'undefined') {
get the type of a variable
typeof [variable]
convert variable to a number
Number([variable])

strings

trim
str.trim()
contains substring
string.includes(substring)
change case
toUpperCase()
toLowerCase()
regex split
str.split([regex], [limit])

arrays

initialize empty array
var a = [];
initialize array with values
var a = [ 0, 1, 2 ]
iterating elements
myarray.forEach(myFunction);
extracting a slice
myarray.slice(3)
myarray.slice(3,5)

functions

defining a function
function foo() {
    alert('foo');
}
parameters
function myFunction(p1, p2) {
  return p1 * p2;
}
default parameters
function sum(p1, p2=0) {
  return p1 + p2;
}

objects

// define object
var person = {
    variableA: "A",
    variableB: "B",
};
object with method
var person = {
    variableA: "A",
    nethodName : function() {
        return "hello " + this.variableA;
    }
};

control flow

iterate array
for(i=0; i<parent.length; i++) {
	console.log(parent[i]);
}
iterate array with for each
for (x of myarray) {
  console.log(x);
}
alternative syntax
myarray.forEach(function(x) {
  console.log(x);
})
iterate properties of object
for (x in obj) {
  text += obj[x];
}

dom

lookup in dom using css selector
var e = document.querySelectorAll("[selector]");
change window title
document.title = 'New Title';
go to url
window.location.href = 'http://www.example.com'
get full url of current page
window.location.href
get domain name only
window.location.hostname returns the domain name of the web host
get path only
window.location.pathname;
get protocol only (http|https)
window.location.protocol
change header text
document.getElementById('myheader').innerText = "change header text";

Threads

invoke with a delay
setTimeout(function() { alert('foo'); }, [millis]);
delay event until user stops typing
function delay(millis, callback) {
  var timer = 0;
  return function() {
    var context = this, args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      callback.apply(context, args);
    }, millis);
  };
}
example usage
document.getElementById('foo').onkeypress(delay(500, function (e) {
	alert('foo');
}));

key events

catch key events
document.getElementById("body").onkeydown = function (e) {
	alert(e.key + ':' + e.code);
};
key codes for events
https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
http://rmhh.co.uk/ascii.html
http://keycode.info/