How to use the 'with' keyword in JavaScript?

JavascriptWeb DevelopmentFront End Technology

The with keyword is used as a kind of shorthand for referencing an object's properties or methods.

The object specified as an argument to with becomes the default object for the duration of the block that follows. The properties and methods for the object can be used without naming the object.


The syntax for with object is as follows −

with (object){
   properties used without the object name and dot


You can try to learn the following code to learn how to implement with keyword −

Live Demo

      <title>User-defined objects</title>
         // Define a function which will work as a method
         function addPrice(amount){
               price = amount;
         function book(title, author){
            this.title = title;
   = author;
            this.price = 0;
            this.addPrice = addPrice; // Assign that method as property.
      <script type="text/javascript">
         var myBook = new book("Python", "Tutorialspoint");

         document.write("Book title is : " + myBook.title + "<br>");
         document.write("Book author is : " + + "<br>");
         document.write("Book price is : " + myBook.price + "<br>");


Book title is : Python
Book author is : Tutorialspoint
Book price is : 100
Published on 03-Feb-2018 15:57:00