# New in Javascript

In this article, we'll explore the functionality and behaviour of the `new` keyword in JavaScript — what it does, the benefits it provides, the steps it takes during execution, and what happens behind the scenes.

## New

The `new` keyword in JavaScript is **an operator used to create an instance of a user-defined object type or a built-in object type that has a constructor function**. When a function is called with `new`, it executes a specific sequence: it **creates a blank, plain JavaScript object**, **links its internal prototype** to the constructor's prototype property, **binds the** `this` **context** to this new object, and **executes the constructor function** to populate it.

If the constructor function returns a **non-primitive value** (like an object or array), that returned value becomes the result of the `new` expression; otherwise, the **newly created object** is returned. For example, `const car1 = new Car("Eagle", "Talon TSi", 1993);` creates a `car1` instance with properties `make`, `model`, and `year` defined within the `Car` constructor.

### **Key Behaviors and Syntax**

*   **Syntax**: The operator follows the pattern `new constructor(arg1, arg2, ...)` or `new constructor()` with no arguments.
    
*   **Classes**: In modern ES6+, **classes can only be instantiated** with the `new` operator; calling a class without it throws a `TypeError`.
    
*   **Built-in Types**: Many built-in constructors like `Array()`, `Date()`, and `Function()` behave as constructors when used with `new`, though some like `Symbol()` and `BigInt()` **require** `new` while others like `Proxy` and `Map` **cannot** be called without it.
    
*   [`new.target`](http://new.target): Inside a function, the special property [`new.target`](http://new.target) is **undefined** when called as a regular function but **equals the function** when invoked with `new`, allowing the code to distinguish between construction and regular invocation.
    

### **The** `new Function` **Syntax**

Distinct from the `new` operator for objects, the `new Function` syntax allows creating a function **dynamically from a string** at runtime. Unlike standard functions that capture their lexical environment (closure), functions created with `new Function` have their `[[Environment]]` set to the **global scope**, meaning they **cannot access outer variables** and can only interact with global ones. This is typically used in specific cases like receiving code from a server or dynamically compiling functions from templates.

The term new function in JavaScript refers to two distinct concepts: using the new keyword with a constructor function to create a new object, or using the new Function() constructor to dynamically create a function from a string.

1.  Constructor Functions (new MyFunction()) When you use the new keyword followed by a function name (e.g., new User()), the function acts as a constructor to instantiate a new object.
    

Mechanism: It creates a blank object, sets its prototype to the function's prototype, executes the function with this bound to the new object, and returns the object (unless a non-primitive is explicitly returned). Usage: This is the standard pattern for creating objects with specific properties and methods before ES6 classes were introduced.

```javascript
function Car(make) { 
    this.make = make; 
} 
const myCar = new Car("Eagle");
```

2.  The new Function() Constructor The syntax new Function(...) is a special built-in constructor used to dynamically create a function from a string argument.
    

Scope: Functions created this way have a global lexical environment and cannot access outer variables (closures) from where they are defined. Syntax: Arguments are passed as individual strings, followed by the function body as a string. // Creates a function that sums two numbers

```javascript
let sum = new Function('a', 'b', 'return a + b'); console.log(sum(1, 2)); // 3
```

Use Cases: Primarily used for dynamic code execution (e.g., receiving code from a server) or compiling templates, though it is less common due to security risks and lack of closure support.

### **Key Differences**

<table style="min-width: 75px;"><colgroup><col style="min-width: 25px;"><col style="min-width: 25px;"><col style="min-width: 25px;"></colgroup><tbody><tr><td colspan="1" rowspan="1"><p>Feature</p></td><td colspan="1" rowspan="1"><p><code>new MyFunction()</code></p></td><td colspan="1" rowspan="1"><p><code>new Function()</code></p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>Purpose</strong></p></td><td colspan="1" rowspan="1"><p>Creates a new <strong>object instance</strong>.</p></td><td colspan="1" rowspan="1"><p>Creates a new <strong>function object</strong>.</p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>Arguments</strong></p></td><td colspan="1" rowspan="1"><p>Passed to the constructor logic.</p></td><td colspan="1" rowspan="1"><p>Passed as <strong>strings</strong> defining parameters.</p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>Scope</strong></p></td><td colspan="1" rowspan="1"><p>Can access <strong>outer variables</strong> (closures).</p></td><td colspan="1" rowspan="1"><p>Restricted to <strong>global scope</strong> only.</p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>Code Source</strong></p></td><td colspan="1" rowspan="1"><p>Defined in the script.</p></td><td colspan="1" rowspan="1"><p>Defined from a <strong>string</strong> at runtime.</p></td></tr></tbody></table>

**Note**: If you see `new function() {}`, it is an **anonymous constructor function** immediately instantiated with `new`, often used to create a single object instance with a private scope for variables.

## Object Creation in javascript

JavaScript offers **four primary methods** to create objects, each serving different architectural needs from simple data structures to complex inheritance patterns. The most direct approach uses **object literals** (e.g., `const obj = { key: value }`), which create plain objects with properties defined immediately. For reusable blueprints, developers use **constructor functions** with the `new` keyword, which initialize multiple instances with shared behavior, or **ES6 classes** that provide a structured syntax for defining constructors and methods.

**Object.create()** provides fine-grained control by creating a new object with a specified prototype, allowing for **classical inheritance** without invoking a constructor function. This method can also accept a second argument to define property descriptors, controlling attributes like **writability, enumerability, and configurability** that are not accessible in standard object initializers. Additionally, **Object.create(null)** creates an object without a prototype, useful for creating map-like structures that avoid inherited properties.

<table style="min-width: 75px;"><colgroup><col style="min-width: 25px;"><col style="min-width: 25px;"><col style="min-width: 25px;"></colgroup><tbody><tr><td colspan="1" rowspan="1"><p>Method</p></td><td colspan="1" rowspan="1"><p>Best Use Case</p></td><td colspan="1" rowspan="1"><p>Key Characteristic</p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>Object Literals</strong></p></td><td colspan="1" rowspan="1"><p>Single object creation</p></td><td colspan="1" rowspan="1"><p>Concise syntax; creates plain objects.</p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>Constructor Functions</strong></p></td><td colspan="1" rowspan="1"><p>Multiple instances</p></td><td colspan="1" rowspan="1"><p>Uses <code>new</code>; allows shared methods via prototype.</p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>ES6 Classes</strong></p></td><td colspan="1" rowspan="1"><p>Structured OOP</p></td><td colspan="1" rowspan="1"><p>Syntactic sugar over constructors; supports <code>extends</code>.</p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>Object.create()</strong></p></td><td colspan="1" rowspan="1"><p>Prototype manipulation</p></td><td colspan="1" rowspan="1"><p>Direct prototype assignment; fine-tuned property control.</p></td></tr></tbody></table>

When using **Object.create()**, the second parameter maps keys to property descriptors, enabling the creation of **accessor properties** (getters/setters) and data properties with specific attributes. While **Object.create()** mimics the `new` operator's behavior, it cannot execute initialization code within a constructor, making it ideal for delegation patterns where constructor overhead is undesirable. Modern code generally prefers **class syntax** for its readability, though **Object.create()** remains valuable for specific inheritance scenarios.

## Prototype linking

When a constructor function is called with the `new` keyword, JavaScript **creates a new empty object** and **links its internal** `[[Prototype]]` directly to the constructor function's `prototype` property. This linkage means the new instance automatically gains access to any properties or methods defined on that prototype object, forming the basis of **prototypal inheritance**.

The process works as follows:

*   **Creation**: A new object is instantiated and its internal `[[Prototype]]` slot is set to point to `ConstructorName.prototype`.
    
*   **Initialization**: The constructor function executes with `this` bound to the new object, allowing it to assign instance-specific properties.
    
*   **Inheritance**: If the new object lacks a specific property, the JavaScript engine traverses the **prototype chain** up to the prototype object and eventually to `Object.prototype` to find it.
    

For example, when `new Person("Ifeoma")` is executed, the resulting object `ifeoma` has its `[[Prototype]]` linked to `Person.prototype`, allowing it to access methods like `greet()` defined there, while its own `[[Prototype]]` (if accessed via `Object.getPrototypeOf(ifeoma)`) equals `Person.prototype`. If `Object.create()` is used instead, the created object's internal prototype is set to the object passed as the first parameter, bypassing the constructor's `prototype` property entirely.

## Instance creation with new keyword

In JavaScript, an **instance** is the object created by calling a constructor function with the `new` **operator**, which acts as a **blueprint** for defining properties and methods. When you invoke a constructor (e.g., `new Person()`), JavaScript **creates a new empty object**, sets its prototype to the constructor's `prototype`, and **executes the constructor function** to initialize properties using `this`.

## **Key mechanisms for instance creation:**

*   **Constructor Functions (ES5):** Defined as regular functions (conventionally capitalized), they initialize object properties when called with `new`.
    
    ```javascript
    function Person(name, age) {
      this.name = name;
      this.age = age;
    }
    const person1 = new Person("Alice", 30); // Creates an instance
    ```
    
*   **Class Constructors (ES6):** Modern `class` syntax uses an explicit `constructor` method that runs automatically upon instantiation.
    
    ```typescript
    class Person {
      constructor(name, age) {
        this.name = name;
        this.age = age;
      }
    }
    const person2 = new Person("Bob", 25); // Creates an instance
    ```
    
*   **Instance Properties:** Each instance holds its own unique values for properties (like `name` or `age`), while methods are typically shared via the **prototype** to save memory.
    
*   **Verification:** You can confirm an object is an instance of a constructor using the `instanceof` operator (e.g., `person1 instanceof Person` returns `true`).
    

Every object created this way inherits from its constructor's `prototype` via the `[[Prototype]]` chain, and the instance's `constructor` property references the original function or class used to create it.

## Summary

The article explains the `new` operator in JavaScript: what it does, why it’s used, and what happens behind the scenes when you call a constructor with `new`.

*   Definition: `new` creates an instance of a user-defined or built-in constructor function.
    
*   Execution steps (high level):
    
    1.  Creates a plain, empty object.
        
    2.  Links the new object’s internal prototype to the constructor’s `prototype`.
        
    3.  Binds `this` inside the constructor to the new object.
        
    4.  Calls the constructor function to initialize properties.
        
    5.  Returns the constructor’s non-primitive return value (if any); otherwise returns the newly created object.
        
*   Syntax: `new Constructor(arg1, arg2, ...)`.
    
*   Notes: ES6 classes must be instantiated with `new` (calling a class without `new` throws a `TypeError`). The operator is commonly used with built-in constructors like `Array`, `Date`, and `Function`.
    
*   Example: `const car1 = new Car("Eagle", "Talon TSi", 1993);` produces a `car1` instance with `make`, `model`, and `year` set by the `Car` constructor.
