DEV Community

Discussion on: Object References (Why ['this']!==['this'])

Collapse
 
tanth1993 profile image
tanth1993

nice article.
In function deepCloner, could we use switch...case instead of if/else?

Collapse
 
fitzgeraldkd profile image
Kenny Fitzgerald (he/him)

Thanks @tanth1993 ! It is definitely possible to use a switch! It may not be the best application since there's not just one expression we're evaluating, but it is an option we can explore. Here's what the function could look like using a switch statement (note that we don't need to use break in each case because the function stops when something is returned):

function deepClonerSwitch(target) {
  switch (true) {
    case (Array.isArray(target)):
      return target.map(deepClonerSwitch);
    case (target instanceof Date):
      return new Date(target);
    case (typeof target === 'object' && target !== null):
      const newObj = {};
      for (const key in target) {
        newObj[key] = deepClonerSwitch(target[key])
      }
      return newObj;
    default:
      return target;
  }
}
Enter fullscreen mode Exit fullscreen mode

Hope this helps!

Collapse
 
tanth1993 profile image
tanth1993

Wow. Nice! thank you for sharing this.