DEV Community

Travailleur Lorick
Travailleur Lorick

Posted on • Updated on

5 useful JavaScript tips

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']

Enter fullscreen mode Exit fullscreen mode

⚠ 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

You can use a simple ternary expression

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

console.log(message) //Welcome
Enter fullscreen mode Exit fullscreen mode

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}

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)