February 13, 2010 at 11:00pm
JavaScript Casting to Number Quiz
Today I was playing with JavaScript again, and as result a small quiz was born. Hope you’ll enjoy.
-
var i;
alert(++i);
- Error
- 1
- NaN
- undefined
-
var i = null;
alert(++i);
- Error
- 1
- NaN
- undefined
-
var i = {};
alert(++i);
- Error
- 1
- NaN
- undefined
-
var i = "";
alert(++i);
- Error
- 1
- NaN
- undefined
-
var i = "0";
alert(++i);
- Error
- 1
- NaN
- undefined
-
var i = "a";
alert(++i);
- Error
- 1
- NaN
- undefined
-
var i = false;
alert(++i);
- Error
- 1
- NaN
- undefined
Answers:
- NaN (undefined + number == NaN)
- 1 (null is casted to 0)
- NaN (object + number == NaN, except nulls)
- 1 (empty string is casted to 0)
- 1 (string “0” is casted to 0)
- NaN (string with not a number is casted to NaN)
- 1 (booleans are casted to numbers: false to 0 and true to 1)
February 12, 2010 at 12:29pm
Small bookmarklet for StackOverflow.com
Like most of StackOverflow regular users I have Interesting and Ignored tags. But when I ignore something, I don’t want to see it at all. So, I’ve made the following bookmark:
Name: StackOverflow.strip!
Address: javascript:%20$(“.question-summary.narrow:not(.tagged-interesting)”).remove();$(“.tagged-ignored”).remove()
And now when I open StackOverflow, it looks like this:

Then I click on my bookmarklet, and ta-da:

In the bookmarklet I’ve used JQuery due to StackOverflow uses JQuery.
February 11, 2010 at 11:24am
JavaScript magic - Hoisting
Recently I’ve faced with an interesting quiz:
var a = "a";
function b() {
if (false) {
var a = "b";
}
alert(a);
}
b();
What would be alerted?
- “a”
- “b”
- “undefined”
- Error
Actually that code is equal to the following:
var a = "a";
function b() {
var a; // here we declare new function scope variable a,
// and it's default value is undefined
if (false) {
a = "b"; // due to the if-condition this code will be never executed
}
alert(a); // so we alert the local variable's value
}
b();
The right answer is “undefined”.