转自:http://berzniz.com/post/68001735765/javascript-hacks-for-hipsters

Javascript Hacks for Hipsters

Javascript is so much fun, except when it’s not.

There’s always the fear of runtime errors that keeps us thinking all the time while writing code. It makes us better coders - we have no other option than to visualize every line of code as if it’s running as we write it.

That’s why it’s so important to have tidy code. Small code. Pretty code. Code you just fall in love with. Otherwise, Javascript will scare you away.

I gathered some fun snippets I enjoy using instead of boring code that takes too much space. Some makes the code shorter, cleaner and more readable. Other are just plain hacks for debugging.

I learned all of this from open source code (until node.js all javascript code was open source, wasn’t it?), but I’ll write them here is if I invented them.

Hipster Hack #1 - Method calling

I really hate if/else blocks and this is quite a useful trick to call the right function based on a boolean value.

// Boring
if (success) {
obj.start();
} else {
obj.stop();
} // Hipster-fun
var method = (success ? 'start' : 'stop');
obj[method]();
 
view rawjshipster_method.js hosted with ❤ by GitHub

Hipster Hack #2 - String joins

It’s a known fact that strings like other strings. Sooner or later you’d like to concatenate two or more of them. I don’t really like +ing them together, so join() comes to the rescue.

['first', 'name'].join(' '); // = 'first name';

['milk', 'coffee', 'suger'].join(', '); // = 'milk, coffee, suger'
view rawjshipster_join.js hosted with ❤ by GitHub

Hipster Hack #3 - Default Operator ||

Javascript is all about not knowing what an object holds. Sometime you get it as a function argument, other times you might read it from the network or a configuration file. Either way, you can use the || operator to use the second argument if the first is falsy.

// default to 'No name' when myName is empty (or null, or undefined)
var name = myName || 'No name'; // make sure we have an options object
var doStuff = function(options) {
options = options || {};
// ...
};

Hipster Hack #4 - Guard Operator &&

Similar to the Default Operator, this one is super useful. It eliminates almost all IF calls and makes for a nicer code.

// Boring
if (isThisAwesome) {
alert('yes'); // it's not
} // Awesome
isThisAwesome && alert('yes'); // Also cool for guarding your code
var aCoolFunction = undefined;
aCoolFunction && aCoolFunction(); // won't run nor crash

Hipster Hack #5 - XXX Operator

This one is totally copyrighted and also SFW. Whenever I write some code, but then have to consult the web, or a different part of the code, I add an xxx line to the code. This makes the code break so I can get back to the specific place and fix it later. Much easier to search for it (xxx usually never appears) and you don’t have to think about a TODO comment.

var z = 15;
doSomeMath(z, 10);
xxx // Great placeholder. I'm the only one using xxx and it's so easy to find in code instead of TODOs
doSomeMoreMath(z, 15);
view rawjshipster_xxx.js hosted with ❤ by GitHub

Hipster Hack #6 - Timing

Ever wonder what’s faster: Looping with an i++ or looping with an i— ? Yeah, me neither. For those who does, you can use the console’s timing methods to test for slow loops or any other event-loop blocking code.

var a = [1,2,3,4,5,6,7,8,9,10];

console.time('testing_forward');
for (var i = 0; i < a.length; i++);
console.timeEnd('testing_forward');
// output: testing_forward: 0.041ms console.time('testing_backwards');
for (var i = a.length - 1; i >= 0; i--);
console.timeEnd('testing_backwards');
// output: testing_backwards: 0.030ms
view rawjshipster_timing.js hosted with ❤ by GitHub

Hipster Hack #7 - Debugging

I learned this one from a Java developer. I have absolutely no idea how he knew about it and I didn’t, but I’ve been using it ever since. Just drop a debugger statement and the debugger will stop on that line.

var x = 1;
debugger; // Code execution stops here, happy debugging
x++; var x = Math.random(2);
if (x > 0.5) {
debugger; // Conditional breakpoint
}
x--;

Hipster Hack #8 - Old School Debugging

I’ve always been a “printf debugger” more than a line-by-line-in-a-debugger kind of developer. If you’re like me, you’ll want to “export” some private vars into the global scope in order to examine them from time to time. Don’t forget to remove these before committing/pushing-to-production.

var deeplyNestedFunction = function() {
var private_object = {
year: '2013'
}; // Globalize it for debugging:
pub = private_object;
}; // Now from the console (Chrome dev tools, firefox tools, etc)
pub.year;

Hipster Hack #9 - Ultra Light Templates

Are you still concatenating strings using the + operator? Here’s a better way to combine a sentence with your data. It’s called templating and here’s a mini framework in 2.5 lines of code.

var firstName = 'Tal';
var screenName = 'ketacode' // Ugly
'Hi, my name is ' + firstName + ' and my twitter screen name is @' + screenName; // Super
var template = 'Hi, my name is {first-name} and my twitter screen name is @{screen-name}';
var txt = template.replace('{first-name}', firstName)
.replace('{screen-name}', screenName);

Javascript几个时髦的hack技巧《Javascript Hacks for Hipsters》的更多相关文章

  1. javascript自动填写表单小技巧

    javascript自动填写表单小技巧 在平时开发过程中,或者在访问某些站点,经常要频繁地填写一大堆表单时,我们可以利用javascript,写一段脚本,预先把要填的信息准备好,然后模拟点击按钮的动作 ...

  2. 【转载】webstorm-前端javascript开发神器中文教程和技巧分享

    webstorm是一款前端javascript开发编辑的神器,此文介绍webstorm的中文教程和技巧分享. webstorm8.0.3中文汉化版下载:百度网盘下载:http://pan.baidu. ...

  3. webstorm-前端javascript开发神器中文教程和技巧分享(转)

    webstorm是一款前端javascript开发编辑的神器,此文介绍webstorm的中文教程和技巧分享. webstorm8.0.3中文汉化版下载:百度网盘下载:http://pan.baidu. ...

  4. webstorm-前端javascript开发神器中文教程和技巧分享(转)

    webstorm是一款前端javascript开发编辑的神器,此文介绍webstorm的中文教程和技巧分享. webstorm8.0.3中文汉化版下载: 百度网盘下载:http://pan.baidu ...

  5. CSS hack技巧

    CSS hack技巧一览,原文来自CSDN freshlover的博客专栏<史上最全CSS Hack方式一览> 什么是CSS hack 由于不同厂商的流览器或某浏览器的不同版本(如IE6- ...

  6. 【历史】JavaScript和Java没啥关系!————JavaScript简史

    文章的开始先上张图: 图片拍摄自北京图书大厦,代表着现在国内应该是绝大部分书店的现状--Javascript书籍放在Java类当中.甚至很多业内人也一直认为Javascript是Java语言在浏览器内 ...

  7. 读《你不知道的JavaScript(上卷)》后感-浅谈JavaScript作用域(一)

    原文 一. 序言 最近我在读一本书:<你不知道的JavaScript>,这书分为上中卷,内容非常丰富,认真细读,能学到非常多JavaScript的知识点,希望广大的前端同胞们,也入手看看这 ...

  8. 2、JavaScript 基础二 (从零学习JavaScript)

     11.强制转换 强制转换主要指使用Number.String和Boolean三个构造函数,手动将各种类型的值,转换成数字.字符串或者布尔值. 1>Number强制转换 参数为原始类型值的转换规 ...

  9. 1、JavaScript 基础一 (从零学习JavaScript)

    1:定义:javascript是一种弱类型.动态类型.解释型的脚本语言. 弱类型:类型检查不严格,偏向于容忍隐式类型转换. 强类型:类型检查严格,偏向于不容忍隐式类型转换. 动态类型:运行的时候执行类 ...

随机推荐

  1. HDU 2516 取石子游戏(斐波那契)

    取石子游戏 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submi ...

  2. 面试总结之MISC(操作系统,网络,数学,软件开发,测试,工具,系统设计,算法)

    操作系统 解释堆和栈的区别. 分配在堆的内存与分配在堆栈的内存有什么不同 分配在堆的内存要手动去释放 线程与进程的区别 多线程中栈与堆是公有的还是私有的 在多线程环境下,每个线程拥有一个栈和一个程序计 ...

  3. [原]Android 开发第一步

    使用 android-studio 开发 写文章时的最新 Android-Studio 程序下载:https://dl.google.com/dl/android/studio/ide-zips/3. ...

  4. 4_bootstrap之栅格系统

    4.栅格系统 4.1.简述栅格系统 为了方便在布局容器中进行网页的布局操作. BootStrap提供了一套专门用于响应式开发布局的栅格系统. 栅格系统将一行分为12列,通过设定元素占用的列数来 布局元 ...

  5. SAFEARRAY

    SAFEARRAY SafeArrayCreate  SafeArrayDestroy // Specify the bounds: // -- dim. count = 2 // -- elemen ...

  6. 跟我学算法-xgboost(集成算法)基本原理推导

    1.构造损失函数的目标函数 2.对目标函数进行泰勒展开 3.把样本遍历转换成叶子节点遍历,合并正则化惩罚项 4.求wj进行求导,使得当目标函数等于0时的wj的值 5.将求解得到的wj反导入方程中,解得 ...

  7. HUAWEI手机解锁

    1.关机:2.同时按上音量键和电源键,直至出现Android system recovery,按下音量键选择wipe date/factory reset->Yes-delete all use ...

  8. Work-Stealing in .NET 4.0

    [Work-Stealing in .NET 4.0] 1.线程按LIFO取Task,因为最后一个Task很可能还在Cache中,提高命中率. 2.Stealer从FIFO取Task,最先加入的Tas ...

  9. uva10288 Coupons 【概率 分数】

    题目: 题意: 一共n种不同的礼券,每次得到每种礼券的概率相同.求期望多少次可以得到所有n种礼券.结果以带分数形式输出.1<= n <=33. 思路: 假设当前已经得到k种,获得新的一种的 ...

  10. 没有Home键之后的iPhone会是什么样子?

    以下内容由Mockplus团队翻译整理,仅供学习交流,Mockplus是更快更简单的原型设计工具. 之前笔者推测新一代的iPhone不会再有“Home”键.果不其然,9月13日苹果发布会证实了笔者的观 ...