One can run JavaScript and other programming languages in the Jupyter notebook
In the previous articles, I have introduced how to run Python, R, and HTML in the Jupyter notebook. You can read these articles if you are interested in them.
2. Different Methods to Edit and Run Python Files in Jupyter Notebook
The Jupyter system supports over 100 programming languages (called “kernels” in the Jupyter ecosystem). Besides Python, R, it also includes Java, Julia, Matlab, Scala, and many more (https://github.com/jupyter/jupyter/wiki/Jupyter-kernels).
In addition, we can run JavaScript directly in the Jupyter notebook without installing “kernels”. In this post, I will introduce two convenient methods to run JavaScript in the Jupyter notebook.
1. Use Magic Command
The first handy method is to use magic command %%js
, or %%javascript
to run JavaScript in the Jupyter notebook. For example, let’s run a simple "hello, world!"
by typing the following code.
%%js
alert("hello, world!");
The outcome looks as:
Let’s see another simply addition example. Type the following code snippet and then click run.
%%js
var x = 5;
var y = 6;
var z = x + y;
element.text(z)
The running process and result looks as follows:
2. Use IPython JavaScript Module
We can also use IPython JavaScript Module to run JavaScript in the Jupyter notebook. First, we have to import the module by the following code:
from IPython.display import Javascript
Let’s still use the above two examples.
(1) One-line example
simpjs = Javascript('alert("hello, world!")')
display(simpjs)
We will get the same result as the one using the magic command.
(2) Multi-line example
js="""
var x = 5;
var y = 6;
var z = x + y;
element.text(z)
"""
jsvar=Javascript(js)
display(jsvar)
Or we can use the following method.
js=Javascript(
'''
var x = 5;
var y = 6;
var z = x + y;
element.text(z)
''')
display(js)
The outcome is the same as the one that we use the magic command.
3. Video Version
If you like a video version of this post, please go to my YouTube channel to watch it. If it is helpful, please subscribe my channel to show your support.
4. Course
If you are interested in learning Jupyter notebook in details, you are welcome to enroll one of my course Practical Jupyter Notebook from Beginner to Expert.