Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Ryoichi Homma
Ryoichi Homma

Posted on • Edited on

     

JS - Things I Sometimes Get Confused

Concept Highlights:

  • Usingfor...of andfor...in Loops
  • Differences BetweenSet() andArray
  • Differences BetweenMap() andObjects
  • Differences BetweenSet() andMap()

1. Usingfor...of andfor...in Loops

Looping is a fundamental concept in programming, allowing to execute the block of code multiple times. In JavaScript,for...of andfor...in are two commonly used loops, but they serve different purposes. Understanding the differences can help you write more efficient and effective code.

1.1for...of Loop

Thefor...of loop is used to iterate over iterable objects, such as arrays, strings, maps, and sets. It provides a straightforward way to access each value in the sequence without needing to worry about the index.

e.g.) In this example,for...of directly accesses each element (team) in theteams array and logs it to the console. This loop is ideal when you only need the values and not the indices.

let teams = ['Red Sox', 'Dodgers', 'Padres']; for (let team of teams) {   console.log(team);}// Output: // Read Sox// Dodgers// Padres
Enter fullscreen modeExit fullscreen mode

1-2.for...in Loop

Thefor...in loop, on the other hand, is used to iterate over the properties (keys) of an object. It's often used with objects, but it can also used with arrays to access indices.

e.g.) In this example,for...in iterates over the keys of theMariners object, allowing access to both the key and the corresponding value. It's important to note thatfor...in should be used cautiously with arrays, as it iterates over all enumerable properties, not just numeric indices.

let Mariners = {place: 'Seattle', league: 'American', color: 'navy blue'}; for (let key in Mariners) {   console.log(`${key}: ${Mariners[key]}`); }// Output: // place: Seattle// league: American// color: navy blue
Enter fullscreen modeExit fullscreen mode

1-3. Key Differences

  • Purpose:
    • for...of iterates over the values of an iterable object (arrays, strings, sets, maps).
    • for...in iterates over the enumerable properties (keys) of an object.
  • Use Case:
    • Usefor...of when you need to access values directly.
    • Usefor...in when you need to access keys or property names.

2. Differences BetweenSet() andArray

JavaScript provides a variety of data structures, each with its strengths and weaknesses. I explored the differences between some of the most commonly used ones:

  • Uniqueness:
    • Set() stores unique values, meaning no duplicates are allowed.
    • Array allows duplicate values.
  • Order:
    • Set() iterates the order of insertion.
    • Array also maintains the order of insertion, but duplicates can alter how you interact with it.

e.g.) In this example, theSet() automatically removes the duplicates3, while the Array retains it.Set() is useful when you need a collection of unique items.

let mySet = new Set([1, 2, 3, 3, 4]); let myArray = [1, 2, 3, 3, 4]; console.log(mySet) // Output: Set { 1, 2, 3, 4 }console.log(myArray) // Output: [1, 2, 3, 3, 4]
Enter fullscreen modeExit fullscreen mode

3. Differences BetweenMap() andObjects

  • Key Types:

    • Map(): Keys can be of any type, including objects, functions, and primitive types.
    • Object: Keys are usually strings or symbols.
  • Order:

    • Map() maintains the order of insertion.
    • Object does not guarantee the order of keys.
  • Size:

    • Map() has asize property that gives the number of key-value pairs.
    • Object requires manually determine the size by iterating through the keys.

e.g.) In this example,Map() allows the use of a variety of key types, while object keys are converted to strings. Additionally,Map() easily provides the size of the map, whereas for objects, you need to manually count the keys.

let myMap = new Map();myMap.set('name', 'John'); myMap.set(42, 'The answer'); myMap.set({}, 'Empty object'); let myObject = {   name: 'John',   42: 'The answer',    {}: 'Empty object'};console.log(myMap.size); // Output: 3console.log(Object.keys(myObject).length); // Output: 2 (due to key string conversion)
Enter fullscreen modeExit fullscreen mode

4. Differences BetweenSet() andMap()

  • Purpose:
    • Set() is a collection of unique values.
    • Map() is a collection of key-value pairs.
  • Use Case:
    • UseSet() when you need to store a list of unique items.
    • UseMap() when you need to associate values with keys.

e.g.) In this example,Set() is used to check for the existence of value, whileMap() is used to retrieve a value associated with a key.

let mySet = new Set([1, 2 ,3]); let myMap = new Map([['key1', 'value1'], ['key2', 'value2']]); console.log(mySet.has(2)); // Output: trueconsole.log(myMap.get('key1')); // Output: 'value'1
Enter fullscreen modeExit fullscreen mode

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

Software Engineer proficient in front-end web development using React, TypeScript/JavaScript, and Tailwind CSS. Aiming to expand into full-stack development using Node.js, Express.js, and MongoDB.
  • Location
    British Columbia, Canada
  • Education
    Thompson Rivers University
  • Pronouns
    he/him/his
  • Work
    Software Engineer Intern at Cajon and COMSQUARE
  • Joined

More fromRyoichi Homma

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