Created
June 17, 2015 15:19
-
-
Save dinh/9e5f0efd13e918525023 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#http://www.sitepoint.com/shorthand-javascript-techniques/ | |
1. If true … else Shorthand | |
var big = (x > 10) ? true : false; | |
var big = (x > 10); | |
//further nested examples | |
var x = 3, | |
big = (x > 10) ? "greater 10" : (x < 5) ? "less 5" : "between 5 and 10"; | |
console.log(big); //"less 5" | |
var x = 20, | |
big = {true: x>10, false : x< =10}; | |
console.log(big); //"Object {true=true, false=false}" | |
2. Object Array Notation Shorthand | |
var a = ["myString1", "myString2", "myString3"]; | |
3. Associative Array Notation Shorthand | |
var skillSet = { | |
'Document language' : 'HTML5', | |
'Styling language' : 'CSS3', | |
'Javascript library' : 'jQuery', | |
'Other' : 'Usability and accessibility' | |
}; | |
4. Declaring variables Shorthand | |
var x, y, z=3; | |
5. Assignment Operators Shorthand | |
x++; //x=x+1; | |
minusCount --; //minusCount = minusCount - 1; | |
y*=10; //y=y*10; | |
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 | |
6. RegExp Object Shorthand | |
var result = /d+(.)+d+/igm.exec("padding 01234 text text 56789 padding"); | |
console.log(result); //"01234 text text 56789" | |
7. If Presence Shorthand | |
if (likeJavaScript) //if (likeJavaScript === true) | |
var a; | |
if ( !a ) { | |
// do something... | |
} | |
8. Function Variable Arguments Shorthand | |
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 ); | |
9. JavaScript foreach Loop Shorthand | |
for(var i in allImgs) | |
Shorthand for Array.forEach: | |
function logArrayElements(element, index, array) { | |
console.log("a[" + index + "] = " + element); | |
} | |
[2, 5, 9].forEach(logArrayElements); | |
// logs: | |
// a[0] = 2 | |
// a[1] = 5 | |
// a[2] = 9 | |
10. Switch Knightmare | |
var cases = { | |
1: doX, | |
2: doY, | |
3: doN | |
}; | |
if (cases[something]) { | |
cases[something](); | |
} | |
11. Shorter IF’z | |
if([1,5,7,22].indexOf(myvar)!=-1) alert('yeah baby!') //if( myvar==1 || myvar==5 || myvar==7 || myvar==22 ) alert('yeah') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment