Debugging JavaScript can be a tedious process. Especially when debugging a function that is called many times in an application. There may be some kind of utility function in an app that processes data, but there’s a bug with one of the values.
In order to debug the function you’d open up Chrome or IE’s Dev Tools and throw in a breakpoint. If the function being debugged is used in many areas, you’ll have to hit continue multiple times to get to the specific case needed.
There are two different ways to avoid this problem.
Say you have the following code.
var process = function( obj ) {
var type = Object.prototype.toString.call( obj );
return type;
};
console.log( process({}) );
console.log( process([]) );
console.log( process("something") );
console.log( process(2) );
The process function gets called 4 times here. What if while debugging, only the case in which the object is of the type String is needing to be debugged?
The first way to do this is with just code. The debugger; is a statement in JavaScript that will trigger a breakpoint in the code. By putting debugger into the code, the execution will pause at that line. The debugger can also be wrapped with a conditional statement that only runs when the condition is true.
var process = function( obj ) {
var type = Object.prototype.toString.call( obj );
if ( ~type.indexOf( "Str" ) ) {
debugger;
}
return type;
};
Now the debugger will only be hit when the type is of “String”.
The other way to set a conditional breakpoint is with the browser’s development tools.
In Chrome…
And in IE10, and I’m pretty sure 9 also.
UPDATE 2/25/2013 several readers asked me to point out that Firefox also supports this feature…
That can definitely be a time saver!
Today I was publishing stuff to npm and came across a situation in which I typed the wrong user account for my local mahcine’s npm.
I typed npm adduser jcreamer898 and then realized it was supposed to be “jcreamer”.
After a few minutes of digging I figured out that there’s a file in my home directory called .npmrc that gets created when you run adduser.
So I renamed that file, to old.npmrc then ran npm adduser jcreamer and voila!
I wrote a few Sublime Text 2 snippets the other day that I thought I would share with the world, I’ll probably add some more to this post over time as snippets are super easy to create, and super helpful!
First one is for jQuery plugins, and is based on http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/ thanks to Addy Osmani.
<snippet>
<content><![CDATA[
(function ( \$, window, document, undefined ) {
// Create the defaults once
var pluginName = "${1:name}",
defaults = {
propertyName: "value"
};
// The actual plugin constructor
function ${2:snippet}( element, options ) {
this.element = element;
this.options = \$.extend( {}, defaults, options) ;
this._defaults = defaults;
this._name = pluginName;
this.init();
}
\$.extend(${2:snippet}.prototype, {
init: function () {
}
});
\$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!\$.data(this, pluginName)) {
\$.data(this, pluginName,
new ${2:snippet}( this, options ));
}
});
};
\$.fn[ pluginName ].defaults = defaults;
})( jQuery, window, document );
]]></content>
<!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
<tabTrigger>jqplug</tabTrigger>
<!-- Optional: Set a scope to limit where the snippet will trigger -->
<scope>source.js</scope>
</snippet>
And here’s another for RequireJS plugins.
<snippet>
<content><![CDATA[
define(['${1:deps}'], function (${2:args}) {
});
]]></content>
<!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
<tabTrigger>def</tabTrigger>
<!-- Optional: Set a scope to limit where the snippet will trigger -->
<scope>source.js</scope>
</snippet>
There ya go! More to come hopefully…
Console.log
<snippet>
<content><![CDATA[
console.log("${1:message}")
]]></content>
<!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
<tabTrigger>log</tabTrigger>
<!-- Optional: Set a scope to limit where the snippet will trigger -->
<scope>source.js</scope>
</snippet>
New HTML Page
<snippet> <content><![CDATA[ <!DOCTYPE html> <html> <head> <title></title> <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;"> <link rel="shortcut icon" href="/favicon.ico"> <link rel="apple-touch-icon" href="/apple-touch-icon.png"> <link rel="stylesheet" href="style.css"> </head> <body> </body> </html> ]]></content> <!-- Optional: Set a tabTrigger to define how to trigger the snippet --> <tabTrigger>htmlp</tabTrigger> <!-- Optional: Set a scope to limit where the snippet will trigger --> <--<scope>source.html</scope>--> </snippet>
This is a really quick post, just thought it was useful enough to post.
There are times with jQuery where I find myself needing to get the html of an entire item.
For example…
// somehtml.html
<div class="whatever">I want more than this html</div>
// somejs.js
// Gives me only "I want more than this html", but I want more...
$('.whatever').html();
Use the following quick function and you’ll have a string representing not only the innerHTML, but also the html of the actual selected element(s).
jQuery.fn.toHtmlString = function () {
return $('<div></div>').html($(this).clone()).html();
};
// Now I have"<div class="whatever">I want more than this html</div>"...
$('.whatever').toHtmlString();
Espresso tip of the day!
Every now and again you come across something really useful that you just have to share.
A few minutes ago that happened to me…
I had a bunch of code that looked like…
var js = @Bundle.Javascript()
.Add("script1.js")
.Add("script2.js")
.Add("script3.js")
.Add("script4.js");
// .... many more ....
And I needed to remove the .Add in place of actual script tags.
Of course I could have just manually done it, but I figured… I am smarter then all that!
So I hit Ctrl + h in Visual Studio to pull of Quick Replace and punched in a regex to find all of my .Adds.
Next, in VS Quick Replace you can use curly braces in your regex to capture stuff. So, my regex became…
\.Add\({.*}\)
Then you can use a \1 in the replace with to place the captured expression in the replace string.
That’s it! Thought that was worth sharing…
JSON has rapidly grown arguably the most popular way to transfer data via API’s. It’s fast, simple, and most every language supports it. ASP.net has a few things like the JavaScript Deserializer Class that do a decent job, but one of the better tools available is JSON.net.
What a better way to test it than to use a real world example. StackOverflow has a public facing JSON api available at http://api.stackoverflow.com/1.1/ so I’ll show how to consume that one.
First, fire up whatever sort of app you want and then head to the Tools –> Library Package Manager –> Package Manager Console (aka. NuGet) and type in Install-Package Newtonsoft.Json
After some NuGet-y magic you’ll have JSON.net at your finger tips.
For starters we’ll consume the Users method of the API. Hitting the Url, http://api.stackoverflow.com/1.1/users/558672 It looks like…

The fastest way to consume it with JSON.net is by using the JsonConvert.DeserializeAnonymousType method.
var client = new WebClient();
byte[] response = client.DownloadData("http://api.stackoverflow.com/1.1/users/558672");
var decompress = new GZipStream(new MemoryStream(response), CompressionMode.Decompress);
var reader = new StreamReader(decompress);
string ret = reader.ReadToEnd();
var stackResponse = new
{
total = 0,
page = 0,
pagesize = 0,
users = new[]
{
new {
user_id = 0,
user_type = "",
creation_date = "",
display_name = "",
reputation = 0,
email_hash = "",
age = 0,
last_access_date = 0,
website_url = "",
location = "",
about_me = "",
question_count = 0,
answer_count = 0,
view_count = 0,
up_vote_count = 0,
accept_rate = 0,
bagde_counts = new {
gold = 0,
silver = 2,
bronze = 9
}
}
}
};
var stackUser = JsonConvert.DeserializeAnonymousType(ret, stackResponse);
One thing to note is that StackOverflow Gzips all of their API responses, that’s what all that decompress stuff is about. So, THAT is it as far as the quickest way to consume a JSON Api with JSON.net.
The next more involved way to consume the API is to create your own classes that mirror the structure of the API and deserialize the response into them. This can look a variety of ways potentially, but here is my implementation.
public class StackUser : StackBase
{
[JsonProperty("user_id")]
public int UserId { get; set; }
[JsonProperty("user_type")]
public string UserType { get; set; }
[JsonProperty("display_name")]
public string DisplayName { get; set; }
[JsonProperty("reputation")]
public int Reputation { get; set; }
[JsonProperty("email_hash")]
public string Email { get; set; }
[JsonProperty("age")]
public int Age { get; set; }
[JsonProperty("last_access_date")]
public int LastAccessDateInt { get; set; }
[JsonProperty("website_url")]
public string Website { get; set; }
[JsonProperty("location")]
public string Location { get; set; }
[JsonProperty("about_me")]
public string AboutMe { get; set; }
[JsonProperty("question_count")]
public int QuesionCount { get; set; }
[JsonProperty("answer_count")]
public int AnswerCount { get; set; }
[JsonProperty("view_count")]
public int ViewCount { get; set; }
[JsonProperty("up_vote_count")]
public int UpVoteCount { get; set; }
[JsonProperty("down_vote_count")]
public int DownVoteCount { get; set; }
[JsonProperty("accept_rate")]
public int AccpetRate { get; set; }
[JsonProperty("association_id")]
public Guid AssociationId { get; set; }
[JsonProperty("badge_counts")]
public Dictionary Badges { get; set; }
}
This class represents all of the properties for a User. The JsonProperty attribute specifies what the actual property looks like in the JSON response.
public interface IUserRepository
{
StackUser GetUserById(params string[] ids);
}
public class Users : StackRepository<UserResponse>, IUserRepository
{
public Users()
{
Method = "users";
}
public StackUser GetUserById(params string[] ids)
{
var userResponse = Get(ids);
return userResponse.Users.FirstOrDefault();
}
}
public class StackResponse : IStackResponse
{
public int Total { get; set; }
public int Page { get; set; }
public int PageSize { get; set; }
}
public class UserResponse : StackResponse
{
public List Users { get; set; }
}
Here I created a UsersRepository to consume all of the methods available for users and declared UsersResponse and a base StackResponse for the paging information that comes back on every request. Then within the UserResponse I get back the StackUser object off of UserResponse.Users
public abstract class StackRepository : IStackRepository
{
public string Method { get; set; }
public RequestOptions Options { get; set; }
private const string ApiUrl = "http://api.stackoverflow.com/1.1/";
public string Request(string request, RequestOptions options = null)
{
var client = new WebClient();
var stackRequest = new StringBuilder(ApiUrl + request);
byte[] response = client.DownloadData(stackRequest.ToString());
if(response == null)
{
throw new Exception(string.Format("No response from request {0}", request));
}
var decompress = new GZipStream(new MemoryStream(response), CompressionMode.Decompress);
var reader = new StreamReader(decompress);
string ret = reader.ReadToEnd();
return ret;
}
public T Get(params string[] ids)
{
var response = Request(Method + string.Join(",", strings);
return Deserialize(response);
}
public T Deserialize(string response)
{
return JsonConvert.DeserializeObject(response);
}
}
public class StackOverflow : IStackOverflow
{
IUserRepository _userRepo;
public StackOverflow(IUserRepository userRepository)
{
_userRepo = userRepository;
}
public StackUser GetUserById(params string[] ids)
{
var users = _userRepo.GetUserById(ids);
return users;
}
}
The StackRepository class here takes in a Generic class that will represent the type of Response that will be returned from the Api, such as the UserResponse that I created above. To use the StackOverflow object, just do this…
var stackOverflow = new StackOverflow();
var user = stackOverflow.GetUserById("558672");
So that is the slightly more complicated way to do it. It takes a little bit more setup, but it makes it a little bit easier to work with and makes the objects re-usable.
Have fun with JSON.net!
UPDATE 2/8/2012
As per a guest recommendation in the comments, there actually is a third way to deserialize the data.
var client = new WebClient();
var stackRequest = new StringBuilder(ApiUrl + request);
byte[] response = client.DownloadData(stackRequest.ToString());
if(response == null)
{
throw new Exception(string.Format("No response from request {0}", request));
}
var decompress = new GZipStream(new MemoryStream(response), CompressionMode.Decompress);
var reader = new StreamReader(decompress);
string ret = reader.ReadToEnd();
dynamic userResponse = JObject.Parse(ret);
var displayName = userResponse.users[0].display_name;
Console.Write(displayName);
So there you go, 3 ways to use JSON.net to work with a JSON Api!
Minifying JavaScripts has many benefits. A few advantages are it reduces the amount of code the user has to download, removes unnecessary comments, and reduces the number of Http requests. There are many minify-ers out there, things such as YUI Compressor, JSMin, Google Closure Compiler, and UglifyJS.
I recently started using the standalone UglifyJS tool that can run in NodeJS. This makes the tool available via command prompt as well as accessing it inside of Node applications with require.
To use Uglify in Windows. First, download and install NodeJS. Once it is installed, you can then run applications in Command Prompt simply by typing node. It installs by default into C:\Program Files\NodeJS or C:\Program Files(x86)\NodeJS on a 64-bit machine.
It drops the node.exe, and the npm.bat file into that directory and makes it available in CMD by adding it to your %PATH%.
NPM is the Node Package Manager that was just recently made available for Windows. It allows you to download Node packages to be easily used in your projects.
The next step is to install UglifyJS and make it global so it’s available everywhere.
Open Command Prompt and run…
npm -g install uglify-js
This put’s the files for Uglify in the %AppData% file, usually around C:\Users\{username}\AppData\Roaming\npm\
As of 1/9/2012, there is a slight bug in the command to actually run Uglify, so in order to fix it, navigate to the folder just mentioned and find uglifyjs.cmd and replace it with…
:: Created by npm, please don't edit manually. @IF EXIST "%~dp0"\"node.exe" ( "%~dp0"\"node.exe" "%~dp0\.\node_modules\uglify-js\bin\uglifyjs" %* ) ELSE ( node "%~dp0\.\node_modules\uglify-js\bin\uglifyjs" %* )
Now, you will be able to just run Uglify by…
cd c:\place\where\files\are\ uglifyjs -o myFile.build.js myFile.js
And wham bam, you’ll find a nicely compressed file. NOTE: You also may need to restart the computer. Sometimes the changes to the path don’t kick in right away. You can string along as many files as you need to compress; the –o flag tells Uglify where to place the built file. Then you could save the commands out to some build.bat file and run it at your plessure.
When working with Entity Framework Code First, the database get’s generated for you… Duh!
You have control over several aspects of how this database get’s created.
First off are Data Annotations, such as Required, DefaultValue, ForeignKey, Key, etc.
Second is the Fluent Api which allows you to tap into the creation of the Database and remove all of those attributes off of your data classes.
You can specify the name of the database by passing a Name, or even a connectionString into the base constructor of your DbContext.
public class MyContext : DbContext
{
public MyContext()
base: ("MyDbName")
{}
}
Lot’s of different control over the DB.
However, one thing that seems to be left out for now is explicitly naming your Primary Key constraints. By default, they come out looking something like… PK_USERS_FBC301?!?!?!?
I think this is a default of SQL more than Code First’s fault or anything, but none the less it is kinda nasty.
The only way I have found to fix this problem is to tap into the Initialize method of the Context using either DropCreateDatabaseAlways, DropCreateDatabaseIfModelChanges, or by implementing your own version of IDatabaseInitializer. I did it like this…
// Somewhere in Global.asax
Database.SetInitializer(new DbInitializer());
// DbInitializer
public class DbInitializer : IDatabaseInitializer<MyContext>
{
public void InitializeDatabase(MyDbcontext context)
{
if (context.Database.Exists())
{
if (!context.Database.CompatibleWithModel(true))
{
string singleUserModeCommand =
string.Format("ALTER DATABASE [{0}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE",
context.Database.Connection.Database);
if (context.Database.Exists())
{
context.Database.ExecuteSqlCommand(singleUserModeCommand);
context.Database.Delete();
}
context.Database.Create();
Seed(context);
}
}
else
{
context.Database.Create();
Seed(context);
}
}
protected void Seed(MyDbContext context)
{
FixPrimaryKeyConstraints(context);
}
private void FixPrimaryKeyConstraints(MyDbContext context)
{
const string sql =
@" SET NOCOUNT on
DECLARE @cnt int
DECLARE @table varchar(128)
DECLARE @cmd varchar(500)
--create table #rowcount (tablename varchar(128), rowcnt int)
DECLARE tables cursor for
SELECT table_name from information_schema.tables
WHERE table_type = 'base table'
ORDER BY table_name
OPEN tables
FETCH NEXT FROM tables into @table
WHILE @@fetch_status = 0
BEGIN
DECLARE @TableName NVARCHAR(128)
DECLARE @IndexName NVARCHAR(128)
DECLARE @OldName NVARCHAR(128)
DECLARE @NewName NVARCHAR(128)
SELECT @TableName = @table
SELECT @IndexName = C.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ,INFORMATION_SCHEMA.KEY_COLUMN_USAGE C
WHERE pk.TABLE_NAME = @TableName
AND CONSTRAINT_TYPE = 'PRIMARY KEY'
AND C.TABLE_NAME = PK.TABLE_NAME
AND C.CONSTRAINT_NAME = PK.CONSTRAINT_NAME
SELECT @OldName = @TableName + '.' + @IndexName
SELECT @NewName = 'PK_' + @TableName
exec sp_rename @OldName, @NewName, 'INDEX'
FETCH NEXT FROM tables into @table
END
CLOSE tables
DEALLOCATE tables";
context.Database.ExecuteSqlCommand(sql);
}
}
This file does a few things. First it detects changes to the DB, forces a drop if neccessary, then runs the seed.
The seed then calls the FixPrimaryKeyConstraints which loops over all of the tables in the Database and renames them PK_TableName.
Hope you enjoyed this Espresso Tip!










