Skip to content

Instantly share code, notes, and snippets.

@jvgreenaway
Last active December 14, 2015 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jvgreenaway/5022220 to your computer and use it in GitHub Desktop.
Save jvgreenaway/5022220 to your computer and use it in GitHub Desktop.
JavaScipt examples extracted from MSDN 's reintroduction.
// The && and || operators use short-circuit logic, which means whether they will execute their second operand is dependent on the first. This is useful for checking for null objects before accessing their attributes:
var name = o && o.getName();
// Or for setting default values:
var name = otherName || "default";
//JavaScript has a ternary operator for conditional expressions:
var allowed = (age > 18) ? "yes" : "no";
for (var i = 0; i < a.length; i++) {
// Do something with a[i]
}
// This is slightly inefficient as you are looking up the length property once every loop. An improvement is this:
for (var i = 0, len = a.length; i < len; i++) {
// Do something with a[i]
}
An even nicer idiom is:
for (var i = 0, item; item = a[i++];) {
// Do something with item
}
// “Named anonymous functions” as below:
var charsInBody = (function counter(elm) {
if (elm.nodeType == 3) { // TEXT_NODE
return elm.nodeValue.length;
}
var count = 0;
for (var i = 0, child; child = elm.childNodes[i]; i++) {
count += counter(child);
}
return count;
})(document.body);
// Attaching functions to objects
function makePerson(first, last) {
return {
first: first,
last: last,
fullName: function() {
return this.first + ' ' + this.last;
},
fullNameReversed: function() {
return this.last + ', ' + this.first;
}
}
}
> s = makePerson("Simon", "Willison")
> s.fullName()
Simon Willison
> s.fullNameReversed()
Willison, Simon
// We can take advantage of the ‘this’ keyword to improve our makePerson function:
function Person(first, last) {
this.first = first;
this.last = last;
this.fullName = function() {
return this.first + ' ' + this.last;
}
this.fullNameReversed = function() {
return this.last + ', ' + this.first;
}
}
var s = new Person("Simon", "Willison");
// Prototypes
function Person(first, last) {
this.first = first;
this.last = last;
}
Person.prototype.fullName = function() {
return this.first + ' ' + this.last;
}
Person.prototype.fullNameReversed = function() {
return this.last + ', ' + this.first;
}
// Closures
function makeAdder(a) {
return function(b) {
return a + b;
}
}
x = makeAdder(5);
y = makeAdder(20);
x(6) // returns 11
y(7) // returns 27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment