Back to blog
Jun 2018·1 min readAI-translated

Javascript Snippets

#javascript#snippets

Here I collect a few JavaScript snippets. A list that will surely grow over time :)

A random element from an array? Nothing easier!

var items = [123, 'John', 11111, 'Doe', 'foo', 2924, 'bar', 'foobar', 55, 'baz'];
var randomItem = items[Math.floor(Math.random() * items.length)];

A random number between a minimum and a maximum? Here you go!

var x = Math.floor(Math.random() * (max - min + 1)) + min;

A "Stack Overflow find": JavaScript shorthand if/else. I didn't know that was possible. Very powerful language... :D

var y = (x == 2 ? "yes" : "no");

Source: stackoverflow.com/questions/11069278

Optional parameters

if (typeof optionalArg === 'undefined') {
  optionalArg = 'default';
}

Promise

new Promise(function(resolve, reject) {
  alert("Action 1");
  resolve();
}).then(function() {
  alert("Action 1 finished");
});
NewerScrollblurOlderBash Snippets