0

I rarely ever use the constructed object form, e.g., (Number, String, Boolean, etc.) to create an object of the relevant type when a literal does the job. On the rare occasions when I do create, say a String object using const str = new String("something");, I use the new keyword. By doing this, an object is created that becomes the this context and an instance is created such that:

const str1 = new String("hi");
const str2 = new String("hi");
console.log(str1 === str2); // false

On the contrary, if the constructed object form is used without the new keyword,

const str1 = String("hi");
const str2 = String("hi");
console.log(str1 === str2); // true

What are the implications of this? When would you use one form over the other? Is the second way just bad practice or is there more to it than that?

univuniv1
  • 63
  • 5
  • 4
    I have never encountered a situation where `new ` has ever been useful, and due to object equality issues, probably best to avoid it altogether – CertainPerformance Jul 04 '21 at 03:15
  • There's a lot of [explanations](https://stackoverflow.com/questions/383402/is-javascripts-new-keyword-considered-harmful) for why with user-defined types you **might** want to avoid new, due to a few pitfalls. But for primitive types, it's mostly harmless (except, for obviously, object equality). – Alex Huszagh Jul 04 '21 at 03:17
  • `String('string')`, without the `new`, is a redundancy. It's not any different from `'string'`. `String(x)` is really only useful when `x` isn't a string. And as someone else has already said, I too have never found `new String('string')` useful for anything. It obviously does _something_ by making an instance wrapper around the string, but why you'd ever want to do that I've yet to discover. – kshetline Jul 04 '21 at 03:30

0 Answers0