What is the expected result when the following script is run in the browser? In a script where a global variable v1 is initially set to 'Blue', a function assigns this.v1 = 'Green' and is invoked, followed by alert(v1). What is the outcome of running the script?

Prepare for the uCertify CIW Advanced HTML5 and CSS3 Specialist Exam. Dive into essential topics with flashcards and multiple-choice questions. Enhance your understanding with hints and explanations for each question. Pass your exam confidently!

Multiple Choice

What is the expected result when the following script is run in the browser? In a script where a global variable v1 is initially set to 'Blue', a function assigns this.v1 = 'Green' and is invoked, followed by alert(v1). What is the outcome of running the script?

Explanation:
Global variables are properties of the browser’s global object (window). When a global variable v1 is initially set to 'Blue', it becomes window.v1. Inside a function, this refers to the global object in non-strict mode, so this.v1 = 'Green' updates the same property, making v1 now 'Green'. If the function alerts v1 after that change, it will show Green, and the subsequent alert outside the function will also show Green. So you end up with two alerts, both displaying Green.

Global variables are properties of the browser’s global object (window). When a global variable v1 is initially set to 'Blue', it becomes window.v1. Inside a function, this refers to the global object in non-strict mode, so this.v1 = 'Green' updates the same property, making v1 now 'Green'. If the function alerts v1 after that change, it will show Green, and the subsequent alert outside the function will also show Green. So you end up with two alerts, both displaying Green.

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy