Dorokhov.codes

16. JavaScript Tricks

Iterating operations

Iterating over an any array using for:

var someArray = ['one', 'two', 'three', 'four', 'five'];

for (var i = 0; i < someArray.length; i++) {
    console.log("Look at this: " + someArray[i] + ".");
}

Iterating over all the symbols of a string using for:

var someString = "Hello, world!";

for (var i = 0; i < someString.length; i++) {
    console.log("Look at this: " + someString[i] + ".");
}

Random values

Random element of an array:

var someArray = ['one', 'two', 'three', 'four', 'five'];

var randomElement = someArray[Math.floor(Math.random() * someArray.length)];

Random symbol of a string:

var someString = "Hello, world!";

var randomSymbol = someString[Math.floor(Math.random() * someString.length)];

Random number from -X to +X:

// Math.random() * X - X/2;
// Example:
Math.random() * 80 - 40 // -40..+40
/**
 * Exmplanation:
 * Math.random() * 80: this gives us number from 0 to 80.
 * So if we subtract a half (-40) we will get a range from -40 to +40.
 */

Destructuring

Array destructuring when working with names:

let [firstName, surname] = "John Smith".split(' ');

Passing parameters to a function using destructuring:

doSomething({
    firstName: "Andrew",
    secondName: "Dorokhov",
    country: "Ukraine",
});

function doSomething({firstName, secondName, country}) {
    // ...
}