0

I am a beginner and getting started with JavaScript, so recently I came across this code and I am really confused as the keyword 'new' in JavaScript is used alongside a constructor function to create a new empty object. Error("Error") isn't a function, still I am successfully able to run this lines of code

let a=new Error("Error")
console.log(a)

I tried researching from my end and look everywhere where I can, but I cant seem to find a satisfactory answer to resolve my doubt

Phil
  • 157,677
  • 23
  • 242
  • 245
  • "*Error("Error") isn't a function*" it is? Why is it any different to `new Person("Fred")`? – VLAZ Nov 03 '22 at 06:51
  • 2
    Well, sure, `Error("something")` _itself_ isn’t a function. But I’m sure you know what the [`new` keyword](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/new) is and how it’s used to construct objects from constructors, right? [`Error`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Error/Error) itself _is_ a function. – Sebastian Simon Nov 03 '22 at 06:54
  • `the keyword 'new' in JavaScript is used alongside a constructor function to create a new empty object` ... no it isn't, `The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.` – Jaromanda X Nov 03 '22 at 06:54
  • @JaromandaX so basically what you are saying, the keyword 'new' creates an instance of an object rather than creating an empty object? Well, I am not sure if I understand the difference between this two, can you explain more? Thanks – Swayam Pattanaik Nov 03 '22 at 06:58
  • 1
    `new Person()` creates an instance of `Person`. An empty object would be `{}` which is not necessarily what `Person` is. – VLAZ Nov 03 '22 at 07:00
  • `new Object` creates an **empty** object, `new Error` creates a *new* Error object, with columnNumber, fileName, lineNumber, message and stack properties - which is 5 properties away from being *empty* (actually `new Object` isn't empty either, but that's another story) – Jaromanda X Nov 03 '22 at 07:02
  • Thanks @VLAZ ps: was my 1st question and very much satisfied with the answers – Swayam Pattanaik Nov 03 '22 at 07:03
  • @JaromandaX yes yes, got you now – Swayam Pattanaik Nov 03 '22 at 07:04
  • By the way, if you want a truly *empty* Object, ... `Object.create(null)` – Jaromanda X Nov 03 '22 at 07:05

0 Answers0