Bird
0
0

Given this code snippet for a board and pieces, what will be the output of console.log(board.pieces[0].type);?

medium📝 Analysis Q13 of 15
LLD - Design — Chess Game
Given this code snippet for a board and pieces, what will be the output of console.log(board.pieces[0].type);?
class Piece {
  constructor(type, position) {
    this.type = type;
    this.position = position;
  }
}
class Board {
  constructor() {
    this.pieces = [];
  }
  addPiece(piece) {
    this.pieces.push(piece);
  }
}
const board = new Board();
board.addPiece(new Piece('Knight', 'B1'));
Aundefined
B"B1"
CError: pieces is not defined
D"Knight"
Step-by-Step Solution
Solution:
  1. Step 1: Understand object creation and storage

    A new Piece with type 'Knight' and position 'B1' is created and added to board.pieces.
  2. Step 2: Access the first piece's type

    board.pieces[0] refers to the first piece, so board.pieces[0].type is 'Knight'.
  3. Final Answer:

    "Knight" -> Option D
  4. Quick Check:

    First piece type = 'Knight' [OK]
Quick Trick: First piece type is stored in pieces[0].type [OK]
Common Mistakes:
  • Confusing position with type
  • Assuming pieces array is empty
  • Expecting an error due to missing pieces

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes