Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
ES6 Map Method | Getting Started: ES6
Introduction to React
course content

Зміст курсу

Introduction to React

Introduction to React

1. Getting Started: ES6
2. Getting Started: JSX
3. React in Practice
4. React Components
5. Controlling Data & Content
6. Hooks
7. React Router

bookES6 Map Method

ES6 introduces a new array method called map, using which we can apply a function on every element of an array. This is useful in React because, using a map, we can generate lists and repeated elements with a minimal amount of code.

123
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]; let twosMultiples = numbers.map ((n) => n * 2); console.log (twosMultiples);
copy

The map iterates over the entire array, passing the elements one by one as an argument into the inline function and storing the return values of the inline function into an output array.

We can use the same logic combined with JSX and React to achieve amazing results. We will explore JSX in detail in later chapters.

Example

There is a popular coding problem called the ‘FizzBuzz’ problem. The user is given an array of integers and asked to go through the array and:

  • Replace the element with "FizzBuzz" if it's divisible by 3 and 5;
  • Replace the element with "Fizz" if it's divisible by 3;
  • Replace the element with "Buzz" if it's divisible by 5;
  • Leave the integer as it is if it's divisible by none.
1234567891011121314
let terms = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; let result = terms.map ((element) => { if (element % 3 == 0 && element % 5 == 0) { return "FizzBuzz"; } else if (element % 3 == 0) { return "Fizz"; } else if (element % 5 == 0) { return "Buzz"; } else { return element; } }); console.log (result);
copy

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 5
We're sorry to hear that something went wrong. What happened?
some-alt