How to write X in both Python 3 and JavaScript


178 points | by chibicode 221 days ago


  • alyandon 221 days ago

    Sort example doesn't take into account Javascript does lexicographical sorting?


      someList = [ 40, 2, 1, 3, 7, 99]
      Array(6) [ 1, 2, 3, 40, 7, 99 ]

      someList = [ 40, 2, 1, 3, 7, 99]
      [1, 2, 3, 7, 40, 99]
    • slx26 221 days ago

      Your comment led me to discover and reaffirm myself that I should stay away from javascript for as long as I can

      • 52-6F-62 221 days ago

        It depends on whether or not you pass it a basic comparator function, eg:

            someArray.sort((a,b) => a - b);
        But yeah the example would have needed this for the less complex example as well to be accurate.
        • Too 221 days ago

          Common mistake when writing a sorting function, a-b is not safe in languages with integer overflow because it will give you incorrect sorting for large numbers. In javascript where everything is double you're probably safe from that kind of error but maybe NaN can give you problems instead?

          • 52-6F-62 220 days ago

            Too true.

            ‘a-b’ is safe enough in JS if you always know the input will be within a safe range regarding integer sizes and types.

            NaN can give you all kinds of trouble so I’d usually test for that in a real case, either before the sort or in the comparator—if necessary.

          • orf 221 days ago

            Shouldn't that be `a < b`?

            • Ajedi32 221 days ago

              No, the compare function needs to be able to indicate when two values are equal, not just when one is smaller/larger than the other. Otherwise your sort function will return inconsistent results for compare(a, b) and compare(b, a) when both values are equal.

              • kristianp 221 days ago


                    someList.sort((a,b) => a => b)
                Would be better, because it produces a stable sort?

                `a - b` produces the same results, so equally valid?

                • jwilk 221 days ago

                  (I'm assuming you meant "a >= b", not "a => b".)

                  That's still not a consistent comparison function, so the results are implementation-defined.

                  To be consistent, it's required, among others, that if cmp(a, b) == 0 then cmp(b, a) == 0. For "a >= b", this is not always true, e.g.:

                    » cmp(0, 1) == 0
                    » cmp(1, 0) == 0
                  • Ajedi32 221 days ago

                    No. `(a,b) => a => b` cannot produce a stable sort in all scenarios. Would theoretically work fine for integers since there's no difference between any two instances of the same number, but consider:

                      let arr = [
                        {number: 2, name: 'a'},
                        {number: 1, name: 'b'},
                        {number: 1, name: 'c'},
                    Now assume we want to sort arr with a compare function, and our sort function expects the compare function to return a boolean, not an integer.

                        let compare = (a,b) => a.number => b.number
                        compare(arr[0], arr[1]) //=> true, so the object named 'a' comes after 'b'
                        compare(arr[1], arr[2]) //=> true, so the object named 'b' comes after 'c'?
                    See the problem?
                • 52-6F-62 221 days ago

                  That will give you a sequence of decreasing numbers. `a-b` will work just as `a > b`.

                  If `a-b` returns a negative number, the result will be treated as -1. If the numbers are the same, then you end up with 0, and so on.

                  I don't know what's faster in that case.

                  • jwilk 221 days ago

                    a > b is not a consistent comparison function. The behavior of sort() with such a function is implementation-defined.

                    • 52-6F-62 221 days ago

                      Agreed. I wouldn't use it the way shown here. I would make sure to return a hard negative, zero, or one in any case.

                      I was surprised when I read into how many different ways `Array.prototype.sort()` is implemented across environments.

              • kbd 221 days ago

                Oh gosh. TIL.

                Edit: I'm actually truly grateful, I'm sure this bit of knowledge saved me some of my hair in the future.

                • combatentropy 221 days ago

                  To me this seems like a bug, or at best an incomplete implementation. Let's fix it in the next version of JavaScript, okay? I suppose someone's code will break, but was it worth preserving?

                  • fogetti 221 days ago

                    That's a good point. Although there is another sorting example which is using the correct format. But yes, you are indeed right.

                    • FridgeSeal 221 days ago

                      I swear this language gets worse every time I learn something new about it.

                    • ChrisSD 221 days ago

                      As someone who is often switching languages, I find these sorts of cheatsheets useful.

                      I know all the syntax in them but I'll be damned if I can ever remember which language uses which until I've settled back in to things.

                      • derimagia 221 days ago

                        My go-to site is usually

                        • chooseaname 221 days ago

                          Me too. On any given day, I can be using any of a half dozen languages (C#, powershell, javascript, bash, perl, python, c++, java - our codebase is all over the place). It gets hard to keep the syntax straight on all of them.

                          • abstractbeliefs 221 days ago

                            You might find Rosetta Code to be useful - it's a wiki site with hundreds of examples, all with solutions in dozens of languages for comparison.

                            ikewise, I felt a little let down. On the flipside, it's an excellent opportunity to bring Rosetta Code to people's attention - a wiki with hundreds of example problems, each solved in many languages for comparison!


                            I find it invaluable in that sort of mid-learning level of a new language, where I have the syntax sorted, but I need lots of programs small enough to hold in my head, but also large enough to show off all the features, to learn and read. Here's Dijkstra, for example:

                          • aninteger 221 days ago

                            How to write using X in both languages:



                            • donio 221 days ago

                              A couple more native X11 client implementations:

                              Common Lisp:


                              Any others?

                              (Looking for implementations of the X11 protocol in $LANGUAGE, not bindings to the C Xlib)

                            • de_Selby 221 days ago

                              This is what I actually thought the article was going to be about!

                              • 52-6F-62 221 days ago

                                Haha, I also expected this.

                                Now I'm kind of glad you responded in kind because I'd seen python-xlib but not the node one. That sounds like a bit of fun and punishment at the same time.

                                • bateller 221 days ago

                                  At least I wasn't the only one lol

                                • ISL 221 days ago

                                  This what I expected from the title.

                                • marsrover 221 days ago

                                  When I read the headline I was expecting the X windowing system. When I clicked the article and saw “junior programmer” I thought this is about to be impressive.

                                  Cool site :P

                                  • fabiomaia 221 days ago

                                    Very cool! Reminds me of

                                    I particularly enjoyed seeing that you used snake case in Python and camel case in JavaScript. Great attention to detail.

                                    • sayazamurai 221 days ago

                                      Creator here! Let me know if you have any suggestions.

                                      • floatrock 221 days ago


                                        Although this is a case where idiomatic python is different from idiomatic js.

                                        In js:

                                          // same:
                                          !! ""   // false
                                          !! 0    // false
                                          !! 1    // true
                                          !! null // false  
                                          // different:
                                          !! {}  // true
                                          !! []  // true
                                        while in python:

                                          # same:
                                          not not ""    # False
                                          not not 0     # False
                                          not not 1     # True
                                          not not None  # False
                                          # different:
                                          not not {}       # False
                                          not not []       # False
                                          not not tuple()  # False
                                        • mschuetz 221 days ago

                                          Nice list.

                                          Perhabs just personal preference but I'd use

                                              for(let element of someList){
                                          instead of

                                              someList.forEach(element => {
                                          for...of is easier to read and recognize as a loop construct at first glance, and as far as I recall it's also faster nowadays since the body of the loop is inline, whereas forEach requires the runtime to deal with a function object.
                                          • tuesdayrain 221 days ago

                                            Personally I find the method-style syntax significantly more readable.

                                            • jsh7 221 days ago

                                              You can also ‘return’ the outer function from within a ‘for...of’ which is pretty useful imo.

                                              • andyfleming 221 days ago

                                                And you can use await in the context of an outer async function, which is a huge advantage in reducing code complexity.

                                              • tormeh 221 days ago

                                                Makes me wonder if maybe the syntax for mapping, folding and other collection operations should have a similar syntax to for instead of the current method-style syntax popular in most modern languages.

                                                • symlinkk 221 days ago

                                                  C# has a syntax called Linq Query Syntax that provides keywords in the language to do things like map, filter, and reduce.


                                                    var queryLondonCustomers = from cust in customers
                                                                               where cust.City == "London"
                                                                               select cust;
                                                  I'm not a big fan of it honestly, the function style seems more consistent and easier to read to me.
                                                  • hnlauncher 221 days ago

                                           does it like this:

                                                      for each(str from [list: "Ahoy", "world!"]):
                                                      for map(n from [list: 1,2,3]): n * n end
                                                      # ==> [list: 1, 4, 9]
                                                      for filter(n from [list: 1, 2, 3]):
                                                        n >= 2
                                                      # ==> [list: 2, 3]
                                                      for fold(sum from 0, n from [list: 4, 5, 6]):
                                                        sum + n
                                                      # ==> 15
                                                    • saghm 221 days ago

                                                      That sounds a lot like Python list comprehensions

                                                  • laumars 221 days ago

                                                    I genuinely love the design of the page. It has personality without compromising readability. This is something a lot of people struggle to get right.

                                                    • andyfleming 221 days ago

                                                      Instead of...

                                                          Object.entries(newDict).forEach(element => {
                                                            console.log(`${element[0]} ${element[1]}`)
                                                      ... you could write ...

                                                          for (const key in newDict) {
                                                            console.log(`${key} ${newDict[key]}`)
                                                      ... or ...

                                                          for (const [key, value] of Object.entries(newDict)) {
                                                            console.log(`${key} ${value}`)
                                                      • settler4 221 days ago

                                                        It would be nice to have a sectioin with things that work differently in both languages. For example in python `if []:` evaluates to False while in javascript `if ([]) {` evaluates to True.

                                                        • armandososa 221 days ago

                                                          First: congratulations, this is very well done.

                                                          Second: I don't like seeing JavaScript code without semicolons. Maybe I am old, but it makes me nervous.

                                                          • FlyingLawnmower 221 days ago

                                                            Thanks for the site! Do you have thoughts on removing all the print/console.logs calls on every line? It feels like there's a lot of visual noise there, that can still be met with the comments showing state/output.

                                                            • plopz 221 days ago

                                                              I might suggest replacing javascript's parseInt() with Number()

                                                              • Sir_Cmpwn 221 days ago

                                                                Consider renaming to "How to write $X in both Python 3 and JavaScript" to avoid the confusion with X11 that others have pointed out? Nice article!

                                                                • fogetti 221 days ago

                                                                  I really like the page. I really enjoyed going through the list. One suggestion would be to add python/javascript generator functions to the list.

                                                                  • sharemywin 221 days ago

                                                                    Very cool reference.

                                                                    • zitterbewegung 221 days ago

                                                                      Add Python 2 and or another language that has a static type system like C.

                                                                      • laumars 221 days ago

                                                                        I think anyone who hasn't learned to do X in Python already really should be better off learning it in Python 3 rather than a version of the language which is in the process of deprecation.

                                                                        • nanna 221 days ago

                                                                          Either you forgot to mention that this is a personal todo, or you're trolling the author?

                                                                      • mvilim 221 days ago

                                                               is a great website with a similar idea.

                                                                      • ramses0 221 days ago
                                                                      • thomasfedb 221 days ago

                                                                        A weird reference imo. Perhaps useful to build as a learning experience but I wouldn't expect who needs if/else included in a cheat sheet to be ready to learn to languages.

                                                                        • fabiomaia 221 days ago

                                                                          The value is in finding what is the most idiomatic way to do something in either language. For example if you're coming from Python and you're used to sum() it is useful to check this reference for the most idiomatic way to do it in JavaScript before doing it by hand with anonymous functions and reduce or looping through the list (as is the case unfortunately).

                                                                          • LyndsySimon 221 days ago

                                                                            Agreed. The value isn’t in it being a tutorial, it’s in it being a quick overview of a language’s idioms as they apply to common tasks.

                                                                        • dkonieczek 221 days ago

                                                                          Do people actually use cheat sheets like this? IMO, the first stackoverflow result in google is generally what I'm looking for and quicker - especially for common things and common languages such as the things on this page. Even if you have the page bookmarked, you still need to find/search/scroll for the specific thing you're looking for. Also, with Alfred you can google anything even quicker by not having to cmd+tab to the browser.

                                                                          • cirgue 221 days ago

                                                                            Maybe not as a reference, but it's certainly helpful to browse if you're going from one language to another (I know python and I'm learning Javascript, this probably saved me a few google searches)

                                                                            • andyfleming 221 days ago

                                                                              In the past I've enjoyed using cheatsheets to get a quick feel for the syntax of a language. It's nice to see a less familiar language next to a more familiar one.

                                                                              • jamesgeck0 221 days ago

                                                                                I used a resource similar to this to get started with Javascript almost a decade ago. Reading through the examples start to finish is a decent intro to the basics.

                                                                              • feniv 221 days ago

                                                                                Reminds me of this OneLang HN post from several months ago -

                                                                                It's an IDE that lets you code simultaneously in several different languages

                                                                                • tobiasz-cudnik 221 days ago

                                                                                  Reminds me of PLEAC - Perl Cookbook translated to >10 langs

                                                                                  • nayuki 221 days ago

                                                                                    When I publish code about algorithms and data structures to my web site, I usually offer multiple language versions. Why? Because understanding the computer science theory and math proofs is a big effort. Writing and debugging my first implementation in any language is a big effort. But porting that code to a bunch of languages is comparatively easy and is almost a thoughtless mechanical process.

                                                                                    • basilgohar 221 days ago

                                                                                      I thought this was going to be a polyglot[1] demonstration of writing code for X Windows. However, I was not disappointed in what I found!


                                                                                      • anticensor 221 days ago

                                                                                        I expected a Python/JS polyglot :)

                                                                                        • 221 days ago
                                                                                        • Too 221 days ago

                                                                                          Impressive to see almost all JS examples being as short as the python ones. Python is normally valued for being short and concise but modern JS is really catching up here.

                                                                                          • aavotins 221 days ago

                                                                                            I had such high hopes when I opened the arsenal. I anticipated it would an article of how to write code that's both JavaScript and Python syntactically correct.

                                                                                            • another-cuppa 221 days ago

                                                                                              What's the point of having print or console.log around everything? Just have one box with "print to standard output" and those two at the top.

                                                                                              • sheikheddy 221 days ago

                                                                                                I love it! Reminds me of

                                                                                                • ingen0s 221 days ago

                                                                                                  Excellent educational tool - will be passing this around to colleagues who need it. Thanks!

                                                                                                  • 221 days ago
                                                                                                    • nanna 221 days ago

                                                                                                      Same here!

                                                                                                    • undershirt 221 days ago

                                                                                                      this is very good. i had it in my head that there was no "extend" function in JS, and didn't realize "push(...array)" was possible. thank you for the super detailed guide

                                                                                                      • 221 days ago
                                                                                                        • tracker1 221 days ago

                                                                                                          FizzBuzz example isn't correct

                                                                                                          • 221 days ago
                                                                                                            • analpaper 221 days ago

                                                                                                              but but no need to write both, just one and compile the other (,, etc..)

                                                                                                              • enitihas 221 days ago

                                                                                                                I was expecting to see a leftpad comparison too :D