Javascript Hacks for Hipsters

-- JavaScript 2014. 7. 16. 22:17
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

자바스크립트를 하면서 실제로 사용했던 것들과 사용하면 유용할 것들이 보여 여기에 정리해둔다.

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]();


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', 'sugar'].join(', '); // = 'milk, coffee, sugar'


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


추가) 2017-01-25

#4.1 - Converting to boolean using !! operator

Sometimes we need to check if some variable exists or if it has a valid value, to consider them as true value. For do this kind of validation, you can use the !!(Double negation operator) a simple !!variable, which will automatically convert any kind of data to boolean and this variable will return false only if it has some of these values: 0, null, "", undefined or NaN, otherwise it will return true. To understand it in practice, take a look this simple example:

function Account(cash) {  
    this.cash = cash;
    this.hasMoney = !!cash;
}

var account = new Account(100.50);  
console.log(account.cash); // 100.50  
console.log(account.hasMoney); // true

var emptyAccount = new Account(0);  
console.log(emptyAccount.cash); // 0  
console.log(emptyAccount.hasMoney); // false  


#4.2 - Converting to number using + operator

This magic is awesome! And it’s very simple to be done, but it only works with string numbers, otherwise it will return NaN(Not a Number). Have a look on this example:

function toNumber(strNumber) {  
    return +strNumber;
}

console.log(toNumber("1234")); // 1234  
console.log(toNumber("ACB")); // NaN  

This magic will work with Date too and, in this case, it will return the timestamp number: (Good~~)

console.log(+new Date()) // 1461288164385  


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);


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


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 (Great!!!)

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);


추가) 2017-01-25

#10 - Caching the array.length in the loop

길이로 for을 돌릴때는 코드가 군더더기 없이 아래처럼 하도록 습관화해야겠다.

for (var i = 0, length = array.length; i < length; i++) {  
    console.log(array[i]);
}


#11 - Array truncation (Good~~)

배열을 줄일 때 length를 지정하여 Truncate 하는 방식

This technique can lock the array’s size, this is very useful to delete some elements of the array based on the number of elements you want to set. For example, if you have an array with 10 elements, but you want to get only the first five elements, you can truncate the array, making it smaller by setting the array.length = 5. See this example:

var array = [1, 2, 3, 4, 5, 6];  
console.log(array.length); // 6  
array.length = 3;  
console.log(array.length); // 3  
console.log(array); // [1,2,3]  


#12 - Merging arrays (Great~~)

If you need to merge two arrays you can use the Array.concat() function:

var array1 = [1, 2, 3];  
var array2 = [4, 5, 6];  
console.log(array1.concat(array2)); // [1,2,3,4,5,6];  

많이 큰 배열끼리의 Merge에서는 concat방식은 새로운 배열을 만들기 위해 메모리 낭비가 심해진다.

However, this function is not the most suitable to merge large arrays because it will consume a lot of memory by creating a new array. In this case, you can use Array.push.apply(arr1, arr2) which instead creates a new array – it will merge the second array in the first one reducing the memory usage:

var array1 = [1, 2, 3];  
var array2 = [4, 5, 6];  
console.log(array1.push.apply(array1, array2)); // [1,2,3,4,5,6];  


출처 : http://berzniz.com/post/68001735765/javascript-hacks-for-hipsters


'-- JavaScript' 카테고리의 다른 글

다른 도메인에서 함수 호출  (0) 2014.11.24
유튜브 동영상 종료 시 처리하기  (0) 2014.08.21
[CrossBrowser] IE7, 8, 9에서 주의사항  (0) 2014.07.01
javascript replace  (0) 2014.05.21
javascript로 number_format 구현  (0) 2013.09.26
posted by 어린왕자악꿍