How to use Generator Function In Javascript
The generator function can be used to yield non-empty values which can be further used to create a custom iterator that skips empty values.
Syntax:
// Generator function
function* skipEmptyValues(arr) {}
Example: The below code explains the use of generator function to create custom iterator that skips empty values.
Javascript
function * skipEmptyValuesIterator(arr) { for (let value of arr) { if (value !== '' ) { yield value; } } } const myArray = [ 'GFG' , '' , 3, '' , 'JavaScript' ]; const iterator = skipEmptyValuesIterator(myArray); for (let value of iterator) { console.log(value); } |
Output
GFG 3 JavaScript
How to Create Custom Iterator that Skips Empty Value in JavaScript ?
Iterators are important concepts in the world of programming. They allow developers to traverse and manipulate collections of data more efficiently and flexibly. JavaScript, being a high-level programming language, also supports iterators. You can even create a custom iterator that skips the empty values using the below methods:
Table of Content
- Using Generator Function
- Using Array.prototype.filter and Symbol.iterator
- Using Iterator Protocol with Custom Class
- Using Array.prototype.entries and Symbol.iterator
- Using Array.prototype.reduce and Symbol.iterator