Skip to content

Hey everyone! πŸ‘‹ I'm diving headfirst into a 100-day JavaScript adventure, and I couldn't be more thrilled to share it with you all! πŸŽ‰ Over the next three months, I'll be immersing myself in everything JavaScript has to offer, from the very basics to some seriously advanced concepts.

Notifications You must be signed in to change notification settings

lassiecoder/100daysofjs

Β 
Β 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

30 Commits
Β 
Β 

Repository files navigation

Exploring Iterables

πŸ₯‘ Symbol.iterator

πŸ₯‘ String is iterable

πŸ₯‘ Calling an iterator explicitly

πŸ₯‘ Iterables and array-likes

πŸ₯‘ Array.from


Symbol.iterator

JavaScript arrays are iterable, meaning they have a built-in Symbol.iterator method that allows them to be iterated over using loops or other constructs

For example:

const array = [1, 2, 3];
const iterator = array[Symbol.iterator]();
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
console.log(iterator.next()); // { value: undefined, done: true }

String is iterable

Strings in JavaScript are also iterable, meaning they can be looped over character by character using the Symbol.iterator method

For example:

const str = 'hello';
for (let char of str) {
  console.log(char);
}
// Output: h, e, l, l, o

Calling an iterator explicitly

You can manually call the Symbol.iterator method of an iterable object to obtain an iterator, which can then be used to iterate over the elements

For example:

const array = [1, 2, 3];
const iterator = array[Symbol.iterator]();
console.log(iterator.next()); // { value: 1, done: false }

Iterables and array-likes

In JavaScript, iterables are objects that implement the Symbol.iterator method, allowing them to be iterated over

Array-like objects are objects that have indices and a length property but may not have the built-in methods of arrays like forEach or map

For example:

// Array-like object
const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 };
// Iterating over array-like object
for (let item of arrayLike) {
  console.log(item);
}
// Output: a, b, c

Array.from

The Array.from method creates a new, shallow-copied Array instance from an array-like or iterable object

For example:

const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 };
const newArray = Array.from(arrayLike);
console.log(newArray); // Output: ['a', 'b', 'c']

About

Hey everyone! πŸ‘‹ I'm diving headfirst into a 100-day JavaScript adventure, and I couldn't be more thrilled to share it with you all! πŸŽ‰ Over the next three months, I'll be immersing myself in everything JavaScript has to offer, from the very basics to some seriously advanced concepts.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published