What is the difference between void, eval, and the Function constructor in JavaScript?


The void keyword

The void is an important keyword in JavaScript, which can be used as a unary operator that appears before its single operand, which may be of any type. This operator specifies an expression to be evaluated without returning a value.

The syntax of the void can be either of the following two −

<head>
   <script>
      <!--
         void func()
         javascript:void func()
         or:
         void(func())
         javascript:void(func())
      //-->
   </script>
</head>

The eval() function

The JavaScript eval() is used to execute an argument. The code gets execute slower when the eval() method is used. It also has security implementations since it has a different scope of execution.

Example

Here’s how you can implement eval() function −

Live Demo

<html>
   <body>
      <script>
         var a = 30;
         var b = 12;
         var res1 = eval("a * b") + "<br>";
         var res2 = eval("5 + 10") + "<br>";
         document.write(res1);
         document.write(res2);
      </script>
   </body>
</html>

Output

360
15

Function Constructor

The function() constructor is used in JavaScript to create new function object. The objects created are parsed when the function is created.

Example

You can try to run the following code to learn how to work with function() constructor −

Live Demo

<html>
   <body>
      <script>
         var num = new Function('p', 'q', 'r', 'return p * q * r');
         document.write("Value after multiplication: "+num(5, 2, 9));
      </script>
   </body>
</html>

Output

Value after multiplication: 90

Updated on: 16-Jun-2020

181 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements