JavaScript new.target meta Property

The new.target pseudo-property let us detect whether a function or constructor is called with the help of new operator or not.

Syntax:

new.target

The following example demonstrates the meta property.

Example 1: In this example, the function is called without the new operator.



HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE HTML>
<html>
  
<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
  
    <p>
        JavaScript | new.target metaKey property
    </p>
      
    <button onclick="Geeks();">
        click here
    </button>
      
    <p id="GFG_DOWN"></p>
  
    <script>
        var el_down = document
                .getElementById("GFG_DOWN");
  
        function Fun() {
            if (!new.target) {
                throw 
    'Fun() is called without new operator';
            }
        }
        function Geeks(event) {
            try {
                Fun();
            } catch (e) {
                el_down.innerHTML = e;
            }
        
    </script>
</body>
  
</html>

chevron_right


Output:

Example 2: In this example, the function is called with the new operator.

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE HTML>
<html>
  
<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
    <p>
        JavaScript | new.target metaKey property
    </p>
  
    <button onclick="Geeks();">
        click here
    </button>
      
    <p id="GFG_DOWN"></p>
  
    <script>
        var el_down = document
                .getElementById("GFG_DOWN");
        class Person {
            constructor(name) {
                this.name = name;
                if (!new.target) {
throw 'Function is called without new operator';
                }
                else {
throw 'Function is called with new operator';
                }
            }
        }
        function Geeks(event) {
            try {
                var p = new Person('GFG');
            } catch (e) {
                el_down.innerHTML = e;
            }
        
    </script>
</body>
  
</html>

chevron_right


Output:

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.