Hit Sixes with JavaScript
Clean Bowling Arrays & Objects Using Cricket Tactics!
Table of contents
- 🏏 Javascript Introduction: Code Like a Captain
- 🧩 Arrays: Your Batting Lineup
- 📋 Objects: Player Profile Cards
- What Are the Methods?
- 10 Awesome Array & Objects Methods – Your Cricket Tactics Playbook
- 1. 🏏 Squad Shuffle: push() & pop() – Adding and Removing Players from a Squad
- 2. 🎯 Batting Lineup Strategy : shift() & unshift() – Managing Batting Order
- 3. 🔄 Death Over Strategy: slice() – Selecting Key Bowlers for the Death Overs
- 4. 🏏 Deep Dive: splice() – Replacing a Player
- 5. 🔥 Strike Rate Calculator: map() – Converting Batting Scores to Strike Rates
- 6. 🎯 Economy Check: filter() – Selecting Players with an Economy Below 6
- 7. 🏆 Top Scorer Spotlight: find() – Finding the Player with the Highest Runs
- 8. 🤝 Quick Team Meeting: forEach() – How Everyone Plays a Role
- 9. 🔍 Dugout Check: includes() – Checking if a Player is Part of the Squad
- 10. 📈 Total Score Tally: reduce() – Total Score Tally
- 🏆 Conclusion: Code Like a Pro!
- Final Over Advice:
🏏 Javascript Introduction: Code Like a Captain
JavaScript isn’t just code it’s a powerhouse for taming data, where arrays and objects act as your ultimate playmakers. Think of arrays as your batting order (a lineup of values) and objects as player profiles (key-value stats), working together to structure everything from to-do apps to live score trackers.
But here’s the twist: Arrays and objects are the Kohli and Babar of your codebase. Like cricket captains strategizing a T20 clash, they orchestrate logic with precision dynamic, adaptable, and game-changing.
In this article, we’ll stump boredom with real cricket scenarios: updating scoreboards mid-match, swapping players like tactical substitutions, and smashing JavaScript methods into six-hitting tools. Whether you cheer for PSL or IPL, these examples will make you a coding all-rounder!
🧩 Arrays: Your Batting Lineup
What’s an array?
Think of an array as your cricket squad roster, a list that keeps all your star players (data) in order. Just like a captain chooses batters, bowlers, and all-rounders, arrays allow you to organize, access, and manage multiple values in a single variable.
//An array is a lineup of players stored in one variable. Think of it as your team roster:
let teamPlayers = [
"Babar Azam",
"Virat Kohli",
"Shaheen Afridi",
"Rohit Sharma",
"Shubman Gill"
];
console.log(teamPlayers);
// Result
//["Babar Azam","Virat Kohli","Shaheen Afridi","Rohit Sharma","Shubman Gill"]
👑 Why Arrays Rule in JavaScript:
Order Matters: Like a batting lineup, arrays keep values in sequence (index 0 = opener!).
Flexible Squad: Add/remove players (elements) dynamically with methods like
push()
andpop()
.Real-World Use: Manage scorecards, player stats, or tournament schedules effortlessly.
💡 Pro Tip: Arrays are your go-to for grouping related data, just like a coach groups batters, bowlers, and all-rounders!
📋 Objects: Player Profile Cards
What’s an object?
An object is like a cricket player’s stats card which stores structured details (key-value pairs) to describe a single entity. Think of it as Virat Kohli’s career profile: name, age, role, batting average, and more all neatly organized!
// 🧑🎓 Virat Kohli’s player card
let player = {
name: "Virat Kohli", // Key: "name", Value: "Virat Kohli"
age: 36, // Age in years
role: "Batsman", // Primary role
matches: 250, // Total matches played
runs: 12,450, // Career runs
average: 56.8 // Batting average
};
// Accessing stats like a coach!
console.log(player.name); // "Virat Kohli"
console.log(player.runs); // 12450
// Update stats after a match 💪
player.matches += 1;
player.runs += 85;
console.log(player.runs); // 12535
👑 Why Objects Rule in JavaScript:
Structured Data: Group-related info (stats, roles) like a player’s report card.
Real-World Use: APIs, user profiles, and scoreboards rely on objects.
Flexibility: Update properties (e.g.,
player.runs
) as easily as updating a live score!
💡 Pro Tip: Objects can nest other objects/arrays!
let player = {
name: "Shaheen Afridi",
wickets: 200,
bestFigures: { // Nested object!
runs: 24,
wickets: 5
}
};
🏏Live Scoreboard Updates – Objects in Action!
Scenario: Imagine a thrilling India vs. Pakistan match – every ball changes the score! Objects let you update stats in real time, just like a stadium’s digital scoreboard.
// 🏟️ Initial scoreboard (15th over)
let scoreboard = {
team: "Pakistan",
runs: 200, // Total runs
wickets: 4, // Wickets fallen
overs: 15.0 // Overs bowled
};
// 🎉 Babar Azam smashes a SIXER!
scoreboard.runs += 6;
scoreboard.overs += 0.1; // Ball-by-ball update
// 😢 Shaheen loses his wicket!
scoreboard.wickets += 1;
console.log(scoreboard);
/*
{
team: "Pakistan",
runs: 206,
wickets: 5,
overs: 15.1
}
*/
What Are the Methods?
In JavaScript, methods are like a cricketer’s skill set – actions that objects or arrays can perform to achieve specific tasks. Just as a bowler uses bowl()
to deliver a ball or a batsman uses drive()
to hit a four, methods let your data do something useful.
// 🧑🏏 A "player" object with methods (skills)
let player = {
name: "Shaheen Afridi",
role: "Bowler",
// Method 1: Bowl a delivery
bowl: function() {
console.log("🎯 Yorker at 145kph!");
},
// Method 2: Update wickets
takeWicket: function() {
this.wickets += 1;
console.log("🥳 Wicket! Total wickets: " + this.wickets);
},
wickets: 0
};
// Use the methods (skills)!
player.bowl(); // "🎯 Yorker at 145kph!"
player.takeWicket(); // "🥳 Wicket! Total wickets: 1"
Built-In Methods: JavaScript’s "Playbook"
Just like cricket teams have predefined strategies, arrays and objects come with built-in methods:
Some of The Array Methods
push()
→ Add a player to the squad.map()
→ Calculate strike rates for all batters.find()
→ Locate the top scorer.
Some of The Object Methods
Object.keys()
→ List all properties (e.g.,name
,role
).Object.assign()
→ Merge player profiles.
Why Methods Matter
Reusability: Like a bowler’s action, reuse methods anywhere!
Organization: Group related logic (e.g.,
bat()
,bowl()
).Encapsulation: Hide complexity (e.g.,
sort()
handles sorting magic).
Real-World Cricket Analogy
Imagine a coach’s playbook:
Method = A play (e.g., “Powerplay Attack”).
Data = Players (e.g., Babar, Kohli).
Execution = Running the play during a match.
// Coach’s playbook method
function powerplayAttack(batsmen) {
return batsmen.filter(batsman => batsman.strikeRate > 150);
}
let aggressiveBatters = powerplayAttack([kohli, rohit, gill]);
💡 Pro Tip: Methods are your secret weapon for clean, efficient code. Treat them like a captain’s tactics – plan, execute, win! 🏆
10 Awesome Array & Objects Methods – Your Cricket Tactics Playbook
1. 🏏 Squad Shuffle: push()
& pop()
– Adding and Removing Players from a Squad
Scenario: Manage your team like a PSL captain!
push()
: Add a new player to the squad (e.g., Rashid Khan joins).pop()
: Remove the last player (injured? Sorry, Rashid!).
let squad = ["Babar Azam", "Virat Kohli", "Shaheen Afridi", "Rohit Sharma"];
// A new player is added to the squad
squad.push("Rashid Khan");
console.log(squad);
// ["Babar Azam", "Virat Kohli", "Shaheen Afridi", "Rohit Sharma", "Rashid Khan"]
// A player gets injured and is removed
squad.pop();
console.log(squad);
// ["Babar Azam", "Virat Kohli", "Shaheen Afridi", "Rohit Sharma"]
2. 🎯 Batting Lineup Strategy : shift()
& unshift()
– Managing Batting Order
Scenario: Rotate openers like an IPL coach!
shift()
: Sack the underperforming opener (Fakhar Zaman walks back).unshift()
: Promote a new star (Kane Williamson steps up).
let battingOrder = ["Fakhar Zaman", "Shubman Gill", "Steve Smith"];
// The first batsman gets out
let outPlayer = battingOrder.shift();
console.log(outPlayer); // "Fakhar Zaman"
console.log(battingOrder); // ["Shubman Gill", "Steve Smith"]
// A new batsman enters the field
battingOrder.unshift("Kane Williamson");
console.log(battingOrder); // ["Kane Williamson", "Shubman Gill", "Steve Smith"]
3. 🔄 Death Over Strategy: slice()
– Selecting Key Bowlers for the Death Overs
What it does:
slice()
copies a portion of an array into a new array.The original array remains unchanged (like keeping your full squad intact).
Scenario: Pick your best 3 bowlers for the final overs.
let bowlers = ["Bumrah", "Shaheen", "Rashid", "Cummins", "Boult"];
// Select bowlers from index 1 (Shaheen) to index 3 (Cummins)
let deathBowlers = bowlers.slice(1, 4);
// ["Shaheen", "Rashid", "Cummins"]
Start index: 1 (
Shaheen
).End index: 4 (stops before index 4 →
Cummins
at index 3).Use case: Safely pick bowlers without altering the original squad.
4. 🏏 Deep Dive: splice()
– Replacing a Player
What it does:
- The
splice()
method is your mid-match strategy tool – it lets you remove, replace, or add elements in an array at a specific position. Think of it as substituting a player mid-innings for maximum impact!
Syntax Breakdown
array.splice(startIndex, deleteCount, newElement1, newElement2, ...);
startIndex
: Position in the array where the change begins (like picking the player’s slot).deleteCount
: Number of elements to remove (e.g., dropping 1 underperforming player).newElements
: Elements to add (optional – like bringing in a replacement).
Scenario: Replace David Warner (index 2) with KL Rahul in the playing XI.
let playingXI = ["Babar Azam", "Virat Kohli", "David Warner", "Ben Stokes"];
// Tactical substitution at index 2:
playingXI.splice(
2, // Start at Warner’s position (index 2)
1, // Remove 1 player (Warner)
"KL Rahul" // Add Rahul as the replacement
);
console.log(playingXI);
// Result: ["Babar Azam", "Virat Kohli", "KL Rahul", "Ben Stokes"]
5. 🔥 Strike Rate Calculator: map()
– Converting Batting Scores to Strike Rates
What it does:
map()
transforms every element in an array and returns a new array.
Scenario: Crunch numbers like a stats analyst!
let playersStats = [
{ runs: 51, balls: 30 },
{ runs: 75, balls: 50 }
];
// Calculate strike rate for each player
let strikeRates = playersStats.map(player => (player.runs / player.balls) * 100);
// [170, 150]
Process: Loops through each player, calculates
(runs/balls)*100
, and creates a new array of strike rates.Original array: Unchanged (stats stay intact).
6. 🎯 Economy Check: filter()
– Selecting Players with an Economy Below 6
What it does:
filter()
returns a new array with elements that pass a test (economy < 6).
Scenario: Hunt for bowlers with economy < 6 (Bumrah = King!).
let bowlersStats = [
{ name: "Bumrah", economy: 5.2 },
{ name: "Shaheen", economy: 6.5 }
];
// Keep only bowlers with economy < 6
let economicalBowlers = bowlersStats.filter(bowler => bowler.economy < 6);
// [{ name: "Bumrah", economy: 5.2 }]
Logic: Tests each bowler’s economy rate.
Result: New array with qualifying bowlers.
7. 🏆 Top Scorer Spotlight: find()
– Finding the Player with the Highest Runs
What it does:
find()
returns the first element that matches a condition (runs > 90).
Scenario: Find the Virat Kohli of your team (runs > 90).
let batsmen = [
{ name: "Babar Azam", runs: 80 },
{ name: "Virat Kohli", runs: 95 },
{ name: "Joe Root", runs: 60 }
];
// Find the first player with runs > 90
let topScorer = batsmen.find((player) => player.runs > 90);
console.log(topScorer);
// { name: "Kohli", runs: 95 }
// *Chants*: "King Kohli! King Kohli!" 👑
8. 🤝 Quick Team Meeting: forEach()
– How Everyone Plays a Role
What it does:
forEach()
executes a function for each element in an array (no return value).
Scenario: Announce each player’s role like a stadium commentator!
let squadRoles = [
{ name: "Babar Azam", role: "Batsman" },
{ name: "Shaheen Afridi", role: "Bowler" },
{ name: "Rohit Sharma", role: "Batsman" }
];
// Log each player’s role
squadRoles.forEach(player => console.log(`${player.name} is a ${player.role}`));
/*
"Babar Azam is a Batsman" // Anchor of the innings!
"Shaheen Afridi is a Bowler" // Yorkers incoming! 🎯
"Rohit Sharma is a Batsman" // Hitman mode activated!
*/
Action: Iterates over the array and logs roles.
Use case: Side effects (like DOM updates or logging).
9. 🔍 Dugout Check: includes()
– Checking if a Player is Part of the Squad
What it does:
includes()
checks if an array contains a specific value (case-sensitive).
Scenario: Verify if a star player is in your XI (Where’s Virat?).
let team = ["Babar Azam", "Shaheen Afridi", "Rohit Sharma", "Shubman Gill"];
// Check if "Kohli" is in the team
let isPlayerInTeam = team.includes("Virat Kohli");
console.log(isPlayerInTeam); //false 😢
// *Crowd boos*: "We want Kohli!"
10. 📈 Total Score Tally: reduce()
– Total Score Tally
What it does:
reduce()
accumulates values (e.g., summing runs) into a single result.
Scenario: Calculate your team’s total like a frantic scoreboard operator!
let batsmenScores = [
{ name: "Babar Azam", runs: 45 },
{ name: "Virat Kohli", runs: 78 },
{ name: "Shubman Gill", runs: 34 }
];
// Sum all runs starting from 0
let totalRuns = batsmenScores.reduce((total, player) => total + player.runs, 0);
console.log(totalRuns); // 157 🏏
// Final over tension! Can the bowlers defend this?
Parameters:
total
: Accumulator (starts at0
).player
: Current array element.
Result: Final accumulated value (
157
).
🏆 Conclusion: Code Like a Pro!
Arrays and objects are your Bat and Ball in JavaScript:
Arrays = Flexible squad lists (add, remove, slice!).
Objects = Player stats cards (name, role, strike rate).
Methods = Match strategies (
map()
for analytics,filter()
for economy checks).
By framing code with cricket scenarios, you’ll debug like Bumrah bowls yorkers and code innings like Pant’s fireworks! Keep practicing—soon, you’ll be the MS Dhoni of JavaScript, cool under pressure! 💻🚀
Final Over Advice:
“Code like a Test match: patience for logic, aggression for bugs. Soon, you’ll lift the JS World Cup!”
🚀 Ready to practice? Try rebuilding a live scoreboard or player auction app!
🔗 Cheat Sheet: Cricket to Code
Cricket | JavaScript |
Batting Lineup | Array |
Player Stats Card | Object |
Coach’s Playbook | Methods |
Powerplay | map() , filter() |