Compressed/Shorthand JavaScript Code

Recently I came across a beautiful dragon animation and was keen to try it out at my end.

The author has provided the following source code:

for(c.width|=p=0;p++<1e3;x.fillRect(X+4,Y+4,w-8,w-8))r=p/4,k=2*t+r/50,x.clearRect(X=960+600*S(k)+r*C(p),Y=510+250*S(k/.5)+r*S(p),w=19+r/5,w)

As advised by him, this is all that is needed.

However, use of this snippet in its present form, as script in skeleton html file results in error related to undefined variables. Unfortunately, the original author is currently out of contact.

I have started learning JavaScript recently and it is the first time that I have come across such a construct for a loop. On searching the web, I have not yet been able to locate suitable explanatory material.

I shall be thankful for any guidance in the matter.

A.D.Tejpal

2 Likes

That is an absolutely terribly written piece of code. You should not use for loops like that, and this code is absurdly obfuscated.

3 Likes

Whoever gave that to you … I agree, it’s terrible. Poorly written, painful to debug, no understandable interface…

My advice, invest the time, learn to code - whether with freecodecamp or another course, learn to make a better version of this.

2 Likes

While all that is true, I suspect that this snippet isn’t meant to be human-readable. It seems like something you’d put into a #140charsOfCode tweet, along with a gif to show what it does.

@adt None of those variables used in the snippet are defined anywhere so there’s clearly something missing.

3 Likes

Yeah, it looks like some absurd golf code thing. I still would replace it with something actually well written.

2 Likes

This is what I call the “cult of concision” - this fetishization of trying to cram as much code into as small an area as possible, thinking it’s some how sexier. I remember seeing code like this back in my C days. I’ve always hated it. Use good variable names and don’t be afraid to expand things for readability. I always imagine that some stranger will have to fix what I’m writing. And that person might be me because I’m probably not going to remember what I was thinking in a few months. Well written code tells a story, it tells you what it does. This code is the opposite.

If I was reviewing a PR and I saw that code, I would reject it without even thinking about it. I wouldn’t even care what it does or if it worked. I can’t imagine any advantage to writing like this, other than being “cool”. Or if you want to obfuscate your code - but there is no reason to do this in your source, there are minifiers and uglifiers for that.

Yeah, I guess I could see doing this competitively, but not irl. I would not let that anywhere near my code. If I needed it, I would rewrite it, giving it good variable names and expanding it out into a “normal” for loop.

2 Likes

It’s funny, I ran into a guy at a meetup that wrote code like this, writing in JS. All variable names were 1 letter, no spacing or indenting, fitting as much one one line as possible. He was convinced that this would make more efficient apps. I tried to explain that not only would no one ever work with him (or he’d better plan on his coworkers slashing his tires daily), but it was completely pointless because minifiers could do this for him. I spent probably 20 minutes trying to convince him that this was a dangerous habit - in the end, he began to see what I was saying, but he was still dubious.

2 Likes

It’s golfed code, deliberately written to be as short as possible. It’s not designed to be readable or good code.

This could either be done for fun. Or it’s to fulfil some specific purpose, eg competitions where the code has to be below a certain size – eg js13k games – or wanting to fit the code into a tweet.

It just uses a series of tricks that abuse certain features of JS so as to shorten the code – see some here or just Google “JavaScript code golf”.

It doesn’t work I think because whatever you’re trying to run it in is trying to do it using strict mode, which will disallow the way the variables are being declared (to reduce size, the author has dropped most of the var keywords – this will work in non-strict mode, but will not in strict)

3 Likes

I certainly get that it looks like code golf. I’m just perplexed why the OP is saying that this was “real world” code.

2 Likes

Oh I’ve seen code exactly like this in production codebases. Largely legacy monoliths where a “senior web dev” ( as though the title existed in 1997) had heard somewhere that code obfuscation made stealing your corporate code harder.

During the browser wars, shoddy code like this was as common as coffee stains on sensitive memos.

2 Likes

Before this gets completely derailed - @adt That code uses the HTML <canvas> element, and draws things on it with JavaScript. There’s a lot on YT about it, here’s a good start:

3 Likes

My sincere thanks to esteemed members (Jeremy, Tobias, jsdisco, Kevin, Dan) - for their kind response.

Your considered views make me feel better as the referred code snippet seemed quite perplexing & out of the blue.

For ready reference, here is the link for the demo referred in my earlier post:

https://www.quora.com/What-are-the-wonders-of-JavaScript

(First demo in first reply – displaying animated dragon)

1 Like

These examples you linked to are all from Dwitter, which appears to be a site dedicated to challenging people to create neat things using no more than 140 characters of JS. So that explains why the code is so terse.

Other than being a challenging/fun exercise for people who like to do such things you would almost never use this type of minimalist coding in the real world, so I would not spend your time trying to figure out what is going on with it.

2 Likes

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/

3 Likes

My grateful thanks Dan. God bless you.

All along, I was curious to know as to what could have been the original normal code, instrumental in bringing up the animation in question.

The sample kindly provided by you now is a valuable illustration enabling examination of real code visa vis dwitter type golphed version. Considering my relative beginning stage for JavaScript, it becomes all the more precious. And – It has given me peace of mind.

I will also study the Reddit article for which you have kindly provided the link (The references provided in your earlier post have also been very helpful).

A.D.Tejpal

1 Like

Thanks to the help kindly provided by Dan Couper at this forum, I have put together an interactive animation demo titled “Dragon Dance”. The link is given below:

http://www.adt28.epizy.com/DragonDance.htm?i=2

Size of the dragon can be altered by clicking anywhere on the screen. Greater the distance of clicked point from centre of screen, larger the dragon size. Accordingly, a click at canvas corner will elicit maximum effect.

Play mode (Single or Multi-Dragons) and animation speed can be altered by clicking relevant buttons at bottom.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.