40 ms·
JavaScript Is Weird
- the_duke 5y agoBuggy in Firefox (89): gets stuck on the second question. Works fine in Chrome.
- krylon 5y agoIt worked fine for me (Firefox 89 on openSuse Tumbleweed). Maybe some add-on is interfering?
- jmrm 5y agoWorks well on Firefox 89.0.2 on Windows 10 :-/
- kiwijamo 5y agoWorks fine in Firefox on Android.
- tgv 5y agoHere too (89.0.2, macOS).
- mikkelam 5y agoSame for me in macOS with firefox 89. Disabled all addons and same problem.
- nodejs_rulez_1 5y ago> JavaScript is a great programming language, but ... Why are we so afraid to call trash "trash"? It's not attacking the creator, but just how can we make progress if things are not perceived as they are? https://wtfjs.com https://wtfjs.com
- deleted 5y ago[deleted]
- deleted 5y ago[deleted]
- globular-toast 5y agoI thought the same thing. I think the author is afraid of offending people. Downvote culture has conditioned a lot of people to walk on eggshells and write this way.
- n4bz0r 5y agoFunny how this comment got downvoted into Valhalla in a matter of minutes.
- cout 5y agoTrash is something you are discarding. If you are keeping it because it still has some utility to you, then it is by definition not trash.
- cies 5y agoLoved this video (4mins) of a talk by Gary Bernhardt (CodeMash 2012) on the topic of JS' quirks: https://www.destroyallsoftware.com/talks/wat https://www.destroyallsoftware.com/talks/wat
- azangru 5y agoIs javascript any more "trash" than python or ruby? I don't think so.
- blowski 5y agoFrom what I read on forums, every single piece of technology that's ever been invented is trash according to some self-appointed expert. I doubt I could name a programming language used by more than 100 people about which at least one person hasn't written a crtical comment.
- kingludite 5y agoElixir? I've never used it but reading about it I kept going ohh, ahhh and wow! In stead of my standard: ** ** *k * ** *sh?!?
- blowski 5y agohttps://news.ycombinator.com/item?id=25787548 https://news.ycombinator.com/item?id=25787548 I've never used Elixir so can't say whether the criticisms are justified.
- hootbootscoot 5y agoPresuming server-side JS, as you won't run Ruby or Python in the browser, typically, you can say that all 3 dynamic languages, as such (garbage collected, heap-based, untyped) will waste computer resources and perform worse than typed compiled languages (even garbage-collected ones) due to memory usage patterns. Python has an interesting C FFI interface, among other approaches, that can at least allow CPU and memory-bound tasks to be accomplished inside of a native code module. You see a lot of domain specific work in Python due to these approaches, cython, etc.. Crystal lang is what I would urge all Ruby devs to look at. (an LLVM-based compiled language that has HTTP in it's standard library, for one thing...I'd pit it against Go, for example.) As I see large front-end teams frequently pushing JS from a typescript base lately, I'm not sure that even the JS community supports "everything JS" anymore. At the point one does backend Node.js work with typescript or other more rigidly typed systems, I have to wonder if targeting V8 is really the desired option any more, and if the programmer would not be better off switching to a high-performance and feature-complete typed backend language system. (the single-threaded JS execution model being a needless constraint at this point, for example. It's great as an event loop)
- nicoburns 5y agoThe vast majority of these are implicit type coercion issues. Which is fairly easily banned with a linter. Once you've done that, I think JavaScript is probably the nicest of the big dynamic scripting languages (Perl, PHP, Python, Ruby) to work with. There could definitely be improvements, but trash seems to be taking things too far.
- pansa2 5y ago> I think JavaScript is probably the nicest of the big dynamic scripting languages (Perl, PHP, Python, Ruby) to work with. As an experienced Python programmer learning JavaScript, this isn’t true for me yet but I hope it becomes true. I think JS will be much more useful to me than Python. > Which is fairly easily banned with a linter. Any particular recommendations?
- furstenheim 5y agoEslint is the default linter. Standard is a curated list of rules with good quality. https://github.com/standard/eslint-config-standard https://github.com/standard/eslint-config-standard I would start with that and tweak what you don't like
- dfabulich 5y ago> Any particular recommendations? TypeScript.
- ehnto 5y agoThe article only really touches on weird language caveats, but where JS really gets weird is it's ecosystem. If you are working with JS in a commercial capacity you will eventually find dependency hell, arbitrary toolchain complexity, asynchronous and callback mind bending, transpiling and compilation, and all just to render some HTML. Quick, get your compsci degree bobby, we need to make this button go to another page!
- ljm 5y agoWhy is it trash? Or is this just like PHP where people are so accustomed to shitting on something that they're completely oblivious to the progress that's actually been made? I don't understand what this actually contributes to the discussion beyond it being a tired, beaten-down programming meme.
- hootbootscoot 5y agoIt is 'trash' for the general purpose 'one-size-fits-all' programming language that it's fans want to impose upon the world. (I shake my head at microcontrollers running dynamic languages. "micro-python" = spare me. line breaks over a TTY? there's the primary question of on-chip resources and a giant shim between the physical realities of a microcontroller and some high-level fantasies about what programming "should be", absent any information on the low level specifics = the issue here.) It's ES3 API is missing a few things, like Object.keys, etc. I still happily code for browsers in ES5 with a few polyfill functions. JS works fine for it's core competency: manipulating DOM elements and local data representations. It's not JS's fault that the browser is the way it is and that HTTP is the way it is and that using a remote directory "browsing" protocol via a specialized file browser that renders hypertext isn't a 2-way bound GUI framework...
- jiofih 5y agoThat’s a load of gibberish. JS as a language has nothing to do with browser APIs, why would you judge it based on that? Also, ES6 was ratified six years ago. Seems like you had a bad experience with espruino / jerryscript or something and are projecting based on that? Dynamic languages are easier to program in. That’s a fact, and why they are so popular.
- golergka 5y agoAlthough I like Javascript (Typescript) a lot, I have to bite: > Dynamic languages are easier to program in. Only if you don't care about writing correct and maintainable programs. The only thing that dynamic languages make easier is writing code. Or, more specifically, the first couple of versions of it. That's not what typical programming as a process mostly consists of.
- jraph 5y agoWe are not saying this because we are afraid to say it, but because it is not true. JS is a great programming language with a lot of quirks and footguns, most of them easily avoidable by enforcing good coding styles, using easily available and widespread tooling. And most language have linters or compilers that issue coding-style related warnings, including C, so this is not specific to Javascript.
- tasuki 5y agoWhy is JS a great programming language?
- jraph 5y agoThere are a lot of things to hate about JS: its questionable choices around type coercion, its Date object, for..in on arrays (indices are string) (a consequence of every object key is a string), for..in on objects which also iterate on inherited properties, the fact everything is dynamic, its weak standard library, null vs undefined, many original things…. There are also great things about it: the ease at which one can write in a functional style code, anonymous functions (vs Python), closures (vs Java), immutable strings, the fact that there is not a shitload of classes to instantiate to achieve anything (vs Java), block-scoped variable definitions, sane default function parameter handling (vs Python). Javascript engines are also very fast nowadays because of the ton of engineering going into them. I'd say, above all arguments, you can rapidly build very fast, lightweight and program programs with it. Sure, you can pull a shitload of pointless dependencies and write bloatware that re-render the world on each keypress, and that's what many people do. And to make things worse, they wrap their shit with an entire browser that uses a lot of ram and processing power. But you are not forced to do that. You can also write efficient server code that does not show up in top, has few dependencies if at all, consume a negligible amount of memory and run without failure for months. That's possible too. Frontend-wise, you have amazing frameworks like Svelte that do wonders and would allow you to build very lightweight apps rapidly. That said I would often pick TypeScript so your program is statically type-checked and your code is documented through types, especially for more-than-one-person / non-trivial projects. I also use and like other languages like Python and D (and a bit of Rust) that have good stuff which JS doesn't have (list comprehension, borrowing, traits, named parameter, sane coercion to False…), or bad stuff which JS has. Javascript is not always the best answer, or even a good answers, but it can be one.
- dfabulich 5y agoCalling it "trash" is a very inflammatory way to describe one the most popular programming languages in the world. Language like that is against the HN guidelines, because it distracts from your argument to debate about whether JS is "trash" or not. JavaScript has a bunch of quirks, but it's still great. In the StackOverflow survey, JS reliably ranks highly in the list of "most loved" languages. https://insights.stackoverflow.com/survey/2020#technology-most-loved-dreaded-and-wanted-languages-loved https://insights.stackoverflow.com/survey/2020#technology-mo... Node.js is a thing because people liked JS so much that they wanted to use it on the server side. You may think they're all fools, but it's actually pretty nice. I like the latest version of Node better than working in Python (mostly because node_modules are better than virtualenvs, IMO.) You can use TypeScript to address many of the quirks described in TFA, but you can also reliably avoid them just by never using == and always preferring ===, using String() before using + to concatenate, and using Number() before subtracting. I basically never encounter situations like the ones depicted in TFA in real code, because I never try to add two arrays or subtract two strings or what have you.
- wruza 5y agoTrash “Admitting like this has a bunch of quirks, but it’s still great.” (not arguing for it though) Criticism is a driving force behind change to the better. Calling something “great” without pointing out great sides I find… pointless and harmful. To name a few great points, distinct from other languages: JS has a pretty shameless object model, where you (usually) have ordered keys, and every key is a property with an {enumerable, writable, configurable, get, set} descriptor. It is much more usable and practical than in almost all other languages. (They do that for “efficiency”, but that’s non-sequitur) JS has very useful destructuring syntax, which many languages lack of and that leads to assignment bloating and boredom. Also, jit optimizes out temporary objects, so foo({x, y}) / function foo({x, y}) works almost at the same speed as foo(x, y). JS has a nice Function type, which allows easier metaprogramming and substitution of ‘this’ object. Functions are objects, so you can function foo() {}; foo.x = 1; console.log(foo.name, foo.x). JS bare objects may have methods and properties: t={_x:1, get_x(){return this._x}, …} JS doesn’t treat syntactic lists in a last-value-only way, so you can expect foo(…a, …b, c) to work, and to work as intended. E.g. Lua cannot do that, and python (afair) requires you to collect items into a single array (not sure, correct me if I’m wrong). But what people usually mean by “great” is “it generally works”. I know it is an american thing, but some aspects of js, including those you meet everyday, are really just trashy. It would be nice to not have them at all.
- MaxBarraclough 5y agoI wouldn't say it's trash. JavaScript has many ugly quirks, but it has many good facets too, and it can be be used to write effective and fairly elegant code. Considering how quickly it was thrown together, and that's it's been evolving since then, I'd say it's a surprisingly good language. > how can we make progress if things are not perceived as they are? People aren't blind to JavaScript's failings. The evolution of JavaScript has been a mix of adding new features and fixing what they got wrong before, e.g. the way it has two different isNaN functions. [0] [0] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- lampe3 5y agothe only trash is that comment LooL
- LandR 5y agoBecause some developers will take offense. They will think that if you call the language they use trash then you are calling them a trash developer. It's odd, there are developers who make the language they work part of their identity and see attacks on that language as attacks on their identity. I don't get it, but it is what it is. If you call javascript trash, you will offend people.
- sesm 5y agoIf we want to perceive JS as it is we need to follow its history, understand the basic ideas behind different features of the language, understand the trade-offs behind various design decisions, etc. Basically, it was meant to be a dialect of Scheme, but with map and array data structures at the bottom, as opposed to lists (hello, Clojure!). Suddenly, the last-minute decision was made to add Java-like syntax and OOP to this language and rebrand it as 'JavaScript'. Brendan Eich did the best he could in the limited timeframe to implement this. Then in 2015 'design-by-committee' approach was accepted and horrible feature creep started. We can then investigate every feature and how it pushed individual company's agendas while compromising the integrity and vision of the language, but that's a typical design-by-committee story.
- lkj23ioj233i 5y agobecause people here wasted years to learn all the quirks in JS and now they should realize all that was a mistake? Much better to downvote negative comments.
- krylon 5y agoThe questions covering floating point are not really weird, or rather their weirdness is not specific to Javascript. It's a fun quiz nevertheless, at least for someone like me who is not very proficient in Javascript.
- ZoomZoomZoom 5y agoEspecially weird was that the quiz stuck at question 2 and kept resizing and shifting the position of the question text on selecting any answer until the quiz ended. CSS in the console is a nice touch though.
- dgb23 5y ago> CSS in the console is a nice touch though. Ty for bringing it to attention. Indeed a cool feature to create emphasis and structure. Haven't bothered with it yet but will consider it. Another cool one is using console.groupCollapsed (as long as you are staying in a callback context).
- southerntofu 5y agoI got stuck at question one like this. Running Tor Browser latest version, tried in all security modes. First time i ever see a form behave like that oO
- imalerba 5y agoIt doesnt work for me in Firefox at all.
- masklinn 5y agoThe awful letterspacing makes it very hard to know whether strings are empty or single spaces. (They’re all empty strings).
- jeltz 5y agoYeah, got a couple of questions wrong due to that.
- vorticalbox 5y agoif you block JS you get this message > This website is literally about JavaScript. I mean what did you expect, a .NET application? This website is 99.9% poorly optimized and highly questionable JS. And yet, you have JS turned off.
- franciscop 5y agoIf you open the console to check after you're finished, it says: "What, are you going to check if the results are accurate? Go ahead " But if you open it console while doing the test, it says: "Hey, stop cheating! "
- amelius 5y agoWhy the hell can websites tell that I'm in the console? If I want to inspect some parts of a website (perhaps save an image), then I don't want that website to interfere.
- woutr_be 5y agoThey don’t. They just use “console.log”, you see it because you opened the console. It’s not like they know you’re there and then write a message.
- hmsimha 5y agoDevtools can actually be detected to a certain extent - https://github.com/sindresorhus/devtools-detect https://github.com/sindresorhus/devtools-detect
- amelius 5y agoThis entire project should be copied verbatim into browser bug trackers, imho.
- pityJuke 5y ago> Doesn't work if DevTools is undocked and will show false positive if you toggle any kind of sidebar. This annoys me every time because I use Tree Style Tab, and a website tries to detect DevTools. See Samy Kamkar's website [0]. [0]: https://samy.pl/ https://samy.pl/
- dgb23 5y agoI use JS since almost a decade and only got half of them right. Specifically I failed at the last one because I got impatient, the octal one got me too (never use those in JS), the true++ and the ones that require you to know that arrays are converted to strings when used in arithmetic. I'll just externalize my embarrassment and say that JS is indeed weird! Another excuse is that I typically try to avoid implicit type conversion except for idiomatic "tricks" such as using !! to convert to a boolean. Cool website though!
- woutr_be 5y agoI have been using JS for almost 10 years, and have written quite a few big apps with it, both front- and back-end, but only a handful of times have I experienced this “weird” issues. Nobody writes code like that, I only know of these things because there have been many websites like this over the years.
- GlennS 5y agoI guess this is why people seem to like Typescript so much.
- onion2k 5y ago0.2 + 0.1 === 0.3 That's not really a JS problem, that's a floating point problem. Plenty of languages will have the same issue. +!![] "" - - "" (null - 0) + "0" Calling these things weird is fair enough but I can't help thinking this is code you'd never actually write outside of the context of a "Look how weird JS is!" post. It's like picking examples from the Annual Obfuscated C Contest to show how hard it is to understand C. Yes, some languages enable you to write weird garbage code that's hard to reason about, and ideally they wouldn't because enforcing sane code would be great, but come on. Most of these things aren't a big problem that we suffer every day. Just be moderately careful about casting things from one data type to another and all these problems go away.
- bruce343434 5y agoYup, garbage in garbage out. I'm not a huge fan of JS, but this sort of criticism is absurd.
- wdroz 5y agoI rather have the language say "Error, this is garbage!" than silently output garbage.
- madeofpalk 5y agoWhich is why we use Typescript
- AnIdiotOnTheNet 5y agoThe fact that there has to be a different language on top of your language to make it same days all that needs saying really.
- lotsofcows 5y agoI keep having this argument with my boss but he refuses to let me write machine code.
- GlennS 5y agoThis covers most of the weirdness with primitive types, but then we have an oddly designed OO system on top of that: prototypes + `this` and constructors + classes bolted on.
- sesm 5y agoIt may seem odd, but it got clear to me once I understood the basic idea. In a language like Java you have objects and classes at the bottom of the language. How would you add maps to the language? Well, you create a Map class, implement put, get, has methods, etc. Now imagine a language where you have functions and maps as your basic primitives, but you don't have classes and objects. How do you add objects and classes to the language? You can do something like this: objects are maps, information about their basic class is saved in 'prototype' property, constructor is a function that returns an object, etc. That's how JavaScript works. You can read about this in more details here https://exploringjs.com/impatient-js/ch_proto-chains-classes.html https://exploringjs.com/impatient-js/ch_proto-chains-classes... , if you keep the basic idea in mind the details are easy to follow.
- dna_polymerase 5y ago> JavaScript is a great programming language I have no idea how you could come up with this sentence after this brilliant display of what an insanely stupid language JavaScript is.
- krylon 5y agoTo be fair, just because a language allows you to do stupid things, doesn't mean that it's bad. C, C++, Perl (oh, Perl!) allow you to do weird things, too, so do lots and lots of other languages. A certain knowledge of this weirdness is very helpful, though, in avoiding it.
- dolmen 5y agoIn fact Perl 5 has less weird coercion rules than JavaScript.
- ecmascript 5y agoYes Javascript is weird but at the same time you almost never face many of these issues in the real world. Bad things exist in all languages, for some maybe there isn't the same in the sense of actual quirks in the language but rather other things that limit the language in some way. I have been a web dev for about 10 years now and I rarely if ever run into these issues. More likely, I face issues and bugs regarding state and just flaws in the logic rather than issues based on that the language wasn't designed so great. For sure this can be worrying if you do something really important but at the same time you have a lot of other languages to choose from.
- davidkunz 5y agoNobody programs like that, so it's not an issue in real-world applications.
- qayxc 5y agoI would agree if wasn't for the fact that JS is a dynamically typed language. You can (and sometimes will) run into instances of this without noticing, because while you won't explicitly write true++ you might do something like x = someFunction() x++ not realising that someFunction() might return a boolean under some circumstances. Anyone who worked with a sufficiently large JS codebase ran into one of these cases and got unexpected results at some point due to this.
- wruza 5y agotrue++ and x++ are syntactically different though. The latter is a post-increment of an identifier, and the former is a post-increment of a boolean literal. Different rules may apply to these cases.
- davidkunz 5y agoThis is true, one must always make sure to handle all possible return types, but that's true for all dynamic languages.
- noisem4ker 5y agoNobody uses straight edge razors for juggling, so they're not dangerous when shaving.
- usagitoneko97 5y agoI have limited knowledge in web development and its history, but why is javascript a first class language in web dev when all I heard is "javascript bad"? Web assembly seems like a much better choice in hindsight where you can choose different language to compile down to wasm.
- lol768 5y agoWASM support hasn't been around for long, comparatively - and I'm not sure if there's been any recent headway with DOM manipulation or GC from WebAssembly.
- Santosh83 5y agoWebassembly is too recent. It needs to catch on. The momentum behind Javascript/Node is huge beyond comprehension. The engineering that has been poured into the JIT is also quite something. Just scrapping all of this and starting again with Wasm is not going to get traction from anyone.
- BenFrantzDale 5y agoCan you explain “Javascript/Node”? I thought Node.js was a JS interpreter but not the interpreter used in the major web browsers. Rather, that Node is an interpreter that’s used to run Js in (typically) headless (server) environments, allowing both sides to be written in JS. Is that accurate?
- madeofpalk 5y ago> Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine.
- jraph 5y agoWASM is not a good solution in a lot of situations. In short: - you have to package your complete runtime in the Wasm binary, this leads to a large binary and memory footprint - DOM manipulation requires calling Javascript code, and calling JS from WASM is costly
- superasn 5y agoI think a lot of these errors can be fixed with using strict types, aka Typescript. I've had the same issues with PHP in the past too, which makes me believe that whosoever created these languages had ease of use as a higher priority than strictness, i.e. it's okay to assign bool, int, string to the same variable.. just get the job done.. okay. On the other end of the spectrum is a programming language like Pascal (or object Pascal which I used for some time) where I had to write so much boiler-plate code that it made a simple job difficult. Maybe good for big projects but checking if email is valid before form submission, it may be too much boiler-plate code for some people with such traditional languages.
- jmkni 5y agoI had a similar feeling recently using Swift for a project. Pure JavaScript is definitely a bit too loose for my liking, but I thought Swift went a bit too far in the other direction.
- Aaargh20318 5y agoI had that experience with Swift for maybe the first 2 days I used it. Nowadays I really appreciate Swift’s strictness. It just helps prevent so many stupid mistakes. I worked on a high-profile project for my company under a strict deadline and Swift was a major part in ensuring we delivered a rock-solid implementation in record time.
- kalleboo 5y agoThe only part of the type system that I feel gets tedious is dealing with numbers, where you're continually casting back and forth between Int, Float, Double, CGFloat (at least the latter is being addressed). I get why it's strict about it due to loss of precision and the madness of floating-point numbers, but sometimes you just don't care
- Aaargh20318 5y agoThe number things isn't that big of an issue once you get used to considering what type your numbers should be in advance, instead of going back and forth between number types, pick one that's appropriate and stick to it.
- Tade0 5y agoFortunately nowadays including any of those in your code would award you the review equivalent of bashing your head in. With the advent of linters most of these patterns started being rightfully considered bad form by default. Currently even innocent stuff like +new Date() (outputs a timestamp) is already something that I've rarely seen make it through review. JS is goofy, but ES2015 managed to avoid making the same mistakes. Shame it took so long to implement it. At the moment the bigger problem is the painful transition from whatever module system you had to ES Modules. Especially browser<->Node.js interoperability suffered massively from this. Hopefully there will be no further standards in this field.
- phist_mcgee 5y agoI am eternally surprised at how long it took node to support ESM. CommonJS modules served their purpose, but they are about to go the way of JS module systems. This is where the appeal of deno comes in. It's a runtime that tries very, very hard to give you the same API surface as that of the browser. I just hope deno catches on faster.
- Tade0 5y agoI consider Deno to be DOA - hopefully I'm wrong. The scope was just too broad.
- MaXtreeM 5y agoBased on the comments half of the people didn't read the introduction.
- gherkinnn 5y agoThese examples are amusing but irrelevant. What I find sorely lacking is sane syntax for working with arrays. Eyeing Python with envy every time. And some pattern matching would be nice too.
- Joeri 5y agoBoth are stage 1 proposals that I hope get in there some day. https://github.com/tc39/proposal-slice-notation https://github.com/tc39/proposal-slice-notation https://github.com/tc39/proposal-pattern-matching https://github.com/tc39/proposal-pattern-matching
- DarkWiiPlayer 5y agoSpecial syntax for specific data structures are exactly why I hate so many languages. No. We don't need more of that garbage. Map & co. do everything you need and adding yet another syntactic construct on top of it would just break the language even more.
- jonplackett 5y agoI did incredibly badly. JS really is weird.
- have_faith 5y agoYou're weird if you write code like this.
- qayxc 5y agoThe sad part is that you don't have to and still encounter one of these cases. The reason is that JS is dynamically typed and thus functions are free to return multiple result types. So you might run into one of these and get unexpected results because at some point in your code one of the functions returned an empty array instead of a number or a boolean, or divided by zero, or... It's good to at least be aware of these edge cases so you can avoid them.
- ksec 5y agoPeople may want to watch "Wat" [1] from 2012 ( for a laugh ) before doing this quiz. [1] https://www.destroyallsoftware.com/talks/wat https://www.destroyallsoftware.com/talks/wat
- golergka 5y agoI guess there's a lot of people who don't work with JS and learn about it from memes like this, so I feel like I have to clarify: I've been writing Javascript (well, actually Typescript, as any other sane person) professionally for quite a few years now, and I can count the amount of times I've actually been bit by these quirks on one hand. And if they added Array.sort() and MAX_SAFE_INTEGER (NEVER serialise and deserialise Facebook's and other long digit IDs as numbers), it's still better than most of the alternatives, in my opinion.
- s_gourichon 5y agoWebsite content on a web browser: > This website is literally about JavaScript. I mean what did you expect, a .NET application? This website is 99.9% poorly optimized and highly questionable JS. And yet, you have JS turned off. Yes, a website can be about Javascript and still be a collection of documents in web standards, like HTML+CSS, possibly with optional interactive features that could be implemented in Javascript. I mean, what did you expect? That it is impossible to edit a book on paper about Javascript because obviously paper cannot run Javascript code? Even I have books about Javascript, and they render fine.
- vvoyer 5y agoI stopped at the first example (true + false). If you write code like this, you have bigger problems than using JavaScript. For most of the examples, it's like saying "Here's what happens when you plug a fan to a faucet". There's no point really. JavaScript is weird just like any other language can be weird when you use it in weird ways. And yes, it's certainly one of the weirdest. If you want to talk about things weird in JavaScript, let's talk about ES modules in Node.js and the Browser, or the number of decisions you have to make to bootstrap a simple web app in JavaScript, and how a language written in 10 days is shipped to billion of devices today. But, this kind of content, (while well made technically) is always the same one about JavaScript.
- qayxc 5y ago> I stopped at the first example (true + false). So you never did something like this: x = performCalculation(getParam1()) y = performCalculation(getParam2()) sum = x + y only to discover that "performCalculation()" sometimes returns a boolean instead of a number? JS is a dynamically typed language after all and functions like function f(x) { if (x >= 0) { return Math.sqrt(x) } else { return false } } are perfectly valid. If you use a 3rd party library that uses return values like this, you might run into such case without realising it. Sure, you won't explicitly write "true + false", but "f(x) + g(x)" is not uncommon and might indeed evaluate to "true + false".
- hajile 5y agoI've not run into that kind of issue in years. Read the docs of the function you're attempting to call. Also, in this case, the function should return NaN so it's not polymorphic.
- qayxc 5y ago> Also, in this case, the function should return NaN so it's not polymorphic. Sure. But what if that's function comes from a 3rd party component that doesn't have great documentation or relies on another package and thus a behaviour like this simply bubbles up through the call chain? And don't think this can't happen - NPM in particular notorious for this kind of deep dependencies. Also mixins and monkey patching are a thing in JS, so just importing a module can lead to an unexpected change in behaviour.
- lampe3 5y agoWhy are people wasting time on sites like this? Every programming language has some weird stuff in it. If you are writing code like that then you are the problem not the language. Is this just for the clicks? Is this developer click bait?
- vvoyer 5y ago^ This! It's "learning content" for tiktok-devs I guess.
- leodriesch 5y agoI took the quiz and enjoyed it. Just have some fun, I don’t think the quiz wants to convey any deeper message.
- AtNightWeCode 5y agoThere are some real problems with the quirks of Javascript too even if the examples are not that common. Some JS coders for instance use the oneof pattern and if you then forget somewhere to check if you got a Number instead of a Boolean you can end up with something weird. I have seen it several times.
- itsbits 5y agoJS is a loose type language by definition. Biggest problem for JS, from the beginning was people start writing without completely understanding it. Even myself seeing my initial JS code feel embarrassed. Noone understand what is or handle loose typing, prototype, closures, functional concepts like currying before coding. I took almost an year to understand same. Although that time there are hardly my resources like now. But I still see, people directly jumping into JS.
- chrismorgan 5y ago> 25. - "" + + "1" * null - [,] > Output: 0 > You answered: I give up > You answered incorrectly. No I didn’t. (Not my fault there were two potentially correct answers!)
- whoomp12342 5y agoTIL I dont know js.
- pdpi 5y agoI have plenty of complaints about Javascript, but most of these aren't it. I haven't done any serious javascript in something like 6 years, and I still got most of this right without much effort. #4, #13, #14, #21 and #24 are floating point problems and are nothing to do with JavaScript. A bunch of them are just "learn the language" issues: #2 I only got wrong because I never noticed JS allows trailing commas. Trailing commas are pretty damn common in most modern languages though. The syntax for empty initialisation of arrays is weird (and I'd argue is a mistake), but the behaviour is exactly what you'd expect. #5 is the comma operator as also seen in C and C++. #8 is something nobody should get wrong. Three nots in front of a true is false. Of course it is. #10 is just an octal literal. They're becoming increasingly rare in modern languages, and were never quite as common as hex literals, but they're also not terribly obscure. #15 is one I'm slightly ashamed I got wrong. It makes no sense to use increment operators on a bare value. This is common to just about all languages that support increment operators (and it's those, if any, that don't agree are in the wrong) #22 is a slightly surprising counterpoint, but it also makes sense. I don't know of a language that has a NaN literal, and JavaScript is no exception. So that NaN is actually a global that is bound to the floating point value NaN. Because it is a global, it can be incremented (but incrementing NaN is still NaN). Everything else is a type coercion issue. #18 and #23 are coercions I really disagree with. Coercing things to a number shouldn't produce NaN. That truly is crazy. Throwing is the only reasonable behaviour here. Ruby is even worse than JS here ("true".to_i produces 0), Python gets it right. Other than that, the coercions are all fairly make sense, and are consistent with what other languages do. Now, implicit type coercion (especially under the guise of abstract equality) is a terrible idea because it's easy to do it by accident and get nonsensical results, but the coercions themselves are, by and large, pretty sane.
- Izkata 5y ago> #2 I only got wrong because I never noticed JS allows trailing commas. No one used to risk it because IE was inconsistent with what it meant.
- eastbayjake 5y agoUX nit: would have preferred question-by-question feedback on right answer and overall score, quite a lot to get through 25 questions before you get any reward for your effort :)
- SavantIdiot 5y agoI don't think it is a UX nit. You would have started to catch on and learn if you had immediate feedback. When is the last time you took an in-person test where the proctor told you if you were right/wrong after every question? You need to grade current knowledge. In fact, I would have removed the multiple choice altogether for this test and had a input(type=text) EDIT: OK, ok: I get it, it is just a fun website, not the BAR.
- some_random 5y agoI'm trying to look at weird javascript, not haze new employees.
- uses 5y agoSame - it was clear to me by question 2 that I was going to be guessing on the rest of the quiz. Having to fill out the rest before getting feedback was a formality at that point. By the time I saw the answers, I couldn't remember why I guessed which way on each question.
- stared 5y agoJudging by the title, it sounded like the biggest discovery of 2021... by someone waking after a long coma. It was discovered in 2012: https://www.destroyallsoftware.com/talks/wat https://www.destroyallsoftware.com/talks/wat I really enjoyed the questions... and even though I am working in TypeScript, I got only 9/25. Precisely because I avoid f---ed up parts of JS, except for trivia games (https://dorey.github.io/JavaScript-Equality-Table/unified/ https://dorey.github.io/JavaScript-Equality-Table/unified/, http://www.jsfuck.com/ http://www.jsfuck.com/). Some parts of code need not to be understood. They need to be blocked by types, tests, and linters (https://p.migdal.pl/2020/03/02/types-tests-typescript.html https://p.migdal.pl/2020/03/02/types-tests-typescript.html).
- hajile 5y agohttps://xkcd.com/1053/ https://xkcd.com/1053/ There are a lot of people being born every year. If a 16-18 year old teenager is getting into web development, they were 4-6 when that talk was given in 2012. Sure, that talk still appears here and there, but it's past its prime and you'd have to be in the right place at the right time to run into it. Crockford's book (JS: The Good Parts) was ubiquitous among JS devs who were coding between 2008 and 2015 (give or take). These days, younger devs have never heard of it. Due to the Seinfeld Effect, if they read it, it would seem trite and obvious not realizing how revolutionary it was at the time.
- edgeform 5y agoNot to mention just because I was alive in 2012 doesn't mean I know or knew about this. The parent comments floating to the top here seem to have a common theme of "I knew that already how did the rest of the world not also get the memo at the same exact moment I did?"
- jonny_eh 5y agoIt's amazing how much of a positive effect that short comic has had on my life.
- stared 5y agoI know this xkcd strip, and love it by my heart. Though, I hope that now people learn JS without its worst parts. In any real codebase, expressions such as `true + ''` should not be understood. They should be eradicated.
- jokoon 5y agoThat was the most horrible quizz I've ever taken in my life. I recently tried to make a simple flask app to sort pictures on my computer. I used file:/// since there were a lot of them. I was quite unhappy to discover that CORS is quite restrictive...
- gmac 5y agoI'm actually pretty fond of JavaScript, but here's a question that has caught me out in real code: const x = [1, 10, 2], y = x.sort(); Now: what is the value of x? (Edit: and y?)
- tinco 5y agoI've been using JavaScript for around 15 years, and I've never used a comma to separate expressions. And I'd still go to MDN to look up if sort() is in place or not :p
- gmac 5y agoThe comma is not material here: the answer is the same if we write `const x = ...; const y = ...`. And that's the first gotcha: sort() is in place.
- dahart 5y agoPretty sure I’ve actually tripped on sort() myself before by assuming it was a new array. It does make sense for performance though, creating a new array would be a bad default choice for performance, for the same reasons that forEach is generally faster than map all else being equal.
- gmac 5y agoTrue. I like Ruby's solution with exclamation marks, such as `sort!`, to make this kind of behaviour obvious.
- zodiakzz 5y agoIn JavaScript every possible value has a .toString() representation* so it makes the most sense that the untyped/mixed array .sort() does lexicographic sorting. If you need numeric sort, use a TypedArray or provide an explicit arrow function. * Except Object.create(null), which throws.
- 5y ago
- tinco 5y agoIronically I got a bunch of these wrong because JavaScript is less weird than I thought it was. For example for some reason I thought ![] would be true, because JavaScript would do something weird, but it's not and JavaScript does exactly what you'd expect any sensible language to do. I didn't enjoy the quiz, it just reminds me how depressing the base layer of the thing I'm most passionate about in life is. The expression [1,2,3]+[4,5,6] returning what it does is just a bummer, it just sucks. Calling it weird is giving it undue merit, as if it's cute somehow that it's so awful.
- Zababa 5y agoI really think we should stop pushing things like that or the wat talk (https://www.destroyallsoftware.com/talks/wat https://www.destroyallsoftware.com/talks/wat). Sure it's funny and all, but it's not helping people understand. We're presenting Javascript as some kind of stupid black magic tool, which is not. You can very easily find the standard online, and go through the examples to understand. Sure it's unintuitive, I agree, but lots of things in programming are unintuitive, and when you can't change them you have to learn them.
- snet0 5y agoI don't even think it is unintuitive. There are very few things here (if any) that make no sense, and a few are literally just basic understanding of floating point spec. And then of course a few questions are basically obfuscated-C levels of code, where you won't get the answer correct unless you get your pen and paper out. I'd argue that if you don't know about type coercion in JS, you don't really know JS. It's a feature; none of these operators will throw; it's a conscious design choice.
- SCLeo 5y agoProbably unpopular opinion: Most of these are just the weirdness of the language caused by the (not-so-wise) design decision that those simple operators should never throw. In my opinion, these are not footguns and should not be used to attack JavaScript, because regular programmers are very unlikely to run into them (which is why when presented, they seem so obscure). However, that is not to say JavaScript is without footguns. For example, the classic `[1, 2, 3, 10].sort()`.
- edgeform 5y ago> these are not footguns and should not be used to attack JavaScript No one is calling them that except you. The site says it right at the front: > most of this syntax is probably, and hopefully, not something you use in your daily life. Your obsession with having to choose Side A or Side B won't let you see this for what it is... Just showing weird syntax in JS. That's all. Good lord.
- zild3d 5y agothe title is "javascript is weird", not "here's some weird syntax in javascript"
- SCLeo 5y agoI am not choosing a side here. However, deciding which language to use for a certain task is a legitimate choice that people to make. When making such decision, people need to analysis the pros and cons of a language. For countless times, I have seen people claiming JavaScript is bad/inconsistent/weird for reasons like `"1" + 1 === "11"` but `"1" - 1 === 0`. All I am saying here is things like these should not weigh too much when deciding whether to use JavaScript.
- mherrmann 5y agoJavaScript sorting numbers alphabetically is a fact I simply cannot get over. I know I should be pragmatic as an engineer but this goes against the core of my being. Awful.
- 5y ago
- zelphirkalt 5y agoAnd now imagine, if you had to deal with a programming language, which does not warn you or error out, when you are using null or undefined bindings in procedures, where you should be using strings or other things ... Wait, people actually invented such a language ...
- slver 5y agoEvery language has undefined or unexpected behaviors. The real lesson is that this doesn't necessarily matter, if they're not essential to the code you write most of the time. Also some of those about floating point math, which is not JS being weird, but rather about needing to know what a float is.
- LW9ucKsYuvuVeBa 5y ago> This website is literally about JavaScript. I mean what did you expect, a .NET application? This website is 99.9% poorly optimized and highly questionable JS. And yet, you have JS turned off.
- asimpletune 5y agoI’ve taught programming to people who struggled because they were misusing JS and the answer they were getting back coincidentally worked for some inputs but not others. Imagine trying to explain to them that this was their fault? Even trying to find the words to explain what happened made me feel bad that their first experience programming was tarnished by a language that will gladly allow you to do nonsense.
- ozim 5y agoCan it be that JS is not good starting language then? Maybe strongly typed compiled languages would be a better fit? One can argue that if you want to program it might be too much information for starters - but IMO basic types are such a fundamental concept that it would be better to teach that concept early on. It also clears up a lot of newbie confusion as you cannot assign string to an int by mistake with strongly typed language. Such scenarios are then handled by compiler so newly starting dev has quick feedback on fundamental issues with his code without having to ask people around.
- asimpletune 5y agoYeah, pretty much everything you mentioned was made clear to me after this.
- darksaints 5y agoThe problem with strongly typed languages is that it makes it infuriating whenever you have to work in a language without the same type guarantees. JavaScript made me want to throw my computers off the top of a skyscraper until I discovered typescript, and typescript just barely makes things slightly tolerable.
- denton-scratch 5y ago> Can it be that JS is not good starting language then? @ozim, I don't believe you are trolling! JS is an absolutely awful language for beginners; it's a 155mm howitzer pointed at your foot. Although you can get the hang of the basics quickly, AND it runs in the browser (super-convenient unless you're headless), those "basics" that you thought you'd got the hang of turn out to have semantics that make sense, but are not what you expected. I wrote JS (about 0.2 of my time, I guess) for my job, for about 20 years. I got 18 out of 25 on that test. Now, I think it was actually an easy test; I got a third of my answers wrong because I haven't learned about a third of JS semantics. I'm either not very good, or not as smart as I like to think. A certain recent colleague of mine would probably have got 25/25; he was cleverer than me, and he was REALLY into Javascript. Try a Pascal-type language, to learn an imperative-type language. Modula2 is better. Learning Prolog is (I think) purely declarative, so it gives you the view from the other side of the curtain - as it were. Forth is a perfectly-feasible beginner's language; it was the second language I learned. I can't recommend any OO language for beginners. Not because I think all OO languages are way too difficult, only all the ones I've used. I haven't used Smalltalk. I haven't used any flavour of Lisp. That language is so pliable that I'm sure there's a flavour that would be good for beginners. [edit] Actually, I wish I had learned a functional language like Lisp as my starting language; I strongly suspect that would have made me a better programmer throughout my career.
- dahart 5y agoNaN++ is sometimes a TypeError in environments that define NaN as read only, that one’s sometimes wrong. The float examples aren’t weird in JS, they’re the same in all languages that use IEEE 754 floats, which specifies that NaN != x, where x is anything. “This is due to a decision made by the IEEE-754 committee for a few reasons, such as space efficiency and the fact that the function isNaN didn't exist at the time.” This explanation feels like it’s trying hard to downplay the reasons and make it sound arbitrary and almost whimsical. It doesn’t make sense to allow NaN - NaN = 0 (Note that Infinity - Infinity == NaN), and it’s important that NaNs used as input to computation produce NaNs as output (other than when using boolean tests).
- jjice 5y agoTypeScript to the rescue! I just prefer strongly typed languages, but it's things like this that disappear (for the most part) when you have types. I personally can't keep types in my head as well as some, so when the language forces me to, it helps a lot. Vanilla JS just makes me feel like I'm walking on egg shells. Then we can get into a lot of fun when we get to type systems like SML and Rust where you start to really touch on some power (but can become intimidating). I'm still a bit weary of trying to hop into Haskell.
- tabtab 5y agoI just wish TypeScript supported optional named parameters. Once I got used to them in C#, it's hard to live without. They make adding enhancements so much easier. The work-arounds, such as object literals, are just not the same.
- Demiurge 5y agoI love that 1/0 = infinity in JS. It's as pragmatic as a tired student doing their algebra homework at 1AM :))
- an1sotropy 5y agoLike others have already noted; 1/0 == inf is something about JS, it is a consequence of JS defaulting to IEEE754 floating point representation for all numbers. Any language that supports IEEE754 FP will have the same result.
- jfoutz 5y agoEh. I'm not a JavaScript developer, just winging it I got 9/25. Seems like there are 3 broad categories of (my) confusion. 1. floating point. Floating point is tricky, and when I use it seriously I have to look up a lot of special cases. I often forget I can get Nan, and it'll infect everything it touches. This is common in just about any language. 2. One or two of those , questions got me. I don't _hate_ it, but there's a little frustration there. Mostly I just need to know the syntax. If I was writing javascript for money, I imagine it would bite me once or twice, then I'd just memorize the rule. 3 (the biggie) implicit conversion. Oof. seems like a lot of types can be converted to other types, and it's not obvious to me what the precedence hierarchy is. With C I have to look up the edge cases around signed/unsigned, but usually it's just use the next bigger one int -> long. Java does the .toString for everything which has bitten me once or twice. I really don't have a sense of javascript implicit conversion. Some of those seem really subtle.
- zwarag 5y agoCould [,,,] be used to optimize an array allocation? Say I'll need an array of fixed size. Could this method be used to help the interpreter to allocate an array more efficiently?
- lkj23ioj233i 5y agoWhat's wrong with JavaScript? It's existence.
- dzonga 5y agosilly questions, some of these expressions you don't use on a daily basis. language has quirks, but allows you to do a lot in a much expressive manner.
- julionc 5y ago“11” + 1 = “111” “11” - 1 = 10 (ノಠ益ಠ)ノ
- gammalost 5y agoI mean to be fair how would one subtract a string? What would "abc" - "def" mean? Would "abcd" - "bcd" = 0? So it's already an absurd thing to do