JS tricks to use in your next project.

JS tricks to use in your next project.
  1. Converting string to number
the_string = "123";
console.log(+the_string);
// 123

the_string = "hello";
console.log(+the_string);
// NaN
  1. Convert a number to a string
var converted_number = 5 + "";
console.log(converted_number);
// 5
console.log(typeof converted_number);
// string

  1. Extract Unique Values
var entries = [1, 2, 2, 3, 4, 5, 6, 6, 7, 7, 8, 4, 2, 1]
var unique_entries = […new Set(entries)];
console.log(unique_entries);
// [1, 2, 3, 4, 5, 6, 7, 8]

4 Flatten a multidimensional array

var entries = [1, [2, 5], [6, 7], 9];
var flat_entries = [].concat(…entries);
// [1, 2, 5, 6, 7, 9]
  1. Replace All
var example = "potato potato";
console.log(example.replace(/pot/, "tom"));
// "tomato potato"
console.log(example.replace(/pot/g, "tom"));
// "tomato tomato"
  1. Short Circuit Conditionals
if (available) {
addToCart();
}
We can easily rewrite the syntax above with a logical && operator.
available && addToCart()

  1. Use the length to resize and empty an array
Resize the array
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]

empty the array
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);
// []

Leave a Reply

Your email address will not be published. Required fields are marked *