JavaScript Simple Tricks

JavaScript Simple Tricks

Part #1

In this post I will share some JavaScript tips and tricks that have helped me to write some nice code and resolve problems in a more clean manner.

Convert string to number with the + operand

You can use the + operand before a string that contains numeric character to parse them to number:

let string_int = +"10" //will be parse to 10 
let string_float = +"10.50" //will be parsed to 10.50
let string_error = +"number" //will give NaN

Simple number round

Using the + string number conversion, now we can make some cleaner number rounding by using the toFixed() function.

toFixed() is a number function which formats a number using the fixed point notation. It receives as a parameter the number of decimals we want and returns the number formatted and rounded as a string.

let num = 10.85989

//with the + operand we parse the string return value back to number
let rounded_number = +num.toFixed(2)

console.log(rounded_number) //10.86

Simple number operation round

Using the same logic as before we can perform number operations that require some number rounding.

let result = +(10.86 + 10.1189).toFixed(2) //20.98

//rounding using Math.round

let result_b = Math.round((10.86 + 10.1189)*100) /100 //20.98

Truncate number without rounding them

Some times we want a number like 10.99121 to just have two decimal places after the point and without being rounded, we can use the Math.trunc() function with some adjustments to make it happen:

let num = 10.99121
let wanted_decimals = 2
let decimal_factor = 10 ** wanted_decimals // 10 ** 2 = 100

//num * decimal_factor (10.99121 * 100) = 1099.121
//Math.trucn() will remove all decimals from 1099.121 so it will return 1099
// num / decimal_factor (1099 / 100) = 10.99 

let trunc_number = Math.trunc(num * decimal_factor) / decimal_factor // returns 10.99

Replace all coincidences on a string

There is a string function called replaceAll(regx,str) which can replace all of the coincidences on a string, but if your node or browser version does not supports it, you can use a regular expression with the g flag in the replace function:

let str = "Do you prefer apple or android!!!  Yes"

let replaced_str = str.replace(/!/g,"?") 

console.log(replaced_str) // Do you prefer apple or android??? Yes

Quick map definition

We can define our map with a set of key values quicker by declaring it like this:

let value_map = new Map([[1,"pizza"],[2,"ice-cream"],[3,"some weird tea"]])

Iterating over a Map or Set

We can simply iterate over a map or a set with for..of

let value_map = new Map([[1,"pizza"],[2,"ice-cream"],[3,"some weird tea"]])

//we can deconstruct the properties of each iterable map object
for(let [key,value] of value_map){
console.log(`The key ${key} holds the value ${value}`)
}

Iterating over a set

let unique_values=new Set(["pizza","ice-cream","cola"])

for(let item of unique_values){
console.log(item)
}

Deconstruct nested properties

We can deconstruct the nested properties of an object that is inside another object:

let computer = {
brand: "lenovo",
model: "thinkpad",
components : {
processor: "yes",
ram: "16",
gpu: "expensive nvidia card"
}
}

let {components: {processor}} = computer // yes

We can also deconstruct more deeply nested properties:

let computer = {
brand: "lenovo",
model: "thinkpad",
components : {
processor: "yes",
ram: "16",
gpu: "expensive nvidia card",
battery: {
  size: "big"
}
}
}

let {components: {processor, battery: {size}}} = computer //yes, big

But as you can see the code starts to become messy, so if you are going to use this technique to deconstruct a nested property, it is better to deconstruct one nested property at a time and avoid deconstructing a too deeply nested one.

This deconstruct method also works with arrays:

let nested_ar = [1,[2,3]]

let [first,[second]] = nested_ar

console.log(first) // 1
console.log(second) // 2

Capitalize first letter of a string

Since ES6 we can use the string with some array like properties, one of those is to access a character whit its index, so capitalizing only the first letter becomes more easier:

let name = "england"
let capitalizedName = name.replace(name[0],name[0].toUpperCase())

console.log(capitalizedName ) //England