1. What does new
do?
- When you use
new
, Javascript: - Creates a new empty object:
{}
- Sets the new object's prototype to the constructor's prototype (
obj.__proto__ = Constructor.prototype
) - Runs the Constructor function with
this
bound to the new object - Returns the new object (unless the constructor explicitly returns another object)
2. Using new
with a Constructor Function
function Person(name) { this.name = name; } const user = new Person("Ankit"); console.log(user.name); // "Ankit"
If you call person("Ankit")
without new
:
- It won't create a new object.
-
this
will refer to the global object (orundefined
in strict mode) -
name
will be set on the wrong thing → Bug! That's why new is important.
3. Using new with a Class
class Car { constructor(brand) { this.brand = brand; } } const c1 = new Car("Tesla"); console.log(c1.brand); // Tesla
Your must use new with classes, or Js will throw an error.
4. What if the Constructor Returns Something?
- If it returns an object, that object is returned instead of the new one.
- If it returns a primitive (string, number, etc.), it's ignore, and the new object is returned.
function Test() { this.value = 10; return { msg: "I override!" }; } const t = new Test(); console.log(t); // { msg: "I override!" }
5. Built-in Objects that use new
Many built-ins in JS can be created with new:
let now = new Date(); let regex = new RegExp("abc"); let obj = new Object(); let arr = new Array(3); // [empty × 3]
But some are fine without new:
let str = String(123); // "123" let num = Number("5"); // 5
6. When NOT to use new:
- Don't use new with normal functions that are not constructors.
function greet() { console.log("Hello!"); } new greet(); // Works but makes no sense → {}
Top comments (0)