Day - avaScript Foundations Professional Certification by Mozilla
Concept Highlights:
- Using for...of and for...in Loops
- Differences Between Set() and Array, Map() and Objects, and Set() and Map()
1. Using for...of and for...in Loops
Looping is a fundamental concept in programming, allowing to execute a block of code multiple times. In JavaScript, for...of and for...in are two commonly used loops, but they serve different purposes. Understanding the differences can help you write more efficient and effective code.
1.1 for...of Loop
The for...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.)
let teams = ['Red Sox', 'Dodgers', 'Padres']; for (let team of teams) { console.log(team); } // Output: // Read Sox // Dodgers // Padres
In this example, for...of directly accesses each element (team) in the teams array and logs it to the console. This loops is ideal when you only need the values and not the indices.
1-2. for...in Loop
The for...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.)
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
In this example, for...in iterates over the keys of the Mariners object, allowing to access both the key and the corresponding value. It's important to note that for...in should be used cautiously with arrays, as it iterates over all enumerable properties, not just numeric indices.
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:
- Use for...of when you need to access values directly.
- Use for...in when you need to access keys or property names.
2. Differences Between Set() and Array, Map() and Objects, and Set() and `Map()
JavaScript provides a variety of data structures, each with its strength and weaknesses. I explored the differences between some of the most commonly used ones:
2-1. Set() vs. Array
- 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.)
`
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]
`
In this example, the Set() automatically removes the duplicates 3, while the Array retains it. Set() is useful when you need a collection of unique items.
2-2. Map() vs. Object
-
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 a size property that gives the number of key-value pairs.
- Object requires to manually determine the size by iterating through the keys.
e.g.)
`
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: 3
console.log(Object.keys(myObject).length); // Output: 2 (due to key string conversion)
`
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.
2-3. Set() vs. Map()
- Purpose:
- Set() is a collection of unique values.
- Map() is a collection of key-value pairs.
- Use Case:
- Use Set() when you need to store a list of unique items.
- Use Map() when you need to associate values with keys.
e.g.)
`
let mySet = new Set([1, 2 ,3]);
let myMap = new Map([['key1', 'value1'], ['key2', 'value2']]);
console.log(mySet.has(2)); // Output: true
console.log(myMap.get('key1')); // Output: 'value'1
`
In this example, Set() is used to check for the existence of value, while Map() is used to retrieve a value associated with a key.
The above is the detailed content of Day - avaScript Foundations Professional Certification by Mozilla. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
