- Javascript Basics Tutorial
- Javascript - Home
- JavaScript - Overview
- JavaScript - Features
- JavaScript - Enabling
- JavaScript - Placement
- JavaScript - Syntax
- JavaScript - Hello World
- JavaScript - Console.log()
- JavaScript - Comments
- JavaScript - Variables
- JavaScript - let Statement
- JavaScript - Constants
- JavaScript - Data Types
- JavaScript - Type Conversions
- JavaScript - Strict Mode
- JavaScript - Reserved Keywords
- JavaScript Operators
- JavaScript - Operators
- JavaScript - Arithmetic Operators
- JavaScript - Comparison Operators
- JavaScript - Logical Operators
- JavaScript - Bitwise Operators
- JavaScript - Assignment Operators
- JavaScript - Conditional Operators
- JavaScript - typeof Operator
- JavaScript - Nullish Coalescing Operator
- JavaScript - Delete Operator
- JavaScript - Comma Operator
- JavaScript - Grouping Operator
- JavaScript - Yield Operator
- JavaScript - Spread Operator
- JavaScript - Exponentiation Operator
- JavaScript - Operator Precedence
- JavaScript Control Flow
- JavaScript - If...Else
- JavaScript - While Loop
- JavaScript - For Loop
- JavaScript - For...in
- Javascript - For...of
- JavaScript - Loop Control
- JavaScript - Break Statement
- JavaScript - Continue Statement
- JavaScript - Switch Case
- JavaScript - User Defined Iterators
- JavaScript Functions
- JavaScript - Functions
- JavaScript - Function Expressions
- JavaScript - Function Parameters
- JavaScript - Default Parameters
- JavaScript - Function() Constructor
- JavaScript - Function Hoisting
- JavaScript - Self-Invoking Functions
- JavaScript - Arrow Functions
- JavaScript - Function Invocation
- JavaScript - Function call()
- JavaScript - Function apply()
- JavaScript - Function bind()
- JavaScript - Closures
- JavaScript - Variable Scope
- JavaScript - Global Variables
- JavaScript - Smart Function Parameters
- JavaScript Objects
- JavaScript - Number
- JavaScript - Boolean
- JavaScript - Strings
- JavaScript - Arrays
- JavaScript - Date
- JavaScript - DataView
- JavaScript - Math
- JavaScript - RegExp
- JavaScript - Symbol
- JavaScript - Sets
- JavaScript - WeakSet
- JavaScript - Maps
- JavaScript - WeakMap
- JavaScript - Iterables
- JavaScript - Reflect
- JavaScript - TypedArray
- JavaScript - Template Literals
- JavaScript - Tagged Templates
- Object Oriented JavaScript
- JavaScript - Objects
- JavaScript - Classes
- JavaScript - Object Properties
- JavaScript - Object Methods
- JavaScript - Static Methods
- JavaScript - Display Objects
- JavaScript - Object Accessors
- JavaScript - Object Constructors
- JavaScript - Native Prototypes
- JavaScript - ES5 Object Methods
- JavaScript - Encapsulation
- JavaScript - Inheritance
- JavaScript - Abstraction
- JavaScript - Polymorphism
- JavaScript - Destructuring Assignment
- JavaScript - Object Destructuring
- JavaScript - Array Destructuring
- JavaScript - Nested Destructuring
- JavaScript - Optional Chaining
- JavaScript - Global Object
- JavaScript - Mixins
- JavaScript - Proxies
- JavaScript Versions
- JavaScript - History
- JavaScript - Versions
- JavaScript - ES5
- JavaScript - ES6
- ECMAScript 2016
- ECMAScript 2017
- ECMAScript 2018
- ECMAScript 2019
- ECMAScript 2020
- ECMAScript 2021
- ECMAScript 2022
- JavaScript Cookies
- JavaScript - Cookies
- JavaScript - Cookie Attributes
- JavaScript - Deleting Cookies
- JavaScript Browser BOM
- JavaScript - Browser Object Model
- JavaScript - Window Object
- JavaScript - Document Object
- JavaScript - Screen Object
- JavaScript - History Object
- JavaScript - Navigator Object
- JavaScript - Location Object
- JavaScript - Console Object
- JavaScript Web APIs
- JavaScript - Web API
- JavaScript - History API
- JavaScript - Storage API
- JavaScript - Forms API
- JavaScript - Worker API
- JavaScript - Fetch API
- JavaScript - Geolocation API
- JavaScript Events
- JavaScript - Events
- JavaScript - DOM Events
- JavaScript - addEventListener()
- JavaScript - Mouse Events
- JavaScript - Keyboard Events
- JavaScript - Form Events
- JavaScript - Window/Document Events
- JavaScript - Event Delegation
- JavaScript - Event Bubbling
- JavaScript - Event Capturing
- JavaScript - Custom Events
- JavaScript Error Handling
- JavaScript - Error Handling
- JavaScript - try...catch
- JavaScript - Debugging
- JavaScript - Custom Errors
- JavaScript - Extending Errors
- JavaScript Important Keywords
- JavaScript - this Keyword
- JavaScript - void Keyword
- JavaScript - new Keyword
- JavaScript - var Keyword
- JavaScript HTML DOM
- JavaScript - HTML DOM
- JavaScript - DOM Methods
- JavaScript - DOM Document
- JavaScript - DOM Elements
- JavaScript - DOM Forms
- JavaScript - Changing HTML
- JavaScript - Changing CSS
- JavaScript - DOM Animation
- JavaScript - DOM Navigation
- JavaScript - DOM Collections
- JavaScript - DOM Node Lists
- JavaScript Miscellaneous
- JavaScript - Ajax
- JavaScript - Async Iteration
- JavaScript - Atomics Objects
- JavaScript - Rest Parameter
- JavaScript - Page Redirect
- JavaScript - Dialog Boxes
- JavaScript - Page Printing
- JavaScript - Validations
- JavaScript - Animation
- JavaScript - Multimedia
- JavaScript - Image Map
- JavaScript - Browsers
- JavaScript - JSON
- JavaScript - Multiline Strings
- JavaScript - Date Formats
- JavaScript - Get Date Methods
- JavaScript - Set Date Methods
- JavaScript - Modules
- JavaScript - Dynamic Imports
- JavaScript - BigInt
- JavaScript - Blob
- JavaScript - Unicode
- JavaScript - Shallow Copy
- JavaScript - Call Stack
- JavaScript - Reference Type
- JavaScript - IndexedDB
- JavaScript - Clickjacking Attack
- JavaScript - Currying
- JavaScript - Graphics
- JavaScript - Canvas
- JavaScript - Debouncing
- JavaScript - Performance
- JavaScript - Style Guide
- JavaScript Useful Resources
- JavaScript - Questions And Answers
- JavaScript - Quick Guide
- JavaScript - Functions
- JavaScript - Resources
JavaScript - new Keyword
The new keyword in JavaScript is used to create an instance of the object that has constructor function. Using new keyword, we can create the instances of a user-defined as well as built-in object types. We can create instances of the classes, prototype, or constructor functions.
When a JavaScript function is called with new keyword, the function is used as constructor. The new keyword will do the following:
Creates a blank/ empty JavaScript object.
Sets its prototype for inheritance.
Binds this variable internally with newly created object.
Executes the constructor function using new crated object whenever this is used.
Returns newly created object, unless the contractor function returns a non-null object reference.
The new keyword is also used to create an instance of the built-in JavaScript objects like String, Boolean, Number, etc.
Syntax
The syntax to use the new keyword in JavaScript is as follows –
new Constructor(arguments);
Parameters
Constructor − It is the name of the constructor function or class name.
arguments −It can be multiple arguments to initialize the object properties with them.
Return Value
It returns the newly created object if the constructor function returns nothing or a primitive value.
It returns the value that is returned by constructor function if constructor returns a non-primitive value.
Using 'new' keyword with Function Constructor
To use a function as a constructor, we should call the function with new keyword placing it before the function name.
We can define multiple objects using function constructor. The function constructor works as the object's prototype.
Follow the syntax below to use the 'new' keyword and constructor function to define the object.
new FuncName(arguments);
Example
We have defined the Watch() constructor function in the code below.
The Watch() constructor function initializes the brand, price, and type properties.
After that, we have created two new instances of the Watch() function and printed them in the output.
<html> <body> <div id = "output"> </div> <script> function Watch(brand, price, type) { this.brand = brand; this.price = price; this.type = type; } const titan = new Watch('titen', 4000, 'analog'); const sonata = new Watch('sonata', 3000, 'digital'); document.getElementById('output').innerHTML += "The titan object is: " + JSON.stringify(titan) + "<br>" + "The sonata object is: " + JSON.stringify(sonata); </script> </body> </html>
Output
The titan object is: {"brand":"titen","price":4000,"type":"analog"} The sonata object is: {"brand":"sonata","price":3000,"type":"digital"}
Example
In the below code, we have defined the Laptop() constructor function, initializing various properties related to the laptop. Also, we have defined the getLaptop() function, which prints the laptop details.
After that, we created the two instances of the Laptop() object and used the getLaptop() method with both. In this way, you can share single methods with different objects.
<html> <body> <div id = "output"> </div> <script> const output = document.getElementById('output'); function Laptop(brand, model, processor) { this.brand = brand; this.model = model; this.processor = processor; this.getLaptop = function () { output.innerHTML += this.brand + ", " + this.model + ", " + this.processor + "<br>"; } } const HP = new Laptop('HP', "VIKING", "i7"); const Dell = new Laptop('Dell', "Inspiron", "i5"); HP.getLaptop(); Dell.getLaptop(); </script> </body> </html>
Output
HP, VIKING, i7 Dell, Inspiron, i5
Using 'new' keyword with Class
You can also use the new keyword to define the instance of a class. The class also provides the blueprint for the object.
Before ES6, the constructor function was used to define the template for the object. After ES6, classes are used to define the template for the object.
Example
In the below example, we have defined the 'WindowClass class. In the 'WindowClass' we have added the constructor to initialize the properties. We have also added the getDetails() method in the class.
After that, we used the 'new' keyword followed by the class name to define an object of the WindowClass.
Next, we invoke the getDetails() method on the instance of the class.
<html> <body> <div id = "demo"> </div> <script> const output = document.getElementById('demo') class WindowClass { constructor(color, size, type) { this.color = color; this.size = size; this.type = type; } getDetails = function () { output.innerHTML = "Color: " + this.color + "<br>" + "Size: " + this.size + "<br>" + "Type: " + this.type; } } // Creating the instance of WindowClass class const window1 = new WindowClass('blue', 'small', 'wooden'); // Calling function object window1.getDetails(); </script> </body> </html>
Output
Color: blue Size: small Type: wooden
Using 'new' keyword with built-in object
You can also use the 'new' keyword to define the instance of the built-in object having constructor functions.
Follow the syntax below to create an instance of the built-in object Number.
const num = new Number(10);
In the above syntax, we have passed the numeric value as an argument of the Number() constructor.
Example
In the code below, we have used the Number() and String() constructors with a new keyword to define the numeric and string objects.
After that, we used the 'typeof' operator to check the type of num and str variables. In the output, you can see that the num and str variable type is an object.
<html> <body> <div id = "output"> </div> <script> const num = new Number(10); const str = new String("Hello"); document.getElementById("output").innerHTML = "num = " + num + ", typeof num " + typeof num + "<br>" + "str = " + str + ", typeof str " + typeof str; </script> </body> </html>
Output
num = 10, typeof num object str = Hello, typeof str object