Skip to content

Instantly share code, notes, and snippets.

@mikoloism
Last active April 2, 2023 13:39
Show Gist options
  • Save mikoloism/49137decdf49e2e2cb668fd17a9f4157 to your computer and use it in GitHub Desktop.
Save mikoloism/49137decdf49e2e2cb668fd17a9f4157 to your computer and use it in GitHub Desktop.
HOW-WRITE-CLEAN-CODE?

Destructure Javascript Object

Object for Destructuring

// common-base
const object = {
  name: {
  first: 'john',
  last: 'doe',
},
  birthday: {
    day: 3,
    month: {
      name: 'september',
      short: 'sep',
      number: 9,
    },
    year: {
      short: 53,
      full: 1953,
    }
  },
};

Practises

Common Code

const firstName   = object.name.first;
const lastName    = object.name.last;
const day         = object.birthday.day;
const shortMonth  = object.birthday.month.short;
const numberMonth = object.birthday.month.number;
const fullYear    = object.birthday.year.full;

Full Destruct Code

const {
  name: { first: firstName, last: lastName },
  birthday: {
    day,
    month: { short: shortMonth, number: numberMonth },
    year: { full: fullYear }
  }
} = object;

Best Destruct

const { name, birthday } = object;
const { first: firstName, last: lastName } = name;
const { day, month, year: { full: fullYear }  } = birthday;
const { short: shortMonth, number: numberMonth } = month;

How Give Object as Argument? (Javascript)

Object for Destructuring

// Object from anywhere we want pass to functions
const args = {
  firstName: "john",
  lastName : "doe",
  username : "jDoe",
  email    : "[email protected]",
  password : 0000
};

practises

Bad Code

/**
  * Parameters: 
  *   firstName,
  *   lastName,
  *   userName,
  *   email,
  *   password (default value is 1234)
  */
const userAgent = (firstName, lastName, username, email, password = 1234) => {
  return `
    user: ${firstName} ${lastName}
    Username: @${username}
    by ${email}
    PASSWORD: ${password}`;
};

Best Code

const userAgent = ({
  firstName,
  lastName,
  username,
  email: mail, // give `email` object as `mail` variable in function
  password = 1234 // default value is 1234
}) => {
  return `
    user: ${firstName} ${lastName}
    Username: @${username}
    by ${mail}
    PASSWORD: ${password}`;
};

Replace two variable

Variables

let var1 = 'Hello',
    var2 = 'World';
console.log(var1, var2); // Hello World

Practises

Common Code

let temp = var1;
var1 = var2;
var2 = temp;
console.log(var1, var2); // World Hello

Clean Code

[var1, var2] = [var2, var1];
console.log(var1, var2); // World Hello
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment