Get started with running JavaScript in Google Sheets
This tutorial will show you how to run JavaScript code in Google Sheets.
PrerequisitesYou're familiar with the basics of Google Sheets.
You know how to create a script from your spreadsheet.
You're familiar with the concept of a Custom Function in Google Sheets.
Step 1 — Create a new Google Sheets spreadsheet
You're familiar with the basics of Google Sheets.
You know how to create a script from your spreadsheet.
You're familiar with the concept of a Custom Function in Google Sheets.
I personally use the URL https://spreadsheet.new to create a new spreadsheet but you can also create one using Google Drive.
Step 2 — Create a Custom Function to evaluate JavaScript
Open the script editor by selecting Extensions —> Apps Script from the menu.
Delete any code in the script editor. Then copy paste the code below into the editor.
/**
* Evaluates JS code.
*
* @param {code} code The code to evaluate.
* @return The result from evaluating the code.
* @customfunction
*/
function RUNJS(code) {
return eval(code);
}
The RUNJS()
function accepts JavaScript code
as input, evaluates it using JavaScript's eval()
function and returns the result.
Save the code by selecting File —> Save from the script editor's menu or by pressing CTRL + S
on your keyboard.
Step 3 — Use the function to run JavaScript code in Google Sheets
You can now use the =RUNJS()
function in your spreadsheet. To try it out, enter 1+1 in cell A2 and enter the formula =RUNJS(A2)
in cell B2. The resulting value in cell B2 is 2, which is the output of evaluating the JavaScript expression 1 + 1
.
Here are some other JavaScript expressions to try out:
JavaScript expression | Description | Expected result |
---|---|---|
1 + 1 | Adding two numbers | 2 |
true && false | An expression that uses the AND logical operator | false |
false || (true || false) | An expression that uses the AND and OR logical operators | true |
2**2 | Exponentiation (similar to the | 4 |
[1,2,3].length | Length of an array | 3 |
1 + 2 * 2 | An expression to illustrate operator precedence |
Below is a screenshot of the results I got by evaluating the JavaScript expressions in the above table using the RUNJS()
function.
Conclusion
This tutorial showed you how you can run JavaScript code in Google Sheets. I thought of this approach while creating exercises for the Learn coding using Google Sheets and Apps Script tutorial. It worked perfectly for my use case so I decided to write this post to help others that might find this technique useful.
Thank you for reading!
Master Google Sheets Automation
I'd appreciate any feedback you can give me regarding this post.
Was it useful? Are there any errors or was something confusing? Would you like me to write a post about a related topic? Any other feedback is also welcome. Thank you so much!