-2

I heard somewhere that new keyword is not mandatory everywhere. Is that true?

app.post('/tasks', (req, res) => {
    const task = new Task(req.body)

here if i dnt write new, its still working. I am confuse about this keyword

validate(value) {
            if(value.toLowerCase().includes('password')) {
                throw new Error(`Password can't be "password"`)
            }
        }
const add = (a, b) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(a + b)
        }, 2000)
    })
}

Again here if i dnt give new ,its not working. Can someone elaborate the difference?

  • 1
    you can check here: https://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript – Stefan F. Feb 13 '20 at 07:48
  • 3
    Does this answer your question? [What is the 'new' keyword in JavaScript?](https://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript) – acagastya Feb 13 '20 at 07:48
  • nice duplicate :-( – Pierre Feb 13 '20 at 07:49
  • It's only possible to omit `new` if the function supports it. You can create such a function yourself as well: https://jsfiddle.net/50w6Lvru/ – TiiJ7 Feb 13 '20 at 07:58
  • Usually you use `new` when you're calling a constructor function or a class in order to create an instance of the constructor/class. Some (especially) host objects can be called without `new` operator, when they might return a different result, ex. `Date]()` returns a string when called without `new`. Some libraries have contructors, which detect they were called by `new`, and if it wasn't used, they call themselves with `new` operator, forcing a new instance to be created. – Teemu Feb 13 '20 at 08:00
  • Things like this can get a bit confusing. The reason is that a function might be a plain vanilla function that maintains state using closures, a constructor function, and even a factory pattern. One hint that it's a class might be to look at is prototype. – Keith Feb 13 '20 at 08:02

1 Answers1

2

The new keyword has a number of effects when you use it.

Typically, a regular function is designed to be used without it.

Typically, a constructor function is designed to be used only with it.

Sometimes, a function may be designed in such a way that it can work with and without it.

For example:

function Duck() {
    if (this instanceof Duck) {
        return this;
    }
    return new Duck();
}

const swedish_blue = Duck();
const welsh_harlequin = new Duck();

console.log(swedish_blue instanceof Duck);
console.log(welsh_harlequin instanceof Duck);

If it is designed to work with or without new then it might, as in the example above, simply apply new itself. It could also have different behaviour.

const date_string = Date();
const date_obj = new Date();
console.log(typeof date_string, date_string instanceof Date);
console.log(typeof date_obj, date_obj instanceof Date);
Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205