Javascript tips

Managing objects

Destructuring is a huge part of ES6 and something you're probably going to be using often. It allows us to extract data from objects, and assigning the extracted data into variables:

const rectangle = { h: 100, w: 200 };
const { h, w } = rectangle;

We can rename the variables if we want to:

const { h: height, w: width} = rectangle;
console.log(height); // 100

Another handy thing we could do is to destructure the returned object by a function and pick and choose what values we want to use:

function getPerson() {
  return {
    firstName: 'Max',
    lastName: 'Best',
    age: 42

const { age } = getPerson();
console.log(age); // 42

So, with destructuring, we can return multiple values from a function by returning an object and choosing the pieces we want to be returned. Removing a property in an immutable way requires a little trick provided by spread’s counterpart, the rest operator, which is written with three dots (...) like spread. However, in this case, we spread the remaining properties into a new object.

const { age:_ , ...person } = getPerson();

console.log(person); // {firstName: "Max", lastName: "Best"}

Now the person object holds all properties from the original person object except age.

Converting to numbers

JavaScript is a loosely typed language, meaning we don't have to explicitly specify types of variables. JavaScript also freely type-converts values into a type depending on the context of their use. Converting values to numbers, especially strings to numbers, is a common requirement and many methods can be used.


Another useful method for determining if the input is an Array or not.

let emojis = ['🔥', '⏲️', '🏆', '🍉'];

let obj = {};