Q
Which of the following methods can help in avoiding global variables?

Answer & Solution

Answer: Option D
Solution:
Encapsulating code in functions, using objects as namespaces, and using ES6 modules can help in avoiding global variables.
Related Questions on Average

What is the output of typeof window in a browser environment?

A). object

B). undefined

C). function

D). global

What is the purpose of the global object in JavaScript?

A). To store local variables

B). To provide a namespace for global variables and functions

C). To define constants

D). To execute code in strict mode

Which statement is true about global variables in JavaScript?

A). They are not accessible inside functions

B). They can be accessed and modified from any part of the code

C). They are constants

D). They can only be read, not modified

How can you access a global variable inside a function if it has the same name as a local variable?

A). By using the window object

B). By using the global object

C). By using a different name for the global variable

D). By using the this keyword

Can a global variable be accessed inside a function?

A). Yes

B). No

C). Only if passed as a parameter

D). Only if defined with var

What happens if you declare a variable without var, let, or const inside a function?

A). It becomes a global variable

B). It becomes a local variable

C). It throws an error

D). It becomes a constant

Which keyword is used to declare a variable in the global scope?

A). let

B). var

C). const

D). function

How can you avoid global scope pollution?

A). By using local variables

B). By using IIFE (Immediately Invoked Function Expressions)

C). By using modules

D). All of the above

What keyword is used to ensure a variable is block-scoped?

A). var

B). global

C). let

D). window

What is the output of console.log(globalVar); if globalVar = 'Hello'; is assigned inside a function without using var, let, or const?

A). Hello

B). undefined

C). error

D). null