1D0-635 · Question #23
Consider the following code: <script type="text/javascript"> var v1 = "alpha"; function f () { var v2 = "bravo"; alert (v1 + ", " + v2); } f(); v1="charlie"; alert (v1 + ", " + v2); </script> What…
The correct answer is B. An alert box displaying alpha, bravo followed by an error. See the full explanation below for the reasoning.
Question
Consider the following code:
<script type="text/javascript"> var v1 = "alpha"; function f () { var v2 = "bravo"; alert (v1 + ", " + v2); } f(); v1="charlie"; alert (v1 + ", " + v2); </script> What is the expected result when you run this script in the browser?Options
- AAn alert box displaying charlie, bravo
- BAn alert box displaying alpha, bravo followed by an error
- CTwo alert boxes displaying alpha, bravo and alpha, bravo respectively
- DTwo alert boxes displaying alpha, bravo and charlie, bravo respectively, followed by an error
How the community answered
(28 responses)- A4% (1)
- B71% (20)
- C7% (2)
- D18% (5)
Community Discussion
4B is correct. The first alert fires inside f() where both v1 ("alpha") and v2 ("bravo") are in scope, so you see "alpha, bravo", but then the script tries to access v2 outside the function where it was declared, and since v2 is function-scoped it simply does not exist there, throwing a ReferenceError before any second alert can display.
B is right. v2 dies when f() returns, so the last alert throws a ReferenceError.
Pretty sure v2 stays "bravo" and v1 never updates before both alerts.
Anjali, v2 does get reassigned before the second alert fires, so it prints the updated value, which is exactly what B captures. The sequence matters here, and the alerts do not both precede that assignment.