JavaScript

[ JS ] Destructuring

Design-loving front-end engineer 2022. 7. 5. 14:23

πŸ”΄  Object Destructuring

βšͺ  큰 μ˜€λΈŒμ νŠΈμ—μ„œ νŠΉμ • λ³€μˆ˜λ‚˜ κ·Έ μ•ˆμ— μ†ν•œ μž‘μ€ μ˜€λΈŒμ νŠΈμ— μ ‘κ·Όν•  수 μžˆλ„λ‘ ν•˜λŠ” 기법

 
const settings = {
  notifications: {
    follow: true,
    alerts: true,
    unfollow: false
  },
  color: {
    theme: "dark"
  }
};
// const λ³€μˆ˜ 생성
const {
  notifications: { follow },
  color
} = settings;

console.log(follow);  // true
console.log(color);  // {theme: "dark"}
 
const settings = {
  notifications: {
    alerts: true,
    unfollow: false
  },
  color: {
    theme: "dark"
  }
};
// follow 값이 μ—†λ‹€λ©΄ false둜 μ„€μ •ν•˜μ—¬ μƒμ„±ν•˜κ³ , notifications μžμ²΄κ°€ μ—†λ‹€λ©΄ 빈 object 생성
const { notifications: { follow = false } = {} } = settings;

console.log(follow);  // false
console.log(color);  // {theme: "dark"}

 

🟠  Array Destructuring

 
const days = ["Mon", "Tue", "Wed"];

const [mon, tue, wed, thu = "Thu"] = days;

console.log(mon, tue, wed, thu);  // Mon Tue Wed Thu

 

🟑  Destructuring Renaming

 
// [ Rename with const ]
const setting = {
  color: {
    chosen_color: "dark"
  }
};
// chosen_color 속성을 chosenColor μ΄λ¦„μ˜ const λ³€μˆ˜λ‘œ μ €μž₯
const {
  color: { chosen_color: chosenColor = "light" }
} = settings;

console.log(chosenColor);  // dark
 
// [ Rename with let ]
const setting = {
  color: {
    chosen_color: "dark"
  }
};

let chosenColor = "blue";

console.log(chosenColor);  // blue

({
  color: { chosen_color: chosenColor = "light" }
} = settings);

console.log(chosenColor);  // dark

 

🟒  Function Destructuring

 
function saveSettings({ notifications, color: { theme } }) {
  console.log(theme);
}

saveSettings({
  notifications: {
    follow: true,
    alert: true,
    mkt: false
  },
  color: {
    theme: "blue"
  }
});

 

πŸ”΅  Value Shorthands

βšͺ  μ€‘λ³΅λ˜λŠ” λ³€μˆ˜λͺ…을 ν•˜λ‚˜λ‘œ μ μ–΄μ€ŒμœΌλ‘œμ¨ μ½”λ“œλ₯Ό κ°„κ²°ν•˜κ²Œ ν•˜λŠ” 방법이닀.

 
const follow = checkFollow();
const alert = checkAlert();

const settings = {
  notifications: {
    follow,  // === follow: follow
    alert    // === alert: alert
  }
};

 

🟣  Swapping and Skipping

βšͺ  Swapping

 
let mon = "Sat";
let sat = "Mon";

[mon, sat] = [sat, mon];

βšͺ  Skipping  λ°°μ—΄μ˜ 일뢀 μš”μ†Œλ₯Ό , λ₯Ό μ‚¬μš©ν•˜μ—¬ μ œμ™Έν•˜λŠ” 방법

 
const days = ["mon", "tue", "wed", "thu", "fri"];

const [, , , thu, fri] = days;

console.log(thu, fri);  // thu fri