JavaScript Playground: Run JS Online with a Real Console
What is a JavaScript playground?
It’s a place to try JavaScript without setting anything up. Type some code on the left, press Run, and whatever
your code prints with console.log() shows up in the console on the right. Errors show up there too, in
red, with the line number. Click the line number and the editor jumps to it.
You may have seen tools like this called a JavaScript compiler. JavaScript isn’t really compiled ahead of time like
C or Java: your browser reads it and runs it straight away, which is exactly what happens here. Nothing is installed
and nothing is sent to our server. The code runs in your own browser.
How to Use It, Step by Step
Step 1 Write Some JavaScript
Start in the JS tab. No setup, no <script> tags, no HTML file. A single line
is enough to get going:
console.log('Hello, Sam!');
Not sure what to write? Open Samples: there’s a coffee order total, a menu sorted with array
methods, waiting with await, a button added to the page and an error to practise reading.
Step 2 Press Run
Click the lime Run button or press Ctrl + Enter (Cmd +
Enter on a Mac). The shortcut works wherever your cursor is on the page, even inside the Preview.
Every run starts from a clean page, so old timers and variables are gone.
Auto run is off at first, on purpose. If it ran on every key press, a half-typed
while loop could run before you’ve written the line that ends it. Turn it on when you want it: the
code then runs a moment after you stop typing.
Step 3 Read the Console
Each message gets its own row. A few things that make it easier to read:
- Objects and arrays open with the little arrow, so you can look inside nested data.
- The link on the right of a row (like line 12) jumps to the line that printed it.
- Errors, Warnings and Logs filter the list, and the numbers tell you how many of each you have.
- The same message printed many times in a row is shown once, with a count next to it.
- Timestamps adds the time to every row. Keep old logs stops the console from clearing on each run.
Step 4 Add HTML and CSS if You Need a Page
Your code runs inside a real web page, so document works. Click + HTML/CSS to get
two more tabs, then open the Preview tab to see and click that page. A green dot on Preview means
your code put something on the page.
Try it: HTML tab
<p id="total">Total: $0.00</p>
<button id="add">Add a latte ($3.80)</button>
JS tab
let total = 0;
document.getElementById('add').addEventListener('click', () => {
total += 3.8;
document.getElementById('total').textContent = 'Total: $' + total.toFixed(2);
});
Want the full HTML, CSS and JS editor with a big live preview instead? That’s the
HTML Editor.
Step 5 Keep Your Work
Your code stays in this browser, so it’s still there next time you open the page. To keep it for good, click
Download. You get one playground.html file with your JS, HTML and CSS in it.
Double-click it and it opens in your browser. Press F12 there to see the console output in the
browser’s own developer tools.
Console Methods, with Tiny Examples
console.log() does most of the work, but the console has a few other methods that save time. Each one
below works in this playground and in every modern browser.
console.log(): print anything
Give it as many values as you like, separated by commas. It puts a space between them.
const name = 'Sam';
const cups = 2;
console.log('Hello,', name);
console.log(name, 'ordered', cups, 'cups');
console.log('%s owes $%d', name, 7.6);
Hello, Sam
Sam ordered 2 cups
Sam owes $7
The last line uses a format string: %s is filled with a string and %d with a whole
number (so 7.6 becomes 7). Plain commas are usually easier to read.
Logging objects and arrays
Objects show as a one-line summary. Click the arrow to open them, and again on anything nested inside.
const order = { drink: 'Latte', size: 'large', extras: ['oat milk'] };
console.log(order);
▸ {drink: 'Latte', size: 'large', extras: Array(1)}
One difference from your browser’s developer tools: this console shows the object as it was at the moment you
logged it. If you change it later, the row doesn’t change. Log it again to see the new values.
console.table(): arrays of objects as a grid
Use it for lists of things that share the same fields, like products or users.
console.table([
{ drink: 'Latte', price: 3.8 },
{ drink: 'Tea', price: 2.1 },
]);
(index) │ drink │ price
0 │ Latte │ 3.8
1 │ Tea │ 2.1
console.info(), console.warn() and console.error()
Same as log, but they get an icon and a color, and the filters can pick them out.
console.info('Shop opens at 8');
console.warn('Only 3 croissants left');
console.error('Card machine is offline');
ℹ Shop opens at 8
⚠ Only 3 croissants left
✖ Card machine is offline
console.group(): fold related messages together
Everything between group() and groupEnd() is indented under one heading you can close. Use groupCollapsed() to start it closed.
console.group('Table 4');
console.log('Latte');
console.log('Banana bread');
console.groupEnd();
▾ Table 4
Latte
Banana bread
console.time() and console.count()
time and timeEnd with the same label measure how long the code between them took.
count prints how many times it has been called with that label.
console.time('sort');
const prices = [5.5, 3, 4.2, 3.8].sort((a, b) => a - b);
console.timeEnd('sort');
for (const p of prices) console.count('price');
sort: 0.051 ms
price: 1
price: 2
price: 3
price: 4
Your time will be a little different, it depends on your computer.
console.assert(): complain only when something is wrong
If the first value is false, it prints an error with your message. If it’s true, it stays quiet.
const stock = 0;
console.assert(stock > 0, 'Out of stock!');
console.assert(1 + 1 === 2, 'Never shown');
✖ Assertion failed: Out of stock!
The rest work too: console.debug(), console.dir(), console.trace()
(shows how your code got to that line), console.timeLog(), console.countReset() and
console.clear().
Reading Error Messages
Red text looks scary, but an error message is mostly the browser telling you where to look. Take this one:
const user = { name: 'Sam' };
console.log(user.adress.city);
✖ Uncaught TypeError: Cannot read properties of undefined (reading 'city') line 2
- Uncaught means nothing caught the error, so the code stopped right there.
- TypeError is the kind of error. It means a value was the wrong type for what you did with it.
- The rest says what happened: it tried to read
city from something that was undefined. That something is user.adress, because the property is spelled address. - line 2 is a link. Click it and the line turns red in the editor.
Under most errors you’ll see a short tip. These are the ones you’ll meet most:
| The message says | It usually means |
x is not defined | The name doesn’t exist. Usually a typo (names are case-sensitive, so total and Total are two different things) or a variable used before you made it. |
Cannot read properties of undefined (reading 'x') | The thing before the dot is undefined. Log it on the line before. A misspelled property name is the classic cause. |
x is not a function | You put ( ) after something that isn’t a function, like calling price() when price is a number. |
Assignment to constant variable | You gave a const a new value. Use let for values that change. |
Unexpected token / Unexpected end of input | A bracket, quote or comma is missing or extra. The whole script stops before running a single line. |
await is only valid in async functions and the top level bodies of modules | Put the await inside an async function, or tick Module so top-level await works. |
Catching errors yourself
When you expect something might fail, like reading data you didn’t write, wrap it in try and
catch. The error goes to your catch block instead of stopping everything.
try {
JSON.parse('{ not json }');
} catch (err) {
console.warn('Could not read the data:', err.message);
}
console.log('Still running');
⚠ Could not read the data: Expected property name or '}' in JSON at position 2 ...
Still running
The exact wording of the JSON message depends on your browser.
Timers, Promises and await
Code that waits doesn’t hold up the code after it. Most people expect the opposite the first time they see it:
console.log('1. Order placed');
setTimeout(() => console.log('3. Coffee ready'), 1000);
console.log('2. Waiting...');
1. Order placed
2. Waiting...
3. Coffee ready
Line 3 prints before the timer, because setTimeout only schedules the function for later. The console
keeps listening after your code finishes, so messages from timers, clicks and promises still arrive. Press
Stop to end a setInterval that keeps going.
import and top-level await need Module
Tick Module and your code runs as a JavaScript module. Then you can use await outside
a function and import packages from a CDN by URL. Those imports load from that site, not from us.
// Tick "Module" first
import { format } from 'https://esm.sh/[email protected]';
console.log(format(new Date(), 'EEEE d MMMM'));
const res = await fetch('https://api.github.com/zen');
console.log(await res.text());
fetch() works for sites that allow requests from other pages (that’s called CORS). Many public APIs do.
If a site doesn’t, the request fails with “Failed to fetch” and there’s nothing your code can do about it from a
browser.
Why Your Code Runs in a Locked Box
Your code runs in a sandboxed frame that the browser treats like a page from nowhere. It can draw on its own page,
show alerts and talk to sites that allow it, but it can’t touch this website, its cookies or anything you’re signed in
to. That keeps you safe when you paste code from a tutorial or a stranger’s answer to see what it does.
The same box is why localStorage and document.cookie throw a SecurityError here. Download
the file and open it if you need to test storage.
Loop protection
A loop that never ends, like while (i < 10) where you forgot i++, would normally freeze
the whole tab. With Loop protection on, a loop that keeps the page busy for more than a second
without a break is stopped, with a message pointing at its line. That counts from the moment the loop starts, so two
half-second loops in a row are fine. Waiting for a timer (await on a setTimeout promise) is
a break. Awaiting promises that are already done is not, so while (true) { await null } gets
stopped too. Loops in <script> tags in the HTML tab are covered as well.
If you’re timing something heavy on purpose, untick it and run again. Without it, an endless loop can’t be stopped
from the page: the Stop button will tell you to reload. Your code is saved first, and after a freeze the playground
doesn’t run that code again on its own when the page opens.
What It Can’t Do
- No Node.js.
require(), fs, process and other Node APIs
don’t exist in a browser. Browser features like document, fetch and
setTimeout are all there.
- No npm install. With Module ticked you can import a package from a CDN URL instead, if the
package works in a browser.
- No TypeScript. Type annotations are a syntax error here. Plain JavaScript only.
- No requests to sites that don’t allow it. That’s the browser’s CORS rule, and no online editor can
get around it.
- Not a full debugger. There are no breakpoints. For that, download the file and use your browser’s
developer tools. The
debugger; statement does pause there.
Related Tools and Guides
Frequently Asked Questions
Is my code saved?
Yes, in this browser only. Your JS, HTML and CSS are kept on this device, so they are still there when you come back. Nothing is sent to our server. To keep your work for good or move it to another computer, click Download and you get one .html file with everything in it.
Where does console.log() output go?
Into the Console panel on the right, as soon as you press Run. Errors show up there too, in red, with a link to the line. If you open your browser’s developer tools (F12) you will see the same messages there as well.
Why doesn’t my code run as I type?
Auto run is off at first, so a half-written loop can’t run before you finish it. Press Run or Ctrl+Enter (Cmd+Enter on a Mac) when you’re ready, or tick Auto run to run a moment after you stop typing.
Can I use import and top-level await?
Yes. Tick Module and your code runs as a JavaScript module, so await works outside functions and you can import packages from a CDN by their URL, for example from esm.sh or jsDelivr. Those files load from that site.
Can I use require(), fs or npm packages?
No. Those belong to Node.js, which runs on a computer or server, not in a web page. Your code here runs in the browser, so you get browser features like document, fetch and setTimeout instead. Many npm packages also work in the browser through a CDN import with Module ticked.
My fetch() call fails with “Failed to fetch”. Why?
Most often the site doesn’t allow requests from other pages (the browser’s CORS rule), so the browser blocks the answer. Public APIs that allow it work fine. It can also mean the address is wrong or you are offline.
What happens if I write a loop that never ends?
With Loop protection on, a loop that keeps the page busy for more than a second without a break is stopped, and the console tells you which line it was on. That includes loops in script tags in the HTML tab, and loops that only await promises. Press Stop to end timers and intervals. With Loop protection off, an endless loop can’t be stopped from the page, so you will be asked to reload. Your code is saved, and it won’t run again by itself when the page opens.
Why does localStorage throw an error?
Your code runs in a locked sandbox that has no access to this website, and that includes storage and cookies. It keeps the code you paste from touching anything else. Download the .html file and open it in your browser to test storage.
Is it free?
Yes. No signup, no limits, and it works on phones too.