4 ms·
Enjoyable Javascript
- actsasbuffoon 13y ago> X ? doSomething() : doSomethingElse() That's called a ternary operator, and it exists in almost every language. It's not a great example of the power of JS. The things that tend to concern people most about JavaScript have little to do with poor browser implementations, but are a result of JS being a really messy language. Consider the following code: [] + 1; // => "1" In any sane language this would result in an exception, not a string. And using strict mode doesn't help: (function() {"use strict"; return [] + 1;})(); // => "1" There are other things that are even more concerning. {} + 1; // => 1 ({} + 1); // => "[object Object]1" This behavior makes no sense. Wrapping an expression in parens should not modify the value of the expression, only its evaluation precedence. It gets worse: {} + 1 === ({} + 1); // => false ({} + 1) === {} + 1; // => true Note that I'm using threequals here, so JS shouldn't be doing any weird automatic type coercions. This violates the basic laws of logic. If A is equal to B, then B must be equal to A. JavaScript was built to be a forgiving language. One of its core principles is that code shouldn't raise exceptions unless there's absolutely no way around it. As a result it does terrifyingly weird things to avoid exceptions, such as letting you subtract a number from an array. That may have seemed welcoming to non-developers 15 years ago, but we've got millions of professional web developers these days who understand that raising an exception is preferable to having your program do something unintended. I think it's the mismatch of expectations that causes a lot of gnashing of teeth about the state of JS. The good news is that JavaScript has proven to be a suitable language compilation target, so we've got things like GorillaScript that fix a lot of these weird behaviors.