Answering Nicholas Zakas’ JavaScript quiz
February 16, 2010 by Ed Spencer · Leave a Comment
A current meme that’s floating around the JavaScript geek corner of the internet is setting quizzes on some of the more unusual aspects of JavaScript. This time round Nicholas Zakas is providing the entertainment, so I thought I’d provide some answers. Let’s get started:
Question 1
Question 1 looks like this:
var num1 = 5,
num2 = 10,
result = num1+++num2;
We’re asked what the values of result, num2 and num1 are. First, let’s deconstruct what that +++ is doing. There is no +++ operator in JavaScript – instead we have a num1++ followed by a + num2.
JavaScript has two ways of incrementing a number by 1 – we can either put the ++ before the variable or after it. The variable is incremented either way – the only difference is what is returned. ++10 returns 11, whereas 10++ returns 10:
var a = 10; var b = a++; //a is set to 11 now, but b is set to 10 var c = ++a; //a is set to 12 now, c is also set to 12
So ‘result’ is the sum of num1++ (which is 5) and num2, which is 10, so result equals 15. num2 remains at 10 as it was not modified. num1 is now equal to 6 because we incremented it by 1, though the incrementation did not affect the sum passed to result.
Question 2
var x = 5,
o = {
x: 10,
doIt: function doIt(){
var x = 20;
setTimeout(function(){
alert(this.x);
}, 10);
}
};
o.doIt();
We’re asked what is alerted. This is mostly smoke and mirrors – there’s some indirection with all the duplicate names but the important thing here is the setTimeout. The function we pass to setTimeout gets run in the global scope, meaning ‘this’ refers to the window object. Declaring x as a variable in the global scope (var x = 5) is the same as setting window.x = 5, so 5 is alerted.
Question 3
var num1 = "10",
num2 = "9";
We’re asked:
- What is the value of num1 < num2?
- What is the value of +num1 < num2?
- What is the value of num1 + num2?
- What is the value of +num1 + num2?
This question is all about type casting.
- num1 < num2 is true - if both operands are strings JavaScript will compare them alphabetically, and "10" is lower alphabetically than "9"
- +num1 < num2 is false - placing a "+" operator before a string casts it into a number, so we're actually testing 10 < "9". When testing a mixture of numbers and strings like this, everything is cast into a number, so we're testing 10 < 9, which is false
- num1 + num2 === “109″ – the plus sign can mean both addition and concatenation, depending on the operand types. Here we have 2 strings so we’re concatenating them together
- +num1 + num2 === “109″ also – again we’re casting num1 into a number, but the + operator means concatenation if at least one operand is a string
The confusion around this comes largely from the fact that the plus sign is used for both addition and concatenation in JavaScript. This causes the engine to have to test the typeof each operand and cast accordingly. All of the other math operators (e.g. /, *, % etc) cast both operands to numbers.
Question 4
var message = "Hello world!";
We’re asked:
- What is the value of message.substring(1, 4)?
- What is the value of message.substr(1,4)?
- message.substring(1, 4); //”ell”
- message.substr(1, 4); //”ello”
substring and substr do similar things. The first argument to each is the character index to start from, but whereas substring’s second argument is the character index to end at, substr’s second argument is the number of characters to return. Therefore message.substr(1, 4) will return a string of length 4, whereas message.substring(1, 4) will return a string of length 3 (4 – 1):
Question 5
var o = {
x: 8,
valueOf: function(){
return this.x + 2;
},
toString: function(){
return this.x.toString();
}
},
result = o < "9";
alert(o);
We’re asked the value of ‘result’, and what gets alerted. This requires an understanding of the special valueOf and toString functions available on every object. These functions are used internally by the JavaScript engine to pull out the best representation of an object’s value based on the situation.
When alerting a value, we want a string representation so toString is called. When comparing the value to another object, valueOf is called instead. So alert(o) alerts “8″, and result is set equal to the result of 10 < "9". The JavaScript engine will decide when to use which option, or we can specify it ourselves:
var num1 = 8, num2 = 9; num1 + num2; //17 num1.toString() + num2.toString(); //"89" num1.valueOf() + num2.valueOf(); //17
The 'result' assignment needs a little explanation. First, the engine calls valueOf on the object, which returns 10. Second, because one of the operands to the < operator is a number, the other is also cast into a number, so we are testing 10 < 9, which returns false. We could instead force it to use toString: o.toString() < "9" returns true.
Quizzes like this are great for getting your teeth into some of the guts of JavaScript, but don't mistake them for a good way to write code. The point is to demonstrate how quirky JS code can be unless you write it in a sensible way.
Ext JS is looking for a QA rockstar
January 19, 2010 by Ed Spencer · Leave a Comment
This has been cross-posted from our Open Discussion Forum.
As part of our ambition of creating the world’s best JavaScript framework, we’re looking to hire a special somebody to help maintain the high quality of our components.
While we have one eye on implementing new features and improving Ext JS’s performance, the other is on making sure what we already have still works well.
This is a difficult job and we need someone smart, focused and well versed in Ext JS. Somebody who will:
* Use our existing systems to test components as new builds of the library are landed
* Maintain a strong presence in the forums and be the first to know of any reported issues
* Respond to bug tickets such as rendering issues and broken functionality
* Totally own the Quality Assurance of Ext JS – we want your ideas and your initiative as well as your expertise with Ext
* Liaise with the core team on a daily basis
This is a full-time position, though allowances can be made for the right person. If you think you would enjoy working with Ext JS, and have what it takes to help us keep Ext at the forefront of our field, drop me a private message with the following information:
* Your name
* Email address
* Location (city, country, timezone)
* All experience with Ext JS
* Bonus points for links to open source software
JavaScript FizzBuzz in a tweet
September 17, 2009 by Ed Spencer · 17 Comments
The FizzBuzz challenge has been around a while but I stumbled across it again after reading another unique Giles Bowkett post.
If you’re not familiar with FizzBuzz, it’s a little ‘challenge’ designed to test a candidate programmer’s ability to perform a simple task. In this case, you just have to print out the numbers from 1 to 100, unless the number is a multiple of 3, when you should instead print “Fizz”, 5 in which case you print “Buzz”, or both 3 and 5 in which case you print “FizzBuzz”.
Here’s a trivial JavaScript implementation:
for (var i=1; i <= 100; i++) {
if (i % 3 == 0) {
if (i % 5 == 0) {
console.log('FizzBuzz');
} else {
console.log('Fizz');
}
} else if (i % 5 == 0) {
console.log('Buzz');
} else {
console.log(i);
}
};
Pretty simple stuff, but a bit verbose. I wanted something that would fit into a tweet. It turns out that’s pretty simple – this is 133 characters including whitespace, 7 within tolerance for a twitter message:
for (var i = 1; i <= 100; i++) {
var f = i % 3 == 0, b = i % 5 == 0;
console.log(f ? b ? "FizzBuzz" : "Fizz" : b ? "Buzz" : i);
}
Which of course begs the question – just how short can a JavaScript FizzBuzz implementation be? Here’s my baseline, which is a tortured and contorted version of the above:
for(i=1;i<101;i++){console.log(i%3?i%5?i:"Buzz":i%5?"Fizz":"FizzBuzz")}
The above is 71 characters – I expect you to do better. The rules are that the only dependency is Firebug’s console.log being available, and you can’t replace ‘console.log’ for anything else.
Of course, if we did swap ‘console.log’ for ‘alert’, the whole thing would fit in a tweet twice, but that would be damn annoying.
Hint: you can take at least three more characters off the above – can you see how?
Using the ExtJS Row Editor
September 16, 2009 by Ed Spencer · 5 Comments
The RowEditor plugin was recently added to the ExtJS examples page. It works a lot like a normal Grid Editor, except you can edit several fields on a given row at once before saving.
This neatly solves the problem of adding a new row to an editor grid, entering data into the first field and finding it save itself straight away, which is rarely desired. In this fashion we can provide full CRUD for simple models in a single page.
Installation
You’ll need to get a copy of the javascript, css and images from the server. This is a bit of a pain. If you still have the ExtJS SDK around you can find these in the examples folder, if not you can get each file as follows:
Grab the plugin JS file below and put it where you usually put your .js files:
http://www.extjs.com/deploy/dev/examples/ux/RowEditor.js
This needs to go with your other stylesheets, usually in a directory called ‘css’:
http://www.extjs.com/deploy/dev/examples/ux/css/RowEditor.css
Download these two images and put them into your existing ‘images’ folder (the same place the other ExtJS images live):
http://www.extjs.com/deploy/dev/examples/ux/images/row-editor-bg.gif
http://www.extjs.com/deploy/dev/examples/ux/images/row-editor-btns.gif
Include the .js and .css files on your page and you should be ready to go.
Usage
RowEditor is a normal grid plugin, so you’ll need to instantiate it and add to your grid’s ‘plugins’ property. You also need to define what type of Editor is available (if any) on each column:
var editor = new Ext.ux.grid.RowEditor();
var grid = new Ext.grid.GridPanel({
plugins: [editor],
columns: [
{
header : 'User Name',
dataIndex: 'name',
editor : new Ext.form.TextField()
},
{
header : 'Email',
dataIndex: 'email',
editor : new Ext.form.TextField()
}
]
... the rest of your grid config here
});
RowEditor defines a few events, the most useful one being ‘afteredit’. Its signature looks like this:
/**
* @event afteredit
* Fired after a row is edited and passes validation. This event is fired
* after the store's update event is fired with this edit.
* @param {Ext.ux.grid.RowEditor} roweditor This object
* @param {Object} changes Object with changes made to the record.
* @param {Ext.data.Record} r The Record that was edited.
* @param {Number} rowIndex The rowIndex of the row just edited
*/
'afteredit'
All you need to do is listen to that event on your RowEditor and save your model object appropriately. First though, we’ll define the Ext.data.Record that we’re using in this grid’s store:
var User = Ext.data.Record.create([
{name: 'user_id', type: 'int'},
{name: 'name', type: 'string'},
{name: 'email', type: 'string'}
]);
And now the afteredit listener itself
editor.on({
scope: this,
afteredit: function(roweditor, changes, record, rowIndex) {
//your save logic here - might look something like this:
Ext.Ajax.request({
url : record.phantom ? '/users' : '/users/' + record.get('user_id'),
method: record.phantom ? 'POST' : 'PUT',
params: changes,
success: function() {
//post-processing here - this might include reloading the grid if there are calculated fields
}
});
}
});
The code above simply takes the changes object (which is just key: value object with all the changed fields) and issues a request to your server backend. ‘record.phantom’ returns true if this record does not yet exist on the server – we use this information above to specify whether we’re POSTing to /users or PUTing to /users/123, in line with normal RESTful practices.
Adding a new record
The example above allows for editing an existing record, but how do we add a new one? Like this:
var grid = new Ext.grid.GridPanel({
//... the same config from above goes here,
tbar: [
{
text : "Add User",
handler: function() {
//make a new empty User and stop any current editing
var newUser = new User({});
rowEditor.stopEditing();
//add our new record as the first row, select it
grid.store.insert(0, newUser);
grid.getView().refresh();
grid.getSelectionModel().selectRow(0);
//start editing our new User
rowEditor.startEditing(0);
}
}
]
});
Pretty simple stuff – we’ve just added a toolbar with a button which, when clicked, creates a new User record, inserts it at the top of the grid and focusses the RowEditor on it.
Configuration Options
Although not documented, the plugin has a few configuration options:
var editor = new Ext.ux.grid.RowEditor({
saveText : "My Save Button Text",
cancelText: "My Cancel Button Text",
clicksToEdit: 1, //this changes from the default double-click activation to single click activation
errorSummary: false //disables display of validation messages if the row is invalid
});
If you want to customise other elements of the RowEditor you probably can, but you’ll need to take a look at the source (it’s not scary).
Final Thought
RowEditor is a really nice component which can provide an intuitive interface and save you writing a lot of CRUD code. It is best employed on grids with only a few columns – for models with lots of data fields you’re better off with a full FormPanel.
I’d be pretty happy to see this included in the default ExtJS distribution, as I find myself returning to it frequently.
Moving from Blogger to Wordpress
September 14, 2009 by Ed Spencer · Leave a Comment
Over the weekend I migrated from Blogger (hosted by Google) to Wordpress (hosted by me). Overall, Wordpress feels far superior, but the migration was not without problems. Here’s a short guide to what I had to do:
Get Wordpress
First, grab the latest version of Wordpress. Being a PHP application, it just drops into a directory and works
Create a database, set config
Wordpress has a setup script but being a bit of a noob I couldn’t give it write permission to my filesystem. If you are also afflicted by such inadequacies the following steps may help you. For clarity I’ll call my DB ‘wordpress’. First, set up your database:
- mysql -u root
- CREATE DATABASE wordpress;
- GRANT ALL on wordpress.* TO ‘wordpress’@'localhost’ identified by ‘wordpress’;
You’ll need a wp-config.php file – Wordpress comes with a default one which you can copy thusly (in the root directory of your wordpress directory):
cp wp-config-sample.php wp-config.php
Now edit wp-config.php, and fill in the details to make it look a little like this:
// ** MySQL settings – You can get this info from your web host ** //
/** The name of the database for WordPress */
define(’DB_NAME’, ‘wordpress’);
/** MySQL database username */
define(’DB_USER’, ‘wordpress’);
/** MySQL database password */
define(’DB_PASSWORD’, ‘wordpress’);
/** MySQL hostname */
define(’DB_HOST’, ‘localhost’);
Hitting the site now should show a default Wordpress installation with some dummy content. Whoop.
Import from Blogger
Importing from Blogger is pleasingly simple – just use the Tools -> Import option on the menu. It’ll ask you to verify access and then pull down all your posts and comments.
It’s not perfect though – for me the post Tags were imported as Categories. To get them to be Tags again, go to the Posts -> Categories menu and use the handy Categories to Tags converter.
I found that the imported Post markup was pretty mangled (I think this is Blogger’s fault, not Wordpress’) – <br />s everywhere and no line breaks. To resolve this I cracked open mysql again and ran the following:
- use wordpress;
- UPDATE wp_posts SET post_content = REPLACE(post_content, “<br />”, “\n”);
That sorted me out alright. Next we need to set up how our permalinks work. Set this in the Settings -> Permalinks menu, and use the following format to mimic the Blogger urls:
/%year%/%monthnum%/%postname%.html
Wordpress will either write a .htaccess file for you at this point, or tell you it can’t write to the filesystem and give you a short text config which you must manually copy into a file called .htaccess.
One final thing to note is that Wordpress constructs its slug urls differently to Blogger (Wordpress would use ‘the-trouble-with-new’ vs Blogger’s ‘trouble-with-new’, for example). If you’re importing blog posts this means your urls won’t always match, so any incoming links will be broken. I couldn’t find an easier way to correct them than just copy/paste by hand – doesn’t take long though.
Syntax Highlighting
This whole step is entirely optional.
Because I’m a geek I post code fairly often. I used the SyntaxHighlighter library back in the Blogger days and wanted to keep using it. You can install the Wordpress plugin version from http://www.viper007bond.com/wordpress-plugins/syntaxhighlighter/. The old syntax didn’t seem to work, so I needed to go back into mysql and run the following:
UPDATE wp_posts SET post_content = REPLACE(post_content, "<pre name=\"code\" class=\"js\">", "[c0de language=\"js\"]"); UPDATE wp_posts SET post_content = REPLACE(post_content, "</pre>", "[/c0de]");
NOTE: So that Wordpress doesn’t interpret those tags above I’ve changed the ‘o’ in code to a ‘0′. You need to change it back
This just swaps all your old <pre name="code" class="js"> and </pre> tags for [c0de language="js"]and [/c0de] respectively. Repeat the first line for any other languages you have used (for me this was xml, css, html and ruby).
Fixing feeds
Wordpress doesn’t like the world to see your content via RSS. Odd, isn’t it? There’s an option in Settings -> Reading which claims to output the full text of each article into your feed, but it doesn’t seem to work. Instead, what you need to do is hack your theme a little. You’ll need to edit the wp-includes/feed-rss2.php file and change line 47 from <?php the_excerpt_rss() ?> to <?php the_content() ?>.
If you’re using Feedburner or similar, don’t forget to give it your new feed url too. In this case you should also update wp-content/themes/yourTheme/header.php and swap out the occurrences with your Feedburner url.
Upload and update DNS
At this point everything should be working nicely, so upload your blog folder and update your DNS settings. I’m guessing if you’re hosting Wordpress yourself you don’t need help with this. I’ve made my own blog into a git repository up on Github, allowing me to deploy any changes I make using Capistrano. It’s a nice solution – for more information see this lovely post by the gentlemen at imedo.