Run JavaScript in Python with Code For Beginners

In this article, you’ll learn how to run JavaScript in python.

Prerequisites:

  1. Python Basics
  2. JavaScript Basics
  3. js2py module

What is JavaScript:

  • JavaScript, often abbreviated as JS, is a programming language that conforms to the ECMAScript specification.
  • JavaScript is high-level, often just-in-time compiled, and multi-paradigm.
  • It has curly-bracket syntax, dynamic typing, prototype-based object orientation, and first-class functions.

Install Necessary Modules:

Open your  Prompt  and type and run the following command (individually):

pip install js2py

js2py the module is used to translator JavaScript to Python & acts as a JavaScript interpreter written in 100% pure Python.

  • It translates any valid JavaScript (ECMA Script 5.1) to Python.
  • Translation is fully automatic.
  • Does not have any dependencies – uses only standard python library.

Limitations:

  • strict mode is ignored.
  • with statement is not supported.
  • Indirect call to eval will is treated as direct call to eval (hence always evals in local scope)

Once Installed now we can import it inside our python code.

Source Code:

'''
Python Program to Run JavaScript in Python
'''

"""
Equivalent Python code:

# Example 1:          
print("Running JavaScript in Python")
            
#Example 2:            
def add(x, y):
    return x + y
    
"""


# Import the necessary module!
import js2py

# Example 1: JavaScript command
# Use of eval.js method from js2py module here, 
# Pass in our js code in it and store it in res1.
js_1 = 'console.log("Running JavaScript in Python")'

res1 = js2py.eval_js(js_1)

# Print the result
res1

########################################################

# Exapmle 2: JavaScript function

# Ask for user input
x = int(input("Enter value of x: "))
js_2 = '''function add(x, y){
    return x + y;
    }'''
# Use of eval.js method from js2py module here, 
# Pass in our js code in it and store it in res2.    
res2 = js2py.eval_js(js_2)

# Print the result
print("Result: x + 3 =", res2(x,3))

Output:


'Running JavaScript in Python'
Enter value of x: 6
Result: x + 3 = 9Code language: JavaScript (javascript)

Leave a Comment