In the previous JavaScript articles, jsB@nk showed many very useful JavaScript tips & tricks:
- Essential Guidelines of Helpful JavaScript Shorthand codes
- Efficient and Helpful JavaScript/jQuery Tips and Tricks
- Some Basic JavaScript Guidelines for Accessibility
Today, in this JavaScript post, I would like to tell about JavaScript shorthand codes, JavaScript shorthand techniques that improve your awesome JavaScript coding skills, JavaScript application development. They're valuable JavaScript coding styles every JavaScript developer should master.
Are you ready to go? Please leave any suggestion you need in the comments.
- Demo
- Enlarge
- Reload
- New window
Free iPage Web Hosting for First Year NOW
If you're still looking for a reliable web host provider with affordable rates, why you don't take a little of time to try iPage, only with $1.89/month, included $500+ Free Extra Credits for the payment of 24 months ($45)?
Over 1,000,000+ existisng customers can not be wrong, definitely you're not, too! More important, when you register the web hosting at iPage through our link, we're going to be happy for resending a full refund to you. That's awesome! You should try iPage web hosting for FREE now! And contact us for anything you need to know about iPage.
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. I have shown you the longhanded versions as well to give some coding perspective.
- 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 coding skills.
It’s as easy as 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:
var big; if (x > 10) { big = true; } else { big = false; }
Shorthand:
var big = (x > 10) ? true : false;
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:
var big = (x > 10);
2. Null, Undefined, ” 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:
if (variable1 !== null || variable1 !== undefined || variable1 !== '') { var variable2 = variable1; }
Shorthand:
var variable2 = variable1 || '';
Don’t believe me? Test it yourself (paste into Firebug and click run):
//null value example var variable1 = null; var variable2 = variable1 || ''; console.log(variable2); //output: '' (an empty string) //undefined value example var variable1 = undefined; var variable2 = variable1 || ''; console.log(variable2); //output: '' (an empty string) //normal value example var variable1 = 'hi there'; var variable2 = variable1 || ''; console.log(variable2); //output: 'hi there'
3. Object Array Notation Shorthand
Useful way of declaring small arrays on one line.
Longhand:
var a = new Array(); a[0] = "myString1"; a[1] = "myString2"; a[2] = "myString3";
Shorthand:
var a = ["myString1", "myString2", "myString3"];
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.
Longhand:
var skillSet = new Array(); skillSet['Document language'] = 'HTML5'; skillSet['Styling language'] = 'CSS3'; skillSet['Javascript library'] = 'jQuery'; skillSet['Other'] = 'Usability and accessibility';
Shorthand:
var skillSet = { 'Document language' : 'HTML5', 'Styling language' : 'CSS3', 'Javascript library' : 'jQuery', 'Other' : 'Usability and accessibility' };
Don�t forget to omit the final comma otherwise certain browsers will complain (not naming any names, IE).
5. 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:
"myString".charAt(0);
Shorthand:
"myString"[0]; // Returns 'm'
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:
x=x+1; minusCount = minusCount - 1; y=y*10;
Shorthand:
x++; minusCount --; y*=10;
Other shorthand operators, given that x=10 and y=5, the table below explains the assignment operators:
x += y //result x=15 x -= y //result x=5 x *= y //result x=50 x /= y //result x=2 x %= y //result x=0
7. Regex Object Shorthand
In Javascript, a Regex object can be called like a function like so:
/test/("is test in here")
As opposed to the more verbose(but sometimes more appropriate in cases that you are reusing the Regex).
Longhand:
searchText = "padding 1234 rocket str austin TX 78704 more padding" /\d+.+\n{0,2}.+\s+[A-Z]{2}\s+\d{5}/m(searchText) //returns: ["1234 rocket str austin TX 78704"]
Shorthand:
var re = new RegExp(/\d+.+\n{0,2}.+\s+[A-Z]{2}\s+\d{5}/m); re.exec(searchText); //returns: ["1234 rocket str austin TX 78704"]
8. If Presence Shorthand
This might be trivial, but worth a mention. When doing “if checks” assignment operators can sometimes be ommited.
Longhand:
if (likeJavaScript == true)
Shorthand:
if (likeJavaScript)
Here is another example. If “a” is NOT equal to true, then do something.
Longhand:
var a; if ( a != true ) { // do something... }
Shorthand:
var a; if ( !a ) { // do something... }
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 substitute to functions as constructors.
Longhand:
function myFunction( myString, myNumber, myObject, myArray, myBoolean ) { // do something... } myFunction( "String", 1, [], {}, true );
Shorthand (looks long but only because I have console.log’s in there!):
function myFunction() { console.log( arguments.length ); // Returns 5 for ( i = 0; i < arguments.length; i++ ) { console.log( typeof arguments[i] ); // Returns string, number, object, object, boolean } } myFunction( "String", 1, [], {}, true );
10. JavaScript foreach Loop Shorthand
This little tip is really useful if you want plain JavaScript and hence can’t use the awesome jQuery.each.
Longhand:
for (var i = 0; i < allImgs.length; i++)
Shorthand:
for(var i in allImgs)
11. Suggest one?
I really do love these and would love to find more, please leave a comment!
- Sent (0)
- New
Generate your business videos by AI with voice or just text
chatGPTaz.com
Talk to ChatGPT by your mother language
AppAIVideo
Your first FREE AI Video App
Deepfake Video
Deepfake AI Video Maker
Deepfake
Deepfake AI Video Maker
AI Deep Fake
Deepfake AI Video Maker
AIvidio
AI Video Mobile Solutions
AIvideos
AI Video Platform & Solutions
AIvedio
AI Video App Maker
Faceswap AI Online
Swap Faces Video, Photo & GIFs Instantly with Powerful AI Tools - Faceswap AI Online FREE
Faceswap AI Online
Swap Faces Video, Photo & GIFs Instantly with Powerful AI Tools - Faceswap AI Online FREE
Temu Free $500 for New Users
Claim Free Temu $500 Credit via Affiliate & Influencer Program
Free TikTok Ads Credit
Master TikTok Ads for Your Business Marketing
Dall-E-OpenAI.com
Generate creative images automatically with AI
chatGPT4.win
Talk to ChatGPT by your mother language
First AI Product from Elon Musk - Grok/UN.com
Speak to Grok AI Chatbot with Your Language
Tooly.win
Open tool hub for free to use by any one for every one with hundreds of tools
GateIO.gomymobi.com
Free Airdrops to Claim, Share Up to $150,000 per Project
iPhoneKer.com
Save up to 630$ when buy new iPhone 16
Buy Tesla Optimus Robot
Order Your Tesla Bot: Optimus Gen 2 Robot Today for less than $20k
Lots of bad advice Reply
10. Don't ever use for in to loop over arrays http://stackoverflow.com/questions/500504/javascript-for-in-with-arrays
9. Unclear what you're showing, are you just showing how to use arguments?
7. What you suggested is not shorter.
5. bracket access instead of charAt is not cross browser.
4. Associative Array is not a JS object, JS has objects, that are hash maps, they are not like PHP's associative array, therefore, you shouldn't use new Array()
2. The two pieces of code are not equivalent: in the first one, variable2 will be undefined if variable1 is null; in the second case, it will become the empty string