Useful JavaScript tips

Here you will find some useful tricks that might help you and reduce your JS code in future.

Replace All

Function string.replace() replaces only the first occurrence however with a little bit of regex you could replace all the occurrences by adding /g at the end.

var test = "tomato potato";
console.log(test.replace(/tom/, "pot"));
// "potato potato"
console.log(test.replace(/tom/g, "pot"));
// "potato potato"

Extract Unique Values

Create a new array with just unique values by using the Spread operator and the Set object.

var exampleArray = [1, 2, 2, 3, 4, 5, 6, 6, 7, 7, 8, 4, 2, 1]
var unique_only = [...new Set(exampleArray)];
console.log(unique_only);
// [1, 2, 3, 4, 5, 6, 7, 8]

Convert a number to a string

Use the concatenation operator with an empty set of quotation marks.

var change_to_string = 5 + "";
console.log(change_to_string);
// 5
console.log(typeof change_to_string);
// string

Convert string to a number

Add + or * operator.

Note: this only works with ‘string numbers’.

var with_plus = "123";
console.log(+with_plus);
// 123
var with_plus = "hello";
console.log(+with_plus);
// NaN
var with_astrics = "123"
var new_number =  with_astrics * 1;
console.log(new_number);

Shuffle elements in an array.

var number_list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(number_list.sort(function() {
    return Math.random() - 0.5
}));
// [4, 8, 2, 9, 1, 3, 6, 5, 7]

Flatten multidimensional array

var mult_array = [1, [2, 5], [6, 7], 9];
var one_array = [].concat(...mult_array);
// [1, 2, 5, 6, 7, 9]

Short Circuit Conditionals

Usual way:

if (available) {
    addToCart();
}

A shorter and better way:

available && addToCart()

Dynamic Property Names

In most cases, you might have seen and thought that you need to declare an object before assigning a dynamic property, this way you don’t have to.

const dynamic = 'flavour';
var item = {
    name: 'Coke',
    [dynamic]: 'Cherry'
}
console.log(item);
// { name: "Coke", flavour: "Cherry" }

Resize or empty an array with length.

How to resize:

var entries = [1, 2, 3, 4, 5, 6, 7];  
console.log(entries.length);
// 7  
entries.length = 4;  
console.log(entries.length);
// 4  
console.log(entries);
// [1, 2, 3, 4]

How to empty:

var entries = [1, 2, 3, 4, 5, 6, 7];
console.log(entries.length);
// 7  
entries.length = 0;   
console.log(entries.length);
// 0
console.log(entries);
// []

Take the values from an array of objects

var people = [
    { name: ‘John’, age: 22 },
    { name: ‘Peter’, age: 23 },
    { name: ‘Mark’, age: 24 },
    { name: ‘Maria’, age: 22 },
    { name: ‘Monica’, age: 21 },
    { name: ‘Martha’, age: 19 },
]
var people = Array.from(people, ({name}) => name);
console.log(people); // returns [“John”, “Peter”, “Mark”, “Maria”, “Monica”, “Martha”]

Convert array to an object.

var fruits = [“banana”, “apple”, “orange”, “watermelon”];
var fruitsObj = { …fruits };
console.log(fruitsObj); // returns {0: “banana”, 1: “apple”, 2: “orange”, 3: “watermelon”, 4: “apple”, 5: “orange”, 6: “grape”, 7: “apple”}

Get array full with data.

var ten_element_array = new Array(10).fill(“1”);
console.log(ten_element_array); // returns [“1”, “1”, “1”, “1”, “1”, “1”, “1”, “1”, “1”, “1”, “1”]

Merge arrays

var fruits = [“apple”, “banana”, “orange”];
var meat = [“poultry”, “beef”, “fish”];
var vegetables = [“potato”, “tomato”, “cucumber”];
var food = […fruits, …meat, …vegetables];
console.log(food); // [“apple”, “banana”, “orange”, “poultry”, “beef”, “fish”, “potato”, “tomato”, “cucumber”]

Get intersection of two arrays

var arrayOne = [0, 2, 4, 6, 8, 8];
var arrayTwo = [1, 2, 3, 4, 5, 6];
var duplicatedValues = […new Set(arrayOne)].filter(item => arrayTwo.includes(item));
console.log(duplicatedValues); // returns [2, 4, 6]

Remove falsy values from an array

var a = [1, 2, "b", 0, {}, "", NaN, 3, undefined, null, 5];
var b = a.filter(Boolean);  // [1, 2, "b", {}, 3, 5];

Get random value from the array

var colors = ['blue', 'white', 'green', 'navy', 'pink', 'purple', 'orange', 'yellow', 'black', 'brown'];
var randomColor = colors[(Math.floor(Math.random() * (colors.length)))]
console.log(randomColor);

We hope you found something that you didn’t know and that you will use it, next time you start to write your code.