Мыслепомойка

Java, Ruby, git, MacOSX

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.

  1. var i; alert(++i);
    1. Error
    2. 1
    3. NaN
    4. undefined
  2. var i = null; alert(++i);
    1. Error
    2. 1
    3. NaN
    4. undefined
  3. var i = {}; alert(++i);
    1. Error
    2. 1
    3. NaN
    4. undefined
  4. var i = ""; alert(++i);
    1. Error
    2. 1
    3. NaN
    4. undefined
  5. var i = "0"; alert(++i);
    1. Error
    2. 1
    3. NaN
    4. undefined
  6. var i = "a"; alert(++i);
    1. Error
    2. 1
    3. NaN
    4. undefined
  7. var i = false; alert(++i);
    1. Error
    2. 1
    3. NaN
    4. undefined

Answers:

  1. NaN (undefined + number == NaN)
  2. 1 (null is casted to 0)
  3. NaN (object + number == NaN, except nulls)
  4. 1 (empty string is casted to 0)
  5. 1 (string “0” is casted to 0)
  6. NaN (string with not a number is casted to NaN)
  7. 1 (booleans are casted to numbers: false to 0 and true to 1)

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?

  1. “a”
  2. “b”
  3. “undefined”
  4. 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”.