Jevgeni Kabanov

JavaScript Puzzlers

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]

Puzzle 2

> var x = "x"
> obj.undefined = "gotcha"

What are the values of

1) obj[x]
2) obj[obj.y]

[Answer]

Puzzle 3

> var a = 17
> a.x = 42

What are the values of

1) a.x

[Answer]

Puzzle 4

> var flag = new Boolean(false);
> result = flag ? true : false;

What are the values of

1) result

[Answer]

Puzzle 5

> function f() {return this.x}

What are the values of

1) f()
2) obj.f = f; obj.f()
3) new f()

[Answer]

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]

blog comments powered by Disqus