19+ JavaScript Shorthand Coding Techniques
2015-06-06 07:37
633 查看
http://www.sitepoint.com/shorthand-javascript-techniques/
Sam Deering
Published July 20, 2011
This really is a must read for any JavaScript based developer. I have made this post as a vital source of reference for learning shorthand JavaScript coding techniques that I have picked up over the years. To help you
understand what it going on I have included the longhand versions to give some coding perspective on the shorts.
Update 05/05/2013 – There are now 19 strong keep em coming! :)
Step 1 – Learn the JavaScript shorthand techniques.
Step 2 – Save valuable coding time by keeping your code to a minimum.
Step 3 – Impress your colleagues with your awesome new coding skillz!
It’s as easy as steps 1,2,3. Here they are.
This is a great code saver for when you want to do something if the test is true, else do something else by using the ternary operator.
Longhand:
Shorthand:
If you rely on some of the weak typing characteristics of JavaScript, this can also achieve more concise code. For example, you could reduce the preceding code fragment to this:
Shorthand:
Don’t believe me? Test it yourself (paste into Firebug and click run):
Useful way of declaring small arrays on one line.
Longhand:
Shorthand:
The old school way of setting up an array was to create a named array and then add each named element one by one. A quicker and more readable way is to add the elements at the same time using the object literal notation. Please
note that Associative Array are essentially JavaScript Objects with properties.
Longhand:
Shorthand:
Don’t forget to omit the final comma otherwise certain browsers will complain (not naming any names, IE).
It is sometimes good practice to including variable assignments at the beginning of your functions. This shorthand method can save you lots of time and space when declaring multiple variables at the same time.
longhand:
shorthand:
Assignment operators are used to assign values to JavaScript variables and no doubt you use arithmetic everyday without thinking (no matter what programming language you use Java, PHP, C++ it’s essentially the same principle).
Longhand:
Shorthand:
Other shorthand operators, given that x=10 and y=5, the table below explains the assignment operators:
Example to avoid using the RegExp object.
Longhand:
Shorthand:
This might be trivial, but worth a mention. When doing “if checks” assignment operators can sometimes be ommited.
Longhand:
Shorthand:
Here is another example. If “a” is NOT equal to true, then do something.
Longhand:
Shorthand:
Object literal shorthand can take a little getting used to, but seasoned developers usually prefer it over a series of nested functions and variables. You can argue which technique is shorter, but I enjoy using object literal notation as a clean substitute
to functions as constructors.
Longhand:
Shorthand (looks long but only because I have console.log’s in there!):
Shorthand:
Shorthand for Array.forEach:
Shorthand:
We’re no longer relying on the less reliable == as !(ret == undefined) could be rewritten as !(ret) to take advantage of the fact that in an or expression, ret (if undefined or false) will skip to the next condition and use it instead. This allows us to trim
down our 5 lines of code into fewer characters and it’s once again, a lot more readable.
Longhand:
Shorthand:
Just like #1 you can use ternary operators to make function calling shorthand based on a conditional.
Longhand:
Shorthand:
Everyone loves switch statements, *cough*. Here is how you might avoid switch case syndrome.
Longhand:
Shorthand:
You may have seen this one around it’s essentially a fancy way to write without the zeros. 1e7 essentially means 1 followed by 7 zeros – it represents a decimal base (JS interprets as a float type) equal to 10,000,000.
Longhand:
Shorthand:
Shorthand:
If you have mutiple IF variable value comparisons you can simply ass them to an array and check for presence. You could use $.inArray as an alternative.
Longhand:
Shorthand:
If you have code that behaves differently based on the value of a property, it can often result in conditional statements with multiple else ifs or a switch cases. You may prefer to use a lookup table if there is more than two options (even a switch statement
looks ugly!).
Longhand:
Shorthand:
The double bitwise trick provides us with some pretty nifty shorthand tricks. Read more about it here: Double
bitwise NOT (~~).
Longhand:
Shorthand:
I really do love these and would love to find more, please leave a comment!
Sam Deering
Published July 20, 2011
This really is a must read for any JavaScript based developer. I have made this post as a vital source of reference for learning shorthand JavaScript coding techniques that I have picked up over the years. To help you
understand what it going on I have included the longhand versions to give some coding perspective on the shorts.
Update 05/05/2013 – There are now 19 strong keep em coming! :)
Step 1 – Learn the JavaScript shorthand techniques.
Step 2 – Save valuable coding time by keeping your code to a minimum.
Step 3 – Impress your colleagues with your awesome new coding skillz!
It’s as easy as steps 1,2,3. Here they are.
1. If true … else Shorthand
This is a great code saver for when you want to do something if the test is true, else do something else by using the ternary operator.Longhand:
2. Null, Undefined, Empty Checks Shorthand
When creating new variables sometimes you want to check if the variable your referencing for it’s value isn’t null or undefined. I would say this is a very common check for JavaScript coders.
Longhand:
3. Object Array Notation Shorthand
Useful way of declaring small arrays on one line.Longhand:
4. Associative Array Notation Shorthand
The old school way of setting up an array was to create a named array and then add each named element one by one. A quicker and more readable way is to add the elements at the same time using the object literal notation. Pleasenote that Associative Array are essentially JavaScript Objects with properties.
Longhand:
5. Declaring variables Shorthand
It is sometimes good practice to including variable assignments at the beginning of your functions. This shorthand method can save you lots of time and space when declaring multiple variables at the same time.longhand:
6. Assignment Operators Shorthand
Assignment operators are used to assign values to JavaScript variables and no doubt you use arithmetic everyday without thinking (no matter what programming language you use Java, PHP, C++ it’s essentially the same principle).Longhand:
7. RegExp Object Shorthand
Example to avoid using the RegExp object.Longhand:
8. If Presence Shorthand
This might be trivial, but worth a mention. When doing “if checks” assignment operators can sometimes be ommited.Longhand:
Longhand:
9. Function Variable Arguments Shorthand
Object literal shorthand can take a little getting used to, but seasoned developers usually prefer it over a series of nested functions and variables. You can argue which technique is shorter, but I enjoy using object literal notation as a clean substituteto functions as constructors.
Longhand:
10. JavaScript foreach Loop Shorthand
This little tip is really useful if you want plain JavaScript and hence can’t use jQuery.each or
Array.forEach().
Longhand:
11. charAt() Shorthand
You can use the eval() function to do this but this bracket notation shorthand technique is much cleaner than an evaluation, and you will win the praise of colleagues who once scoffed at your amateur coding abilities!
Longhand:
12. Comparison returns
We’re no longer relying on the less reliable == as !(ret == undefined) could be rewritten as !(ret) to take advantage of the fact that in an or expression, ret (if undefined or false) will skip to the next condition and use it instead. This allows us to trimdown our 5 lines of code into fewer characters and it’s once again, a lot more readable.
Longhand:
13. Short function calling
Just like #1 you can use ternary operators to make function calling shorthand based on a conditional.Longhand:
14. Switch Knightmare
Everyone loves switch statements, *cough*. Here is how you might avoid switch case syndrome.Longhand:
15. Decimal base exponents
You may have seen this one around it’s essentially a fancy way to write without the zeros. 1e7 essentially means 1 followed by 7 zeros – it represents a decimal base (JS interprets as a float type) equal to 10,000,000.Longhand:
16. Decimal base exponents
You can use 1 and 0 to represent true and false. I’ve seen this used in JavaScript game development in shorthand while loops. Note that if you use the negative start your array may be in reverse. You can also use while(i++<10) and you don’t have to add the
i++ later on inside the while.
Longhand:
17. Shorter IF’z
If you have mutiple IF variable value comparisons you can simply ass them to an array and check for presence. You could use $.inArray as an alternative.Longhand:
18. Lookup Tables Shorthand
If you have code that behaves differently based on the value of a property, it can often result in conditional statements with multiple else ifs or a switch cases. You may prefer to use a lookup table if there is more than two options (even a switch statementlooks ugly!).
Longhand:
19. Double Bitwise
The double bitwise trick provides us with some pretty nifty shorthand tricks. Read more about it here: Doublebitwise NOT (~~).
Longhand:
20. Suggest one?
I really do love these and would love to find more, please leave a comment!
相关文章推荐
- Lazy loading JavaScript to improve site speed
- javascript在chrome浏览器中无法刷新的问题
- JavaScript中使用concat()方法拼接字符串的教程
- JavaScript中的lastIndexOf()方法使用详解
- JavaScript中操作字符串之localeCompare()方法的使用
- JavaScript中String.match()方法的使用详解
- JavaScript中的replace()方法使用详解
- 简介JavaScript中search()方法的使用
- JavaScript中的slice()方法使用详解
- JavaScript中的substr()方法使用详解
- 简介JavaScript中substring()方法的使用
- JavaScript中的toLocaleLowerCase()方法使用详解
- 简介JavaScript中toUpperCase()方法的使用
- JS多维数组转一维
- Javascript表达式中连续的 && 和 || 之赋值区别
- 函数传参和实际应用—JS学习笔记2015-6-5(第49天)
- 【js】解压缩的问题
- JavaScript Style Attributes
- 事件冒泡与事件捕获
- Javascript 多浏览器兼容性问题