JavaScript and Python are two of the most popular and commonly used languages in the world. JavaScript is an integral part of web development on both the front and back end. On the other hand, Python is more suitable for back-end coding and rapid application development.

While both have their benefits, you can get the best of both worlds by running JavaScript code from a Python program.

An Introduction to JavaScript and Its Syntax

JavaScript is a scripting language used for web development. You can use JavaScript to add behavior and functionality to web pages. It is an interpreted language meaning the code runs in real time without a compiler translating it to machine code.

Some of the language’s distinctive syntax features are:

  1. Code Blocks: JavaScript uses curly braces ({}) to enclose statements within the same block.
  2. Variables: You can define variables using the var keyword. The syntax for initializing a variable is var variable_name = value;.
  3. Constants: You can define constants using the const keyword. The syntax for defining a constant is, const constant_name = value;.
  4. Operators: You can use various logical operators in JavaScript including &&, || and !. The equality operator comes in two forms: == comparing value, and === comparing value and data type.
  5. Input/Output: You can take input in JavaScript using window.prompt() and display output on the console using console.log().

If you're looking to get into full-stack, front-end, or back-end development, you should understand the basics of JavaScript.

The Syntax of Python

Python is a high-level programming language that finds its application in backend development, Artificial Intelligence, and Data Science. Python is regarded as an interpreted language that's dynamically typed and garbage collected.

A few key syntaxes in Python to note are:

  1. Code Blocks: Python uses indentations to enclose statements within the same block.
  2. Variables: You can initialize variables in Python as variable_name = value.
  3. Constant: Python doesn't really support constants, but convention states that you name variables that shouldn't change with capital letters e.g. CONSTANT_NAME.
  4. Operators: You can use logical operators like and, or​​​​​​, and not. Use the Equality operator (==) to compare both the value and type of data.
  5. Input-Output: You can obtain input from the user using input() and display the output using print().

Python is one of the easiest languages to master and with wide applications you should definitely get your hands dirty with it. These courses and apps are a great place to learn Python for free.

What Is the Js2Py Module?

Js2Py is a JavaScript-to-Python translator and JavaScript interpreter written in 100% pure Python by Piotr Dabkowski. To install this module, open your Terminal and execute:

        pip install js2py
    

Js2Py translates any valid JavaScript (ECMA Script 5.1, ECMA 6) to Python automatically without using any dependency. It only uses the standard Python library.

There are three limitations to using the Js2Py module as listed in this official documentation on GitHub:

  1. Js2py ignores strict mode.
  2. The with statement is not supported.
  3. It treats an indirect call to eval as a direct call to eval.

Despite these limitations, the module works perfectly well and converts most of the JavaScript code into Python language.

Examples of Running JavaScript Code in Python

These are a few examples of translating and running your JavaScript code in Python:

1. The Hello World Program

The first program you write in any language is the Hello World program. You implement it as:

        import js2py
js2py.eval_js('console.log("Hello World!")')

The first step is the import the js2py module into your environment. Pass the JavaScript code as a parameter to eval_js() to evaluate it. On passing console.log("Hello World!") it displays Hello World! on the output terminal of Python as it does on the console windows of the browser.

Running Hello World program for JS to PY

2. A Function to Add Two Numbers

This is how you can perform the addition of two numbers using JavaScript in Python:

        import js2py
js_add = '''function add(a, b){
return a + b;
}'''
add = js2py.eval_js(js_add)
print(add(3, 7))

Declare a function using JavaScript format and enclose it in the multiline string (""" or '''). You can store it in a variable called js_add. Pass the function variable to eval_js() to translate it into Python equivalent. Display the result by making a function call and passing two numbers as arguments.

This is the output obtained for the addition of two numbers using a function in JavaScript:

Running addition of two number program for JS to PY

3. How to Convert an Entire JavaScript File Into a Python File

Suppose you have a JavaScript file named example.js that contains the following code:

        // Object
function Rectangle(w, h) {
    this.w = w;
    this.h = h
}
 
Rectangle.prototype = {
    getArea: function () {
        return this.w * this.h
    }
};
 
x = new Rectangle(10, 5)

This JavaScript contains a function Rectangle that takes width and height as parameters and returns the calculated area using the formula width * height.

There are two simple methods to convert the JavaScript file into a Python file. They are:

  1. The first method runs the JavaScript file without explicitly translating it. You can implement it as:
            import js2py
    eval_result, example = js2py.run_file('example.js')
    The run_file() takes a JavaScript file as an argument and returns the result of the evaluation along with an object you can use to run and test any JS code.
  2. The second method explicitly converts and saves the whole JavaScript file into a Python file. You can implement it as:
            import js2py
    js2py.translate_file('example.js', 'example.py')
    By using the first method you can work with the JavaScript file in your Python environment itself. However, if you just want to convert and run the file in Python, the second method is more feasible.

4. Creating an Object Using the New Function

One thing to note is that you cannot create an object of the JavaScript file as new example.Rectangle(8,2). Instead, you have to use .new(8,2). You can code it as:

        import js2py
eval_result, example = js2py.run_file('example.js')
rect = example.Rectangle.new(8,2)
print(rect.getArea())

Using the first method, translate the JavaScript file which contains the code to calculate the area of a rectangle. Use the dot (.) operator to access the Rectangle function within the evaluated file and use the new() function to create its object. Pass two numbers as an argument. Use the getArea() function to calculate the area and display it using the print statement.

This is the output obtained for the calculation of the area of a rectangle using JavaScript:

Running calculation of rectangle area program for JS to PY

Running Python in the Browser

While Python is a popular tool that you can use to code on the backend, there are a few tools you can explore to try it on the front end as well. You can use Brython, Transcrypt, and Pyjs to write JavaScript-powered web applications entirely in Python.

You can use other strategies to combine Python code and JavaScript in the same application. The most straightforward is by communicating via a simple, open standard like JSON.