How to Create a Baseball Game in JavaScript?

Estimated read time 2 min read

Creating a full-fledged baseball game in JavaScript would require a lot of code and can be a complex project, but here’s a simple example of a basic JavaScript program that simulates a single at-bat in a baseball game:

function playAtBat(strikeCount, ballCount) {
  if (strikeCount === 3) {
    return "Strikeout!";
  } else if (ballCount === 4) {
    return "Walk!";
  } else {
    let result = Math.random();
    if (result < 0.5) {
      return "Strike!";
    } else {
      return "Hit!";

let strikes = 0;
let balls = 0;

while (strikes < 3 && balls < 4) {
  let atBatResult = playAtBat(strikes, balls);
  if (atBatResult === "Strike!") {
  } else if (atBatResult === "Ball!") {
  } else {

In this example, the playAtBat function simulates a single at-bat in a baseball game. It takes two parameters, strikeCount and ballCount, which represent the current count of strikes and balls in the at-bat. The function first checks if the player has already accumulated 3 strikes (in which case they strike out) or 4 balls (in which case they walk), and returns the appropriate result. If neither of those conditions are met, the function generates a random number and returns either “Strike!” or “Hit!” based on the result.

The while loop is used to keep playing at-bats until either the player strikes out or walks. On each iteration of the loop, the result of the at-bat is logged to the console, and the count of strikes or balls is updated based on the result of the at-bat.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply