Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Mastering #
Michael J. Larocca
Michael J. Larocca

Posted on • Originally published atselftaughttxg.com

     

Mastering #"/t/javascript">#javascript#foreach#ternary#tutorial

This article explores how to effectively use JavaScript's forEach method in combination with the ternary operator, enhancing your understanding of the underlying code while writing it more efficiently!


Image credit: Star Wars character © Lucasfilm Ltd. & TM. All Rights Reserved. Coca-Cola can © The Coca-Cola Company. Used under fair use for educational purposes.

Introduction

Using JavaScript'sforEach method in conjunction with theternary operator can increase your coding efficiency. Learning how to integrate different methods like this will enable you to write cleaner, more efficient code, enhancing readability and functionality.

Throughout the article, we will discuss key JavaScript concepts, including:

  • Objects: Understanding how to structure and utilize objects to organize data.

  • Arrays: Learning how arrays can store multiple values and how to manipulate them.

  • forEach Method: Discovering how to iterate over arrays efficiently using this built-in method.

  • Iterating and Modifying Object Arrays: Exploring techniques to update object properties within arrays.

  • Ternary Operator: Mastering this concise alternative to traditional if-else statements for decision-making.


JavaScript Objects

Anobject in JavaScript is a collection of related data and functionality, organized as key-value pairs. Objects help you organize related information, making managing and accessing data in your code easier.

The following code defines a JavaScript object named Anakin. This object contains several key-value pairs that describe his attributes:

constAnakin={name:"Anakin Skywalker",ForcePath:"light",affiliation:"Jedi",homePlanet:"Tatooine",lightsaberColor:"blue",mentor:"Obi-Wan Kenobi",apprentice:"Ahsoka Tano",knownAs:"The Chosen One"};
Enter fullscreen modeExit fullscreen mode

JavaScript Array

A JavaScriptarray is a special type of object used to store multiple values in a single variable. Arrays are like lists that can hold a collection of items, such as numbers, strings, or even other objects. Each item in an array has a specific position, called an index, starting from zero. This makes accessing, adding, or modifying items using their index easy.

We can create two new Star Wars character objects, and then add them to an array as follows:

constcharacters=[Anakin,ObiWan,Dooku];
Enter fullscreen modeExit fullscreen mode

JavaScript forEach Method

TheforEach method in JavaScript is a built-in function used to execute a specific function once for each element in an array. It's a convenient way to loop through all the items in an array without having to write a traditionalfor loop.

When you use forEach, you provide a function that will be called for each element in the array. This function can perform any operation you need, such as logging values to the console, updating elements, or performing calculations.

While iterating over the array with forEach, you can access the values of an object's properties using dot notation. Dot notation allows you to easily retrieve or update the value associated with a specific key in an object.

We can iterate over the Star Wars characters array and console log each charactersname,ForcePath, andaffiliationas follows:

characters.forEach(character=>{console.log(`Name:${character.name}`);console.log(`Force Path:${character.ForcePath}`);console.log(`Affiliation:${character.affiliation}`);});
Enter fullscreen modeExit fullscreen mode

Iterating and Modifying Object Arrays

Now that we have an understanding of a JavaScript object, an array, and the forEach Method: Let’s write code to iterate and modify the object arrays’ affiliation values based on each character's ForcePath value.

If the character has a value of “light“ for theirForcePath, then theiraffiliation value is“Jedi. If the character has a value of “dark“ for theirForcePath, then theiraffiliation value is“Sith.

characters.forEach(character=>{if(character.ForcePath==="dark"){character.affiliation="Sith";}});
Enter fullscreen modeExit fullscreen mode

Now, changing Anakin’s ForcePath to dark changes his character affiliation to Sith!


Ternary Operator

Theternary operator in JavaScript is a shorthand way of writing anif-else statement. It allows you to make a quick decision between two values based on a condition. The ternary operator uses the? and: symbols and follows this basic structure:

condition ? valueIfTrue : valueIfFalse

Here's how it works: if the condition is true, the operator returns the value before the colon (:); if the condition is false, it returns the value after the colon. It's a concise way to assign values or execute expressions based on a condition, making your code shorter and often easier to read.

We can revise the if statement code inside the forEach loop to a ternary operator for better readability and concise code:

characters.forEach(character=>character.ForcePath==="dark"?character.affiliation="Sith":character.affiliation="Jedi");
Enter fullscreen modeExit fullscreen mode

CodePen Demonstration

To see the code in action, check out the complete implementation on CodePenhere. Make sure to open the console log to view the results.


My Personal Use Case

As a personal project, I am working on a JavaScript Pac-Man game based on Ania Kubów’s1-hour Pac-Man in JavaScript YouTube tutorial. This tutorial was featured both on Scrimba and freeCodeCamp, and it’s a really fun way to learn JavaScript!

🔗 Here is alink to my JavaScript Pac-Man game, which is in progress.

I added levels to my game. When each level is completed, I increase the speed of Pac-Man and all the ghosts.

Following Ania’s tutorial, I created the four ghosts using a JavaScript Ghost class stored in a ghosts array. After completing each game level, I needed to update each ghost's speed value to achieve the desired result.

As a quite comical glitch, as the levels progress, the ghosts' speed increases so much that the gameplay becomes unplayable; they zip by so fast that avoiding them is impossible!

exportclassGhost{constructor(className,startIndex,speed,size,color,eyes){this.className=className;this.startIndex=startIndex;this.speed=speed;this.size=size;this.color=color;this.eyes=eyes;this.currentIndex=startIndex;this.isScard=false;this.timerId=NaN;}}exportconstghosts=[newGhost('blinky',321,225,`ghost-${ghostSize}`,'ghost-red',`ghost-look-left-${eyeSize}`),newGhost('inky',376,275,`ghost-${ghostSize}`,'ghost-blue',`ghost-look-up-${eyeSize}`),newGhost('pinky',377,250,`ghost-${ghostSize}`,'ghost-pink',`ghost-look-down-${eyeSize}`),newGhost('clyde',378,300,`ghost-${ghostSize}`,'ghost-orange',`ghost-look-right-${eyeSize}`),];
Enter fullscreen modeExit fullscreen mode

The ghosts' speeds are initially set to different values in milliseconds, which determine how quickly they move. After each level is completed, the speed of each ghost is increased by reducing the time interval by 25 milliseconds. This makes the ghosts move faster, adding to the challenge of the game as players progress through the levels.

Using all of the JavaScript concepts covered in this article, I wrote the following code to “cap“ each ghost's speed at 100 milliseconds, which solved the issue of the ghost moving at an unplayable rate.

ghosts.forEach(ghost=>ghost.speed!==100?ghost.speed-=25:ghost.speed=ghost.speed)
Enter fullscreen modeExit fullscreen mode

My other related articles


Be sure to listen to the HTML All The Things Podcast!

📝I also write articles for the HTML All The Things Podcast, which you can read on their website:https://www.htmlallthethings.com/.

Be sure to check out HTML All The Things on socials!


Affiliate & Discount Links!

With CodeMonkey, learning can be all fun and games! CodeMonkey transforms education into an engaging experience, enabling children to evolve from tech consumers to creators. Use CodeMonkey'sFREE trial to unlock the incredible potential of young tech creators!

With a structured learning path tailored for various age groups, kids progress from block coding to more advanced topics like data science and artificial intelligence, using languages such as CoffeeScript and Python. The platform includes features for parents and teachers to track progress, making integrating coding into home and classroom settings easy.

Through fun games, hands-on projects, and community interaction, CodeMonkey helps young learners build teamwork skills and receive recognition for their achievements. It fosters a love for coding and prepares children for future career opportunities in an ever-evolving tech landscape.

To learn more about CodeMonkey, you can read my detailedreview article!

Affiliate Links:


Advance your career with a 20% discount on Scrimba Pro using thisaffiliate link!

Become a hireable developer with Scrimba Pro! Discover a world of coding knowledge with full access to all courses, hands-on projects, and a vibrant community. You canread my article to learn more about my exceptional experiences with Scrimba and how it helps many become confident, well-prepared web developers!

Important:This discount is for new accounts only. If a higher discount is currently available, it will be applied automatically.

How to Claim Your Discount:

  1. Clickthe link to explore the new Scrimba 2.0.

  2. Create a new account.

  3. Upgrade to Pro; the 20% discount will automatically apply.

Disclosure:This article contains affiliate links. I will earn a commission from any purchases made through these links at no extra cost to you. Your support helps me continue creating valuable content. Thank you!

Conclusion

To become a better JavaScript developer, it's important to learn and understand the underlying logic of your code. This provides you with the skill to revise it using built-in methods, resulting in cleaner and more efficient code. For example, once you understand the logic and how to write a for loop, you can alternatively use JavaScript’s forEach method.

Another example of code revision is using a ternary operator instead of an if-else statement. Combining shorthand operators and built-in methods further helps you to create more concise and readable code.

Most importantly, enjoy the process of coding! I created objects featuring Star Wars characters to illustrate the concepts discussed. I then used these concepts to revise the code in my JavaScript Pac-Man game! What entertainment genres do you enjoy? Do you find coding games fun as well? Customize your learning experience to make it enjoyable and become a better developer!


Let’s connect! I’m active onLinkedInandTwitter.


Are you now confident in using JavaScript's forEach method and ternary operators to write more efficient code? Do you have other tips for mastering these JavaScript concepts? Please share the article and comment!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Hello, I'm Michael. Like many people, I am an aspiring self-taught web developer.
  • Location
    New York
  • Joined
DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp