 |
February 28th, 2008 | by Jevgeni Kabanov |
|
I have just attended a great course on JavaScript soft typing by Peter Thiemann. No doubt I’ll write more about it later, but today I want to show how fun and quirky can JavaScript be.
Note that all puzzles are given in succession and every next one includes all the code of the previous ones. Also note that I tested the puzzles in Mozilla Rhino, and can’t be held responsible for how standards non-compliant browsers (read Internet Explorer) will behave.
Puzzle 1
> var obj = {x : 1}
What are the values of
1) obj.y
2) print(obj.y)
3) obj.y.z
[Answer]
1) Value is undefined
2) Prints "undefined"
3) Runtime error
Absent property values will return undefined in JavaScript. Undefined values can be further converted into strings (“undefined”), numbers, bool values and objects. However accessing undefined object properties raises one of the only two JavaScript runtime errors.
Puzzle 2
> var x = "x"
> obj.undefined = "gotcha"
What are the values of
1) obj[x]
2) obj[obj.y]
[Answer]
1) 1
2) "gotcha"
As I mentioned already undefined converts to “undefined” when a string is expected.
Puzzle 3
> var a = 17
> a.x = 42
What are the values of
1) a.x
[Answer]
1) undefined
Every value in JavaScript can be converted to an object. In case of numbers it is autoboxed into a Number object. However that object is discarded immediately, as no references to it exist and a fresh one is created for the property access.
Puzzle 4
> var flag = new Boolean(false);
> result = flag ? true : false;
What are the values of
1) result
[Answer]
1) true
Objects are converted to booleans by treating every defined object as true.
Puzzle 5
> function f() {return this.x}
What are the values of
1) f()
2) obj.f = f; obj.f()
3) new f()
[Answer]
1) x
2) 1
3) [object Object]
Functions can be used in three different settings and “this” is bound accordingly:
- If the function is called directly by name, “this” refers to the global context and “this.x” to the global variable “x”.
- If the function is called as a method field, “this” refers to enclosing object instance and “this.x” to object property “x”.
- If the function is called by a constructor, “this” refers to the newly created object. However if the function returns undefined, the result of the function will still be the newly constructed object.
Puzzle 6
> function g1() {
> u = 2;
> print(u);
> var u;
> u = 3;
> print(u);
> }
>
> function g2() {
> u = 4;
> print(u);
> eval("var u");
> u = 5;
> print(u);
> }
> u = 1;
> g1();
> print(u);
> g2();
> print(u);
1) What values are printed out?
[Answer]
1) 2, 3, 1, 4, 5, 4
If “var x” is present anywhere in the function body, the variable will be treated as a local variable, shadowing the global one. However, if you evaluate “var x” dynamically it will be treated as local variable only after the definition point.
Posted in creative | View Comments