Skip to content

Javascript snippets

Set variable if it's undefined

var x = (x === undefined) ? your_default_value : x;

Concatenate two arrays

const arr1 = ["Cecilie", "Lone"];
const arr2 = ["Emil", "Tobias", "Linus"];
const children = arr1.concat(arr2);

To join more arrays you can use:

const arr1 = ["Cecilie", "Lone"];
const arr2 = ["Emil", "Tobias", "Linus"];
const arr3 = ["Robin"];
const children = arr1.concat(arr2,arr3);

Check if a variable is not undefined

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
}

Select a substring

'long string'.substring(startIndex, endIndex)

Round a number

Math.round(2.5)

Remove focus from element

document.activeElement.blur();