Key to ‘JavaScript Puzzlers'(3)

4.What is the result of this expression? (or multiple ones)

1
2
3
4
5
6
7
var END = Math.pow(2, 53);
var START = END - 100;
var count = 0;
for (var i = START; i <= END; i++) {
count++;
}
console.log(count);

A 0

B 100

C 101

D other

Correct answer is D.253 is the largest number in javascript,so that i never become lager than START.This code will cause infinite loop.

5.What is the result of this expression? (or multiple ones)

1
2
3
var ary = [0,1,2];
ary[10] = 10;
ary.filter(function(x) { return x === undefined;});

A [undefined x 7]

B [0,1,2,10]

C []

D [undefined]

C is correct answer.The ary looks like [0,1,2,undefined x 7,10] , but in fact array.prototype.filter() ignore undefined element.So it returned [] > See more information about array.prototype.filter()

6.What is the result of this expression? (or multiple ones)

1
2
3
4
5
var two   = 0.2
var one = 0.1
var eight = 0.8
var six = 0.6
[two - one == one, eight - six == two]

A [true,true]

B [false,false]

C [true,false]

D other

Is C.

Javascript hasn't ability of precise calculation,so that float number will be calculated in a imprecise mode.

> 0.8-0.6 = 0.20000000000000007

Specially, 0.2-0.1 = 0.1

7.What is the result of this expression? (or multiple ones)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function showCase2(value) {
switch(value) {
case 'A':
console.log('Case A');
break;
case 'B':
console.log('Case B');
break;
case undefined:
console.log('undefined');
break;
default:
console.log('Do not know!');
}
}
showCase2(String('A'));

A Case A

B Case B

C Do not know!

D undefined

swith() method uses '===' to judge condition,new String(A) construct a new string object,

new String('a') == 'a' but new String('a') !== 'a'.

So this question's answer is C

let a = new String("b")

typeof a === 'object'

8.What is the result of this expression? (or multiple ones)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function showCase2(value) {
switch(value) {
case 'A':
console.log('Case A');
break;
case 'B':
console.log('Case B');
break;
case undefined:
console.log('undefined');
break;
default:
console.log('Do not know!');
}
}
showCase2(String('A'));

A Case A

B Case B

C Do not know!

D undefined

Correct is A.

String('A') === 'A'

let a = String('b')

typeof a === 'string'