loading...

5 useful JavaScript tips

loriick profile image Travailleur Lorick Updated on ・2 min read

Copy an array

There are different ways to copy an array

//Define a array
const cities = ['New-York', 'Paris', 'Pointe-à-Pitre']

//With slice
const citiesWithSlice = cities.slice(0)
console.log(citiesWithSlice) //['New-York', 'Paris', 'Pointe-à-Pitre']

//With concat
const citiesWithConcat = [].concat(cities)
console.log(citiesWithConcat) //['New-York', 'Paris', 'Pointe-à-Pitre']


//With spread operator
const citiesWithSpread = [...cities]
console.log(citiesWithSpread) //['New-York', 'Paris', 'Pointe-à-Pitre']

⚠ this type of copy it's a shallow copy and not a deep copy see this link

Get object length

//Define an object
const user = {
lastname: "Doe",
firstName: "John",
age: 99
}


//Transform the object to array and use the length property to it
const userLength = Object.keys(user).length
console.log(userLength) //3

Ternary expression

Instead of a regular if statement like

let isLogged = true;
let message;

if (isLogged){
message = "Welcome"
} else {
message = "Sign in"
}

console.log(message) //Welcome

You can use a simple ternary expression

let isLogged = true;
let message = isLogged ? "Welcome" : "Sign in"

console.log(message) //Welcome

Merge multiple objects

In this case we have different objects but we want now to have only one.
let's see


const defaultUser = {
  name : "",
  firstName: "",
  hasHisLicence: false
}

const user = {
  name: "Doe",
  firstName:"John"
}

//With Object.assign
const data = Object.assign(defaultUser, user);
console.log(data) // {name: "Doe",firstName:"John",hasHisLicence: false}


//With spread operator 
const userData = {...defaultUser, ...user}
console.log(UserData) // {name: "Doe",firstName:"John",hasHisLicence: false}

convert to a boolean

This is a magic trick which convert any type to a boolean it's !! let's see that

const arr = []
console.log(arr.length) //0
console.log(!!arr.length) // false

Discussion

pic
Editor guide