logo

Object Property Value Shorthand

April 2, 2021

  • The "old" way of doing:
const dog = "Dino";
const cat = "Bob";
const pets = {
  dog: dog,
  cat: cat,
};
  • Using the new shorthand property syntax:
const dog = "Dino";
const cat = "Bob";
const pets = {
  dog,
  cat,
};

console.log(pets); // {dog: "Dino", cat: "Bob"}

Another example:

const getInfo = arr => {
  const max = Math.max(...arr);
  const min = Math.min(...arr);
  const sum = arr.reduce((total, currentVal) => {
    return total + currentVal;
  }, 0);
  const avg = sum / arr.length;
  return { min, max, sum, avg };
};

const nums = [1, 2.2, 7, 5.0];
console.log(getInfo(nums)); // {min: 1, max: 7, sum: 15.2, avg: 3.8}

function rand(arr) {
  const idx = Math.floor(Math.random() * arr.length);
  return arr[idx];
}

function getEmoji() {
  const emojiArray = ["😀", "😁", "😂", "🤣", "😃", "😄", "😅", "😆", "😉"];
  const moodsArray = ["silly", "happy", "calm", "cheerful"];
  const emoji = rand(emojiArray);
  const mood = rand(moodsArray);
  return {
    emoji,
    mood,
  };
}

console.log(getEmoji()); // {emoji: "😁", mood: "calm"}
console.log(getEmoji()); //  {emoji: "😂", mood: "calm"}
console.log(getEmoji()); //  {emoji: "😅", mood: "happy"}
console.log(getEmoji()); //  {emoji: "😅", mood: "cheerful"}