As a couple of people have said, this is from Dwitter & you’re missing all the setup code @adt , that’s why it won’t run.
I’d argue it isn’t bad code at all, it’s pretty good, but it’s for an extremely specific purpose (rendering some graphics on an HTML canvas element using 140 or less characters of JavaScript code). It isn’t really JavaScript, it’s a domain-specific language that uses JavaScript as a base.
Again, as others have said, you’d never write code like this (it’s a game that happens to use the JS language as a base) unless you were creating something for Dwitter, that’s its sole purpose. Here is a working version (it’s HTML, just paste it into a file, save the file as html, open it in a browser):
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Dwitter thing</title>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
display: flex;
}
canvas {
max-width: 90%;
max-height: 90vh;
margin: auto;
}
</style>
</head>
<body>
<canvas>Dwitter thing</canvas>
<script>
const canvas = document.querySelector("canvas");
canvas.width = 1920;
canvas.height = 1080;
const context = canvas.getContext("2d");
function toInt(num) {
return num | 0;
}
function rgba(r, g, b, a = 1) {
return `rgba(${toInt(r)}, ${toInt(g)}, ${toInt(b)}, ${a})`;
}
const startTime = +new Date();
function animate(time) {
// I haven't looked in detail at what the maths does,
// so unfortunately all the variables have the same
// one-character names:
for (let i = 0; i < 1e3; i++) {
let r = i / 4;
let k = 2 * time + r / 50;
let X = 960 + 600 * Math.sin(k) + r * Math.cos(i);
let Y = 510 + 250 * Math.sin(k / .5) + r * Math.sin(i);
let w = 19 + r / 5;
context.clearRect(X, Y, w, w);
context.fillRect(X + 4, Y + 4, w - 8, w - 8)
}
}
function loop() {
requestAnimationFrame(loop);
animate((new Date() - startTime) / 1000);
}
loop();
</script>
</body>
</html>
It’s a picture someone has drawn using maths. If you want to do things like it, you can do it via trial-and-error, or [probably necessary for anything complex] need to be able to do some maths. It’s a picture someone has drawn using maths, and it’s a one-off. It isn’t usable outside of that particular dweet. Normal programs aren’t written like this: any that are can reasonably be considered to be coded very badly – normally, programs need to be clear to be useful to the humans who read them, not just the computer that executes them.
Edit: and this post on Reddit is a good explanation for beginners I think: https://www.reddit.com/r/dwitter/comments/7mgcd1/basic_dwitter_guide/