8 ms·
JavaScript Hacks for Hipsters
- rezistik 12y agoWhy `success ? 'method1' : 'method2'` instead of `success ? obj.method1() : obj.method2() `? That seems more concise to me.
- ryandvm 12y agoMakes sense. Javascript is the PBR of programming languages.
- kachnuv_ocasek 12y agoWhat's the PBR?
- JonnieCache 12y agohttps://en.wikipedia.org/wiki/Pabst_Blue_Ribbon https://en.wikipedia.org/wiki/Pabst_Blue_Ribbon As I understand it its basically a low quality beer supposedly drunk by US hipsters in order to cultivate a kind of working class legitimacy. It's long since become a meme in itself though.
- k__ 12y agoI don't know what to make of it. Some seem like good ideas and some like really bad ones...
- giancarlostoro 12y agoI couldn't take it seriously so I laughed instead. I really need some coffee.
- speakeron 12y ago"Trade bloated if/else blocks for a quick function call" Is there any programmer since the 1970s that needs to be told this?
- thirdtruck 12y agoPeople who have only been programming since the 2010s, for instance. Developers are not born with a refined code aesthetic. They have to learn it at some point.
- speakeron 12y agoWhat you're describing is a beginner programmer; that's not necessarily what a hipster is and the title is a bit of a slur. The article should have been titled "Programming Tips for New Programmers".
- JonnieCache 12y agoHows this for hipster: these are all basic programming techniques that have existed for decades and barely need to be pointed out. Or have I missed the joke? EDIT: this is "fake surprise" isn't it. I'm sorry HN. Everyone has to learn this stuff somewhere. But the title was kindof asking for it. To any newly minted developers out there, the best way to learn this stuff is just to read other peoples code. Pick the library you enjoy using the most and read every file until you understand what all the constructions and bits of syntax are for. Then compare it to another library, etc etc. Develop a taste for some and a distaste for others. There's no excuse not to learn experimentally in js as it has a repl. Use the source luke!
- whoisthemachine 12y agoYou didn't realize you are the ultimate hipster, you knew about these tricks before they were cool.
- JonnieCache 12y agoI'm pretty sure they were probably cool and then uncool and then cool again several times before I was born. Just because people used to punch holes in cards doesn't mean they didn't have l33t hax.
- phpnode 12y agoMost of this is just idiomatic JS, hardly "hacks".
- officialjunk 12y agoif internet explorer is important in your life, you can forget some of these.
- brbcoding 12y agoWhy is that? Which of these are browser specific?
- Cthulhu_ 12y agoPff, I used most of those before they were mainstream.
- Mithaldu 12y agoFor some reason the entire thing reads to me as a guide to writing Javascript like an experienced Perl developer. Either way, it's really cool to see people advocating an idiomatic style for JS. :)
- berzniz 12y agoWhile introducing new developers to work on the JS part of our codebase (node & client side) - I noticed some puzzled looks here and there. Not everyone understands why && and || are used outside of if statements. Not everyone knows about joining strings using an array. This summarises the things you'll have to know to read code in our codebase.
- xorcist 12y agoDon't they know about the join operator at all, or is there something else here? What else would you join if not arrays?
- berzniz 12y agoTell a novice JS developer to concatenate a list of strings: "first", "middle" and "last" into "first, middle, last". You'll probably get a solution using loops and a check if adding a comma is needed or not. I know, I asked my friends. Ask your new teammates.
- nmjohn 12y agoI would be concerned by someone not knowing || - it is used all the time by almost every major project. Not knowing what that one did outside of an if functions tells me 1.) Said person hasn't actually looked at any code other than their own OR 2.) They saw it and didn't care enough to learn what it did. Either way, strike against them. The && though, I've never used in this context. And I'm not sure if I've seen it out in the wild or not. I knew what it did right away so I imagine if I have seen it before I wouldn't remember.
- mattxxx 12y agoHey, I love neat Javascript tricks... but things like the "TODO" operator are really bad style and will hurt larger teams. Stick to standards, so ease-of-communication is simpler! The reality is that collaboration is harder than programming!
- nmjohn 12y agoI agree. If you want that functionality your text editor probably has it or a plugin for it - which will be much more efficient. In sublime for example, Ctrl+F2 marks a line, and F2 toggles between marked lines. (Ctrl+F2 removes the mark as well).
- rbinv 12y agoYou certainly lose some code readability with some of these.
- johannh 12y agoThis was originally published a year ago in this blog post: http://berzniz.com/post/68001735765/javascript-hacks-for-hipsters http://berzniz.com/post/68001735765/javascript-hacks-for-hip... Makes for a nicer read than slideshare imo.
- callahad 12y agoNon-slideshow link: http://berzniz.com/post/68001735765/javascript-hacks-for-hipsters http://berzniz.com/post/68001735765/javascript-hacks-for-hip... This may impugn my credibility as a professional developer, but I genuinely can't tell if this article is sarcastic or sincere.
- usingpond 12y agoMany of these are: 1) Much less legible, and in some cases outright lazy 2) Extremely vulnerable to Javascript's fast-and-loose type checking. However it's good to be AWARE of them, since you tend to see them a lot in team projects.
- Kiro 12y agovar aCoolFunction = undefined; aCoolFunction && aCoolFunction(); What is the purpose of this?
- berzniz 12y agovar getJSON = function(callback) { // did async work to get the JSON data and now I want to call the callback function, but is it there? callback && callback(data); }; getJSON(); // See how I don't care about the result
- lnanek2 12y agoIf the function doesn't exist, don't do anything. aCoolFunction is false so the other half of the statement won't execute. If it does exist, call it. Useless as written, but there may be cases where you don't know if it is defined or not when you want to call it.
- nmjohn 12y agoVery few practical purposes. It was already described what it does - but the thing is, why would you ever want that? If a function is coming up undefined that I expect to be defined, that's an issue - not one I want to fail silently - because that is no fun to debug. If something I expect to be defined isn't, that should throw an error and stop execution. There are some edge cases where it may not matter and there is a legit reason why a function may sometimes be undefined, but I've never written code like that and can't think of anything that doesn't have a much better alternative.
- nikon 12y agoSome of these are mildly useful, but not sure it deserves front page. I like using .filter, .forEach and .map native methods on arrays. Also making use of Underscore.js where possible.
- fedlarm 12y agoOne I've never thought of using before is the: isAwesome && alert("yay"); I have used the name || "no name" operator a lot and thought to myself that it looked cool on first impression. But having something like: isAwesome() && alert("yay"); Already makes it harder to read I think. I'm curious to what others think of this one? Maybe its just because it is new to me..
- JonnieCache 12y agoI agree that it's ugly, but also in some languages you can get into trouble because of operator precedence. This is why ruby and perl have the operators `or` and `and` as well as || and &&. http://devblog.avdi.org/2010/08/02/using-and-and-or-in-ruby/ http://devblog.avdi.org/2010/08/02/using-and-and-or-in-ruby/
- byerley 12y agoI don't think I've ever misread that style (usually the function being called makes it obvious), but it relies on short-circuit evaluation which doesn't carry over to a lot of languages - http://en.wikipedia.org/wiki/Short-circuit_evaluation http://en.wikipedia.org/wiki/Short-circuit_evaluation C is particularly dangerous because it will normally short-circuit, but the standard doesn't require it and in rare cases the compiler will optimize it out.
- xyclos 12y agoit is also useful for cross browser debugging. having a console.log() in your code running in IE will cause problems if the console isn't actually open. If you use window.console&&console.log() you can be sure that it wont hurt your code running in IE.
- digibo 12y agoI find constructs like isAwesome() && alert("yay"); confusing as well, but in our codebase it's pretty much standard to use a simple falsy check like 'callback && callback()' for optional callbacks, but we don't use it anywhere else. To be honest, I like and use some of those, especially when writing experimental/disposable code, but otherwise I try to be gentle to less experienced developers and my future self. As of #5 - I used to do and love this when writing unit tests. At the end of the work day, if I'm in the middle of implementing a feature, I'd commit and then write the next unit test (inevitably) sitting in my head and leave it failing. Really helps when it's Monday.
- otikik 12y agoPresentation Hack for Hipsters: Use bigger fonts than this guy.
- wildpeaks 12y agoThe problem with #1 is that the minifier (e.g. http://closure-compiler.appspot.com/home http://closure-compiler.appspot.com/home) can't optimize as much. --------- Example using strings: var obj = { start: function(){ 'use strict'; console.log('start'); }, stop: function(){ 'use strict'; console.log('stop'); } }; exports.onDummy = function(success){ 'use strict'; var method = (success ? 'start' : 'stop'); obj[method](); }; results in: var a={start:function(){console.log("start")},stop:function(){console.log("stop")}};exports.a=function(b){a[b?"start":"stop"]()}; --------- Same thing, using if..else: var obj = { start: function(){ 'use strict'; console.log('start'); }, stop: function(){ 'use strict'; console.log('stop'); } }; exports.onDummy = function(success){ 'use strict'; if (success){ obj.start(); } else { obj.stop(); } }; results in the much shorter: exports.a=function(a){a?console.log("start"):console.log("stop")};
- thomasmarcelis 12y agoSomeone needs to clarify to me why people are excited about this. Isn't this just horrible for readability? I've just started reading Clean Code, and there is a lot of emphasis on writhing readable code, because the philosophy is that code is only written once but read many times.
- wuliwong 12y agoI have read a few places recently about techniques and strategies to get rid of ifs and else's in code. It was all in the spirit of writing more concise and compact code, not about the actual speed when executing the code. So often, I see "concise" at odds with "readability." The '&&' slide is a good example of this. For me, multi-line if/else statements are pretty easy to read. I hate running into complicated, one line, if else statements, it feels to me that it takes twice as long to parse and understand.
- nkg 12y agoI have witnessed many of these on some JS projects I've been working on! While I took time to think on it and figure out what the "author" was aiming at, my colleagues were more like "What does this mean? No way I'm touching that. Let's rewrite that crap!"
- drinchev 12y agoIMHO, hipster JavaScript is called CoffeeScript. 1) do obj[if success then 'start' else 'stop'] 2) ['milk', 'coffee', 'sugar'].join ', ' 3) doStuff = (options = {}) -> 4) isThisAwesome?() 5) ### ... ### 6-8) ... 9) template = "Hi, my name is #{firstName} and my twitter screen name is @#{screenName}" [1] http://coffeescript.org/#try:do%20obj%5Bif%20success%20then%20'start'%20else%20'stop'%5D%0A%0A%5B'milk'%2C%20'coffee'%2C%20'sugar'%5D.join%20'%2C%20'%0A%0AdoStuff%20%3D%20(options%20%3D%20%7B%7D)%20-%3E%0A%0AisThisAwesome%3F()%0A%0Atemplate%20%3D%20%22Hi%2C%20my%20name%20is%20%23%7BfirstName%7D%20and%20my%20twitter%20screen%20name%20is%20%40%23%7BscreenName%7D%22 http://coffeescript.org/#try:do%20obj%5Bif%20success%20then%...
- blergh123 12y agoI'm actually not sure whether this is a joke or not, some of these practices like #1, #4 and even #5 reek of amateurish programming practices - maybe this is fine for your own pet projects, but if you're working with teams or on open source then have fun!