iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Output

JavaScript can write output to the console, the DOM, an alert, or back to the server. Pick the right tool for the situation.

Five ways to output

EXAMPLE
// 1. console - the developer's primary tool
console.log('plain message');
console.warn('warning');
console.error('error - shows stack trace');
console.info('info');
console.debug('debug (hidden by default)');

// Tables, groups, and timing - all underused
console.table([{ id: 1, name: 'Ada' }, { id: 2, name: 'Linus' }]);

console.group('user fetch');
console.log('start');
console.log('done');
console.groupEnd();

console.time('parse');
JSON.parse(bigString);
console.timeEnd('parse');     // -> 'parse: 12.4ms'


// 2. Write to the DOM (the visible page)
document.body.innerText = 'hello';
document.getElementById('out').textContent = 'safer (no HTML parsing)';
document.getElementById('html').innerHTML  = '<strong>bold</strong> (parses HTML - XSS risk)';

// React/Vue/Svelte handle this for you with reactive bindings


// 3. Alerts (avoid in production - blocks the UI thread)
alert('Are you sure?');
const ok = confirm('Continue?');
const name = prompt('Name?');


// 4. Send output back to the server
await fetch('/api/log', {
  method: 'POST',
  headers: { 'content-type': 'application/json' },
  body: JSON.stringify({ event: 'click', target: 'cta' }),
});


// 5. Use the structured Console API for shipping logs to a tool
// Datadog, Sentry, Logflare etc. all wrap console with breadcrumbs + sampling.
import { init } from '@sentry/browser';
init({ dsn: '...' });

console.error('this is captured with stack trace and tags');


// Tips
// - Strip console.* from production builds (vite plugin, webpack DefinePlugin)
// - Never console.log secrets - leaked into devtools
// - Use textContent over innerHTML unless you intentionally insert markup

Why it matters

console.log is for debugging, not for production behaviour. For visible output use the DOM (or a UI library). For audit trails use a logger that ships to a server. Alerts are forgotten relics for the modern web.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Output!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Print a debug message to the dev tools console.

console. ('hello');

Test yourself

Q1. Best default for debugging is…
Q2. Which method should you AVOID in production?
Q3. Pretty-print rows with…

Discussion

Loading…