Javascript idioms

From Zoltan Kochan, author of pnpm

 

Double exclamation

Prefixing anything with !! converts it to a boolean.

var foo = 0
console.log(!!foo)
//> false

Essentially it is a shorter way to write Boolean(foo).

Converting arguments to array

The arguments object can be used to access the arguments passed to the function. However, it is not an Array so it doesn’t have Array properties except length. The Array.prototype.slice.call(arguments) idiom is used very frequently to convert the argument’s object to an actual array.

(function() {
  console.log(arguments instanceof Array)
  //> false

  var args = Array.prototype.slice.call(arguments)
  console.log(args instanceof Array)
  //> true
})()

Assigning default values

function foo(opts) {
  var msg = opts.message || 'Hello world!'
  console.log(msg)
}

// instead of
function foo(opts) {
  var msg = opts.message ? opts.message : 'Hello world!'
  console.log(msg)
}

More examples of interesting || and && usages can be found in the 12 Simple (Yet Powerful) JavaScript Tips article.

Converting to array if not already

var totallyArray = [].concat(value)

//instead of
var totallyArray = value instanceof Array ? value : [value]

Converting strings to number

var foo = +'12.2'
var bar = +'12'

// instead of
var foo = parseFloat('12.2')
var bar = parseInt('12')

Checking if an array includes an element

if (~[1, 2, 3].indexOf(2)) { console.log('includes') }

// instead of
if ([1, 2, 3].indexOf(2) > -1) { console.log('includes') }

There are some other usage examples for the tilde operator as well in The Great Mystery of the Tilde(~).

Writing multi-line strings

var multiStr = [
  "This is the first line",
  "This is the second line",
  "This is more..."
].join("\n");

// instead of
var multiStr = "This is the first line\n" +
  "This is the second line\n" +
  "This is more...";

Looping through an array

It can be used if order is not important

for (var i = arr.length; i--;) {
  // ...
}

// instead of
for (var i = 0; i < arr.length; i++) {
  // ...
}

setTimeout(func, 0)

JavaScript code runs on one thread. Calling setTimeout with 0 allows to schedule a function to run after the current event loop tick.

setTimeout(function() {
  console.log('log message from next tick')
}, 0)

console.log('Hello world!')
//> Hello world!
//> log message from next tick

Comparison between class and traits in Scala

Singleton Can create new instance Can have a constructor Can be inherited
Class No Yes Yes Yes
Abstract class No No Yes Yes
Trait No No No Yes
Object Yes No No No

Also a small trick: Since an object cannot be inherited, we need to create a trait (a trait make sure the object won’t have a constructor) with the common values and functions of the objects we wanted to create, then both object would inherit the trait, with one object expanding on the trait.

This construction can be applied to perform Enumeration inheritance in Scala (since Enums by convention are created as objects)

Load data into controls in asp.net

Usually when working on windows form, I use this to do the work

        DropDownList1.DataSource = new ApplicationTableAdapter().GetDataBySystemID(1);
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataValueField = "ID";

But surprisingly, when switched to ASP.NET, the above code no longer works, at first I thought it was a problem with the paradigm so I tried to store the data as a session variable but that didn’t work either, until I tried this

        DropDownList1.DataSource = new ApplicationTableAdapter().GetDataBySystemID(1);
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataValueField = "ID";
        DropDownList1.DataBind();

One extra line.

Under the hood: how your friends might have updated their status via “mobile devices”

Recently I noticed a friend keeps on updating his status which appears to be coming from the most trendy mobile devices on the market right now.

Shiny stuff

He could have borrowed his friend’s devices though, but since he is watching the World Cup alone I guessed there was something abnormal about it, so I decided to look for some sort of application that allow you to change your status with those neat little “via Facebook for iPhone”, “via Facebook for Blackberry” etc.

I found this

Status update service

It worked and I was able to get those appealing statuses, but what bothered me is, this seems all too simple, it seems to utilize some sort of Facebook API but previously, when I referenced the Facebook wiki for Stream writing and link posting, I found no parameters that would allow you to edit the “via…”. And the site above didn’t show how it did that, so I decided to dig in. Time for Ctrl+U (view source).

A bunch of Iframes (notice the capitalization, it's not iFrame :p)

That seemed simple, it’s just a bunch of iframes referencing to some sort of Facebook’s live-chat like service. It does say “event” so I tried to create an event but found no options to create such a widget. I tried to search for Facebook connect instead and found this post.

Step 1 – Create the App in Facebook

First things first. Go here to create the App in Facebook: http://www.facebook.com/developers/createapp.php. Give it a name:

Then, add all the necessary info that you can, including logos, icons, user-facing URLs, etc on the “Basic” tab:

You technically don’t have to fill out really anything except this next part.

Go to the “Connect” Tab on the left and fill out this important information there:

Make sure you get this right!

And that’s it! Make sure you write down (or copy) your Application ID, as you’ll need that next:

Step 2 – Create the iFrame, Style, and Finish!

Honestly, most of the hard work is done already!

All you have to do is copy some iFrame code into your template or website with the Application ID, adjust some of the width/height to fit correctly, and you’re done!

As you can see, I’m adding the code to the bottom of the page, just above the Footer. I’ve added a “fbc” <div> class to styling to make sure it’s centered correctly, etc.

You don’t have to do any of this, of course, and most people won’t have to do anything with CSS styling.

And here’s what the code looks like in my footer.php file (I’m using WordPress to power this site).

As you can see, I’ve adjusted the width to be 983 pixels wide (matching my div class) and the height is 500 pixels.

You can, of course, change all of this to whatever you’d like! The only important part for you to change is the “app_id” value, which is currently set to 94203137849, which is my application ID.

You don’t need the <div> like that post instructed, it’s just for styling, what you really need is the url inside the <iframe>.

It involves creating a Facebook application, which has evolved since the last time I touched it (to create a voting application). It doesn’t even require you to write a single line of FBML like before, but just point-and-click. The trick leverages the fact that the Facebook applications for devices utilize the same framework, and hence by making your own application, you con edit its name to modify the “via…” part to anything you’d like. Here, I made an application with the name “iPhone 4”. Click here to try it.

Now you know what to do when iPhone 5 prototypes leak out ;))

Buying an iPad is not the only way to impress your folks ;))