JavaScript Classes & OOP Quiz

JavaScript
0 Passed
0% acceptance

Work through 50 questions on class syntax, constructors, instance and static members, getters/setters, inheritance with extends/super, private fields, composition vs inheritance, using this, creating multiple instances, basic design patterns, and best practices.

50 Questions
~100 minutes
1

Question 1

What does OOP (Object-Oriented Programming) emphasize?

A
Modeling programs around objects that contain data and behavior
B
Only pure functions without state
C
Exclusively global variables
D
Inline scripting
2

Question 2

Which statement describes class declaration syntax?

A
class MyClass { ... } defines a constructor-like structure with methods
B
class is a function keyword
C
Classes run immediately
D
Classes are hoisted like function declarations
3

Question 3

What is a class expression?

A
const Foo = class { ... }
B
class expression() {}
C
function class() {}
D
var class = {}
4

Question 4

What does the constructor method do?

A
Initializes new instances when new ClassName() is invoked
B
Runs once globally
C
Defines static methods
D
Creates prototypes automatically
5

Question 5

Which of the following describes class expressions?

A
They can be anonymous or named and assigned to variables or passed around
B
They hoist like function declarations
C
They must be declared at top level only
D
They cannot extend other classes
6

Question 6

What is the difference between class declarations and expressions regarding hoisting?

A
Both are hoisted but stay in the temporal dead zone until evaluated
B
Declarations hoist fully while expressions do not
C
Expressions hoist, declarations do not
D
Neither is hoisted
7

Question 7

How do you create multiple instances from a class?

A
Call new ClassName() repeatedly with different arguments
B
Assign ClassName to multiple variables without new
C
Cloning prototypes manually
D
Using global functions
8

Question 8

Which statement about this in class methods is correct?

A
this refers to the instance on which the method is invoked
B
this is bound to the class itself automatically
C
this equals window even in strict mode
D
this is undefined in constructors
9

Question 9

What does new ClassName() return if constructor does not explicitly return an object?

A
The newly created instance
B
undefined
C
A prototype object
D
The constructor function
10

Question 10

Which best describes class expressions vs declarations for naming?

A
Class expressions can be anonymous or named; declarations must have names
B
Declarations can be anonymous
C
Expressions cannot have names
D
Both must be anonymous
11

Question 11

What does the constructor keyword define?

A
A special method in the class body executed during instantiation
B
A global function
C
An inherited method automatically
D
A static helper
12

Question 12

What does this code log?

javascript
class Person {
  constructor(name) {
    this.name = name
  }
  greet() {
    return `Hi, ${this.name}`
  }
}
const alice = new Person('Alice')
console.log(alice.greet())
A
Hi, Alice
B
undefined
C
Throws because greet missing
D
Hi, undefined
13

Question 13

What does the following demonstrate?

javascript
class Counter {
  constructor() {
    this.count = 0
  }
  increment() {
    this.count++
  }
}
const c1 = new Counter()
const c2 = new Counter()
c1.increment()
console.log(c1.count, c2.count)
A
1 0 — each instance has its own count property
B
1 1 — count shared
C
0 0 — increment failed
D
Throws because classes cannot mutate this
14

Question 14

How do you define default values for constructor parameters?

javascript
class User {
  constructor(name = 'Guest') {
    this.name = name
  }
}
const u = new User()
console.log(u.name)
A
Use default parameters; output Guest
B
Set defaults via static properties
C
Use Object.assign in constructor body always
D
Impossible without if statements
15

Question 15

What does returning an object inside constructor do?

javascript
class Example {
  constructor() {
    return { replaced: true }
  }
}
const e = new Example()
console.log(e.replaced)
A
Instances can be replaced by explicit object returns
B
Return statements are ignored
C
Throws SyntaxError
D
replaced is undefined
16

Question 16

What does this code show about this binding?

javascript
class Logger {
  constructor() {
    this.prefix = '[LOG]'
    this.log = this.log.bind(this)
  }
  log(msg) {
    console.log(this.prefix, msg)
  }
}
const logger = new Logger()
const fn = logger.log
fn('hello')
A
[LOG] hello — binding in constructor retains instance context
B
undefined hello
C
Throws because log is not a function
D
[LOG] undefined
17

Question 17

Where should per-instance mutable data typically be stored?

A
Inside the constructor and assigned to this
B
On the class prototype
C
As static properties
D
In global variables
18

Question 18

How do you define instance methods in class syntax?

A
Declare them directly inside the class body without function keyword
B
Assign functions to this.method in constructor
C
Use prototype.method = function outside class
D
Use static keyword always
19

Question 19

What is the effect of using arrow functions as class fields for methods?

A
They create per-instance bound functions, useful for callbacks but increase memory per instance
B
They become prototype methods
C
They bind to prototypes automatically
D
They are static by default
20

Question 20

Why might you avoid storing methods on this in the constructor?

A
It duplicates functions per instance, using more memory and preventing prototype sharing
B
It is illegal
C
It automatically becomes static
D
Constructors cannot assign functions
21

Question 21

What does static keyword do for class members?

A
Attaches them to the class constructor itself instead of instances
B
Makes methods private
C
Creates constants
D
Clones instances
22

Question 22

What does this static example output?

javascript
class MathUtil {
  static double(x) {
    return x * 2
  }
}
console.log(MathUtil.double(5))
A
10
B
Throws because instance needed
C
undefined
D
NaN
23

Question 23

How do getters and setters work in class bodies?

javascript
class Temperature {
  constructor(celsius) {
    this._c = celsius
  }
  get fahrenheit() {
    return this._c * 9 / 5 + 32
  }
  set fahrenheit(value) {
    this._c = (value - 32) * 5 / 9
  }
}
const temp = new Temperature(0)
temp.fahrenheit = 212
console.log(temp.fahrenheit)
A
Getters and setters act like properties; outputs 212
B
Getters require ()
C
Setters cannot assign
D
It throws
24

Question 24

Why is encapsulation useful?

A
It hides internal details and prevents external code from mutating state directly
B
It makes code slower
C
It removes the need for constructors
D
It converts classes to objects
25

Question 25

What does private field syntax (#) enforce?

javascript
class Counter {
  #value = 0
  increment() {
    this.#value++
  }
  get value() {
    return this.#value
  }
}
const c = new Counter()
c.increment()
console.log(c.value)
A
Private fields cannot be accessed outside class; outputs 1 via getter
B
Private fields accessible via c.#value
C
Private fields require proxies
D
Private fields share across instances
26

Question 26

Why might you use static properties for caching?

A
Static properties are shared across all instances, making them suitable for caches or configuration
B
Static props are reinitialized per instance
C
They cannot store data
D
They automatically persist to disk
27

Question 27

What does this getter/setter example show?

javascript
class Rectangle {
  constructor(width, height) {
    this.width = width
    this.height = height
  }
  get area() {
    return this.width * this.height
  }
  set area(value) {
    this.height = value / this.width
  }
}
const rect = new Rectangle(4, 5)
console.log(rect.area)
rect.area = 40
console.log(rect.height)
A
20 then 10 — setter adjusts internal state based on assigned value
B
Throws because area is read-only
C
0 then 0
D
Undefined outputs
28

Question 28

How do you declare getters/setters that map to private fields?

A
Use #field along with public get/set methods that interact with it
B
Use Object.definePrivate
C
Set property descriptors manually only
D
Private fields cannot have getters
29

Question 29

Why use getters for computed properties?

A
They let you compute values on demand while exposing property-like syntax
B
They make properties read-only always
C
They serialize automatically
D
They run once only
30

Question 30

Why might you use setters to validate input?

A
Setters intercept assignments, allowing type or range checks before storing data
B
Setters cannot access this
C
Setters are only for static fields
D
Setters run only during construction
31

Question 31

What does extends keyword do?

javascript
class Vehicle {}
class Car extends Vehicle {}
A
Sets up prototype inheritance from Vehicle to Car
B
Copies methods
C
Runs Vehicle constructor automatically without new
D
Prevents Car from adding methods
32

Question 32

What does super() inside a constructor call?

javascript
class Animal {
  constructor(name) {
    this.name = name
  }
}
class Cat extends Animal {
  constructor(name) {
    super(name)
    this.type = 'cat'
  }
}
const kitty = new Cat('Luna')
console.log(kitty.name, kitty.type)
A
Calls the parent constructor, allowing this to be used afterwards
B
Calls parent static methods only
C
Does nothing
D
Throws because super forbidden
33

Question 33

What does this overriding example output?

javascript
class Shape {
  area() { return 0 }
}
class Square extends Shape {
  constructor(size) {
    super()
    this.size = size
  }
  area() {
    return this.size ** 2
  }
}
const sq = new Square(4)
console.log(sq.area())
A
16
B
0
C
Throws because overriding disallowed
D
undefined
34

Question 34

How do you call a parent method from a child override?

A
Use super.methodName() inside the overriding method
B
Call this.methodName()
C
Use Parent.prototype.method.call(this)
D
Parent.method() only
35

Question 35

What does this logging example show?

javascript
class Logger {
  log(msg) {
    console.log('base', msg)
  }
}
class ColorLogger extends Logger {
  log(msg) {
    super.log(msg)
    console.log('color', msg)
  }
}
new ColorLogger().log('info')
A
base info then color info
B
color info only
C
Throws due to super usage
D
base info only
36

Question 36

What does this snippet demonstrate about instanceof?

javascript
class A {}
class B extends A {}
const obj = new B()
console.log(obj instanceof B, obj instanceof A)
A
true true — extends maintains prototype chain for instanceof checks
B
true false
C
false true
D
false false
37

Question 37

Why might you prefer composition over inheritance?

A
Composition combines small behaviors without deep hierarchies, reducing tight coupling
B
Inheritance is deprecated
C
Composition prevents code reuse
D
Inheritance cannot share state
38

Question 38

What does this composition pattern show?

javascript
const flyable = Base => class extends Base {
  fly() { return 'flying' }
}
const quackable = Base => class extends Base {
  quack() { return 'quack' }
}
class Animal {}
class Duck extends quackable(flyable(Animal)) {}
const duck = new Duck()
console.log(duck.fly(), duck.quack())
A
Mixin functions (functional composition) add behaviors without deep inheritance
B
Only fly works
C
Mixin pattern is invalid
D
Throws because multiple inheritance disallowed
39

Question 39

How does method overriding interact with polymorphism?

A
Polymorphism allows child classes to provide specific implementations while preserving a common interface
B
Overriding breaks polymorphism
C
Polymorphism requires private methods
D
Polymorphism only works with static methods
40

Question 40

What happens if super.method() is omitted in an override when needed?

javascript
class Base {
  init() {
    this.baseSet = true
  }
}
class Derived extends Base {
  init() {
    this.derivedSet = true
  }
}
const d = new Derived()
d.init()
console.log(d.baseSet, d.derivedSet)
A
baseSet is undefined because parent logic not invoked
B
baseSet true automatically
C
Throws error automatically
D
derivedSet undefined
41

Question 41

What does this private field example output?

javascript
class SecretBox {
  #secret
  constructor(value) {
    this.#secret = value
  }
  reveal() {
    return this.#secret
  }
}
const box = new SecretBox('code')
console.log(box.reveal(), Object.keys(box))
A
code [] — private fields are not enumerable or accessible via Object.keys
B
code ["#secret"]
C
undefined []
D
Throws due to # usage
42

Question 42

How do private methods differ from public ones?

A
Private methods declared with #method can only be called inside the class body; external calls cause syntax errors
B
Private methods become static automatically
C
Private methods run faster
D
Private methods are visible on the prototype
43

Question 43

What does this code show about private helpers?

javascript
class PasswordValidator {
  #sanitize(raw) {
    return String(raw).trim()
  }
  validate(raw) {
    const value = this.#sanitize(raw)
    return value.length >= 8
  }
}
const validator = new PasswordValidator()
console.log(validator.validate(' secret '))
A
true — private #sanitize is used internally and cannot be called from outside
B
Throws because #sanitize is undefined
C
false always
D
validator.#sanitize is callable externally
44

Question 44

How do you verify multiple instances stay independent?

A
Instantiate several objects and confirm each maintains its own data without cross-effects
B
Assume independence automatically
C
Use static variables only
D
Share mutable objects on prototypes
45

Question 45

Why can using class methods as event handlers require binding?

A
When passed as callbacks, methods lose their implicit this binding unless bound or written as arrow fields
B
Event handlers cannot call class methods
C
Classes run outside strict mode
D
this always points to window
46

Question 46

What does this static counter demonstrate?

javascript
class Session {
  static total = 0
  constructor() {
    Session.total += 1
  }
}
new Session()
new Session()
console.log(Session.total)
A
2 — static fields track global counts across instances
B
0 — static is per instance
C
Throws because static fields unsupported
D
undefined
47

Question 47

Which basic design pattern does the following describe: providing a single shared instance throughout the app?

A
Singleton pattern
B
Factory pattern
C
Observer pattern
D
Decorator pattern
48

Question 48

When is a factory class useful?

A
When you centralize object creation logic, possibly returning different subclasses based on input
B
When you need private fields
C
When classes must be static
D
Factories replace constructors entirely
49

Question 49

How does composition appear in class-based code?

A
By holding references to helper objects or mixins and delegating work instead of inheriting
B
By extending multiple classes simultaneously
C
By copying methods between classes
D
By using static methods only
50

Question 50

Which best practice improves class-based OOP design?

A
Prefer clear constructor arguments, keep prototypes stable, limit inheritance depth, and document how instances should be used
B
Mutate prototypes at runtime frequently
C
Store all data on static properties
D
Expose every field publicly

QUIZZES IN JavaScript