Code Monkey home page Code Monkey logo

int-u5l3-23-24-student-exercises's Introduction

Lesson 5.3: Loops

  • Purpose: The forEach loops iterates over each item in an array, executing a callback function for each element.
  • Syntax:
    array.forEach(function(currentValue, index, arr), thisValue)
  • Parameters:
    • currentValue: The current element being processed in the array.

    • index (Optional): The index of the current element being processed.

    • arr (Optional): The array the forEach loop is being applied to.

    • thisValue (Optional): A value to use as this when executing the callback.

Code Snippets

Basic Iteration

const fruits = ['apple', 'banana', 'cherry'];
fruits.forEach(function(item) {
  console.log(item);
});

Using Index

const fruits = ['apple', 'banana', 'cherry'];
fruits.forEach(function(item, index) {
  console.log(index, item);
});

Refactoring with forEach

Before:

const images = document.querySelectorAll('img');
images[0].src = 'image1.jpg';
images[1].src = 'image2.jpg';
images[2].src = 'image3.jpg';

After:

const imageSources = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
document.querySelectorAll('img').forEach((img, index) => {
  img.src = imageSources[index];
});

Best Practices

  • Use forEach for side effects within a function.
  • Remember that forEach doesn't stop or break - it loops through the entire selected array.

Happy coding! ๐Ÿ˜Š

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.