How to display the result of a Javascript cell?

Hi, I have this JS code in a code cell and when it runs nothing happens…

%%js
// Put a zero in for the unknown value
let n1 = 1;
let d1 = 2;
let n2 = 0;
let d2 = 16;

if (n2 === 0) {
  let answer = (d2 * n1) / d1;
  console.log("n2 =", answer);
}

if (d2 === 0) {
  let answer = (n2 * d1) / n1;
  console.log("d2 =", answer);
}

I’m trying to translate that python code that work:

# Put a zero in for the unknown value
n1 = 1
d1 = 2
n2 = 0
d2 = 16

if n2==0:
    answer = d2 * n1 / d1
    print("n2 = ", answer)
    
if d2==0:
    answer = n2 * d1 / n1
    print("d2 = ", answer)

thanks for your help :slight_smile:

The code just runs in your browser, so the output is in the browser console.

If you want the output to be inside a notebook you should install nodejs and a javascript kernel.
I use tslab but since jupyterlab 4 the syntax highlighting does not work anymore.

2 Likes

Hey @spookster! thank you so much for your answer!
I see, yes I’m getting the correct output in the console.
Now I tried to install tslab following the recommendations from the Github link:


(I have Python 3.10.6 and node v20.4.0 installed)
but it still doesn’t work:
image
I’m using Jupyter Notebook 7.0
Thank you :slight_smile:

the syntax highlighting suggest you are still on the Python kernel.

you need to create a notebook using the javascript kernel or switch the kernel in the top right corner to the javascript kernel.

1 Like

@spookster it works! (after restarting the server)
thanks for your help I really appreciate it! have a good one :slight_smile:

2 Likes

@spookster I’m getting this error when restarting the server:

image

running the Python 3 (ipykernel) kernel works fine… any idea?

finding this post: Kernel Error: Failed to start a kernel - #3 by Rose_Zhang
it looks like it works when I start the server from the command line but not from the launcher… (on linux mint with jupyter notebook 7.0)

add the the folder with npm binaries to your PATH environment variable.

Hi @spookster, I have tried different stackoverflow solutions like

export PATH=$PATH:/home/user_name/.nvm/versions/node/v20.4.0/bin

or

image

** with the correct path I get from which node **

but nothing worked so far…
Would you mind telling me the commands?
Thank you

this should normally work but I don’t know why it’s not working for you.

you can put the complete path into the .local/share/jupyter/kernels/jslab/kernel.json (and the tslab kernel too while you are at it).

just change

{"argv": ["tslab", "kernel", "--config-path", "{connection_file}", "--js"], "display_name": "JavaScript", "language": "javascript"}

to something like this:

{"argv": ["/path/to/your/tslab/executable/from/which/tslab", "kernel", "--config-path", "{connection_file}", "--js"], "display_name": "JavaScript", "language": "javascript"}