If you’re familiar with event loop and concept of microtasks and macrotasks it’ll be easy for you to answer all questions in

10 JavaScript Promise Challenges Before You Start an Interview

PS. Try from the last one.

No matter the result - subscribe to Tech Read channel.
Likes, shares and recommendations are welcome.

#javascript #promise
If you are a JavaScript developer - check your code again.
Are you sure that you handled all the “unhandled rejections”?

If not - check the post of Jake Archibald The gotcha of unhandled promise rejections

Spoiler: sometimes you need to write something like “preventUnhandledRejections” specifically if you use old versions of Node.js (please update) for example (<12.9.0).

Not to miss something useful - subscribe to Tech Read channel.
Likes, shares and recommendations are welcome.

#javascript #nodejs #promises
In article Middleware for web applications: it’s not just for enterprises you’ll find the reasons and ways to implement with middlewares such common functionalities as authentication/authorization (hope you know the difference) using 3 different languages - Golang, JavaScript and Python.

Additionally you’ll find a lot of useful links in the “Learn More” section.

Also a lot of useful links you can find in Tech Read channel so subscribe and enjoy.
Likes, shares and recommendations are welcome.

#middleware #javascript #golang #python
Just a List of Enterprise Integration Patterns with small description, schema and details.

Will be useful and interesting for architects and engineers.

Hope as useful and interesting a Tech Read channel.
Likes, shares and recommendations are welcome.

#patterns
“JS (Browser + Node.js): Broadcast Channel API - How to Reduce Server Load”

In this article I described the use case of combining Broadcast Channel API and Shared Workers (or Worker Threads in Node.js) for reducing the number of server connections.

Broadcast Channel API is a JavaScript interface that allows communication between different browsing contexts, such as tabs or frames (or between Node.js Worker Threads, but about this at the end of the article), that share the same origin. It provides a simple publish-subscribe model for sending and receiving messages between these contexts.

Shared Worker - a special type of web worker that can be accessed by multiple instances of an application. Shared workers have a single thread of execution and a shared scope between all clients, allowing for efficient communication and synchronization between tabs.

To know how to combine them - check the article.

Medium link

If you liked the article and want to support the author:
Clap and follow me on Medium
Follow me on Linkedin
Subscribe to Tech Read channel

#javascript #nodejs #broadcastchannelapi #webapi #sharedworker
The Hidden Danger: Malware in NPM Modules

In today's interconnected world, where software development heavily relies on third-party libraries and frameworks, we must remain vigilant about the security of our codebases. One area that often goes unnoticed is the presence of malware in npm modules, posing a significant threat to our projects.

NPM (Node Package Manager) has revolutionized the JavaScript ecosystem by providing a vast collection of reusable modules. While most npm modules are developed and maintained by trustworthy individuals and organizations, the open nature of the ecosystem leaves room for potential vulnerabilities and malicious intent.

The proliferation of malware-infected npm modules has become a growing concern. Hackers have increasingly exploited this avenue to inject harmful code into unsuspecting projects. These malware-infected modules can take various forms, including hidden backdoors, data exfiltration mechanisms, crypto-mining scripts, or even ransomware.

So, how can we protect ourselves and our projects from such threats? Here are a few essential measures to consider:

1. Regularly Update Dependencies: Keeping your project's dependencies up to date is crucial. Developers often release security patches and bug fixes to address vulnerabilities. By updating your npm modules regularly, you ensure that you are using the latest, more secure versions.

2. Scrutinize Dependency Sources: When choosing npm modules, it's vital to review the module's source, maintainers, and the overall community engagement. Opt for modules that have an active developer community, reliable maintainers, and transparent code reviews. Additionally, check if the module has undergone security audits or has a history of security-related issues.

3. Analyze Module Popularity: The popularity of an npm module can be an indicator of trustworthiness. Highly popular modules usually have a larger user base and undergo more scrutiny, reducing the likelihood of malware infiltration. However, popularity alone is not a guarantee, and additional due diligence is necessary.

4. Implement Continuous Integration and Testing: Incorporating automated security checks into your development workflow is essential. Leverage tools like vulnerability scanners, static code analyzers, and dependency checkers to identify any potential security risks. Integrate these checks as part of your continuous integration (CI) and continuous deployment (CD) pipelines for maximum effectiveness.

5. Stay Informed: Stay updated with the latest news and reports on security vulnerabilities or malware incidents related to npm modules. Follow trusted sources, security forums, and advisory lists to receive timely information about emerging threats and recommended actions.

Remember, the responsibility for securing our projects lies with us as developers. By being proactive, vigilant, and implementing the best practices outlined above, we can mitigate the risks associated with malware-infected npm modules.
Stay safe, keep your codebase secure, and happy coding!

To know more - subscribe to the Tech Read channel in Telegram.
Also I’ll add a link with the article “Five Packages And Their Evil Install Scripts”.
Likes, shares and recommendations are welcome.

#npm #security #javascript

Links:
https://blog.sandworm.dev/dissecting-npm-malware-five-packages-and-their-evil-install-scripts
Server-Sent Events (SSE)

In one of my previous articles I’ve described the usage of BroadcastChannel API with Websockets. At the same time I’ve passed over another way of Server-Client communication. I should correct the situation.

Server-Sent Events (SSE) is a powerful technology that enables real-time communication between a server and a client. It allows the server to push data to the client over a single HTTP connection, making it an ideal choice for building interactive and event-driven applications. In this post, we will explore the concept of Server-Sent Events and how they can revolutionize the way we create real-time applications.

What are Server-Sent Events?
Server-Sent Events is a web API that enables server-initiated communication with the client. Unlike traditional request-response patterns, SSE allows the server to send data to the client without the need for the client to repeatedly poll the server for updates. This one-way communication channel opens up exciting possibilities for building real-time applications where information is delivered instantly to connected clients.

How do Server-Sent Events work?
SSE works by establishing a persistent connection between the client and the server. The server sends data to the client as a stream of events, and the client handles those events as they arrive. The connection remains open as long as both the client and the server desire, facilitating ongoing communication and real-time updates.

Benefits of Server-Sent Events:
1. Real-Time Updates: SSE provides a seamless way to deliver real-time updates to clients, enabling instant data synchronization and interaction. This is particularly useful for applications such as chat systems, social media feeds, live dashboards, and collaborative tools.
2. Simplicity and Efficiency: SSE is based on standard HTTP protocols and does not require additional dependencies or complex setup. It uses a single, long-lived connection, reducing overhead and improving efficiency compared to frequent polling or WebSocket-based approaches.
3. Compatibility: SSE is supported by most modern web browsers, making it widely accessible to a broad range of users. It can be used alongside existing web technologies, and server-side implementations can be achieved with various frameworks and languages.
4. Error Handling and Reconnection: SSE handles error conditions and reconnection automatically, ensuring robust communication. If the connection is lost, SSE attempts to reconnect, minimizing data loss and providing a seamless experience for clients.

Use Cases for Server-Sent Events:
- Real-time chat and messaging applications
- Live updates and notifications
- Collaborative document editing and shared whiteboards
- Stock tickers and financial data feeds
- Sports scores and live event updates

Conclusion:
Server-Sent Events offer a straightforward and efficient approach for building real-time applications. With its ability to push data from the server to the client, SSE simplifies the development of interactive and event-driven systems. Whether you're building chat applications, live dashboards, or collaborative tools, consider leveraging Server-Sent Events to deliver real-time updates and create engaging user experiences. Embrace the power of SSE to unlock a world of real-time possibilities in your web applications.

To know more - subscribe to the Tech Read channel in Telegram.
Also I’ll add a link to the article with SSE usage examples.
Likes, shares and recommendations are welcome.

#sse #websockets #javascript

Links:
https://javascript.plainenglish.io/js-browser-node-js-broadcastchannel-api-8d4ceb408a5
https://blog.endpts.io/server-sent-events-with-nodejs
About sessionStorage

One crucial aspect of web development is managing data within the browser. In this post, let's delve into the browser's sessionStorage and understand its purpose and functionality.

What is sessionStorage?
sessionStorage is a built-in web API provided by modern browsers that allows developers to store key-value pairs locally within the user's browser session. Unlike cookies, which are sent to the server with every request, sessionStorage is purely client-side storage. It provides a temporary storage mechanism for the duration of the user's session on a particular website.

How does it work?
When you store data in sessionStorage, it is associated with the specific origin (protocol, domain, and port) from which it originates. This means that the stored data is accessible only within the same origin and cannot be accessed by other websites or origins.
sessionStorage data persists as long as the user's browsing session remains active. If the user closes the browser or navigates away from the website, the sessionStorage data is cleared, and subsequent visits to the website will start with a clean slate.

Using sessionStorage
Working with sessionStorage is straightforward. Here are a few key methods to interact with it:
- sessionStorage.setItem(key, value): Stores a key-value pair in sessionStorage.
- sessionStorage.getItem(key): Retrieves the value associated with the specified key.
- sessionStorage.removeItem(key): Removes the key-value pair with the given key from sessionStorage.
- sessionStorage.clear(): Clears all key-value pairs stored in sessionStorage.

Remember that sessionStorage values are always stored as strings. If you want to store complex objects or arrays, you need to convert them to JSON strings using JSON.stringify() before storing and parse them back using JSON.parse() when retrieving.

Use Cases
- Storing temporary data or user preferences during a session.
- Implementing client-side caching to avoid redundant network requests.
- Saving form data temporarily, ensuring it survives page refreshes.

Tip: Remember that sessionStorage is limited to a specific browser tab or window. If you need to share data across multiple tabs or windows, you should explore other techniques like localStorage or server-side storage.

Understanding and effectively utilizing the browser's sessionStorage API can enhance the user experience and provide seamless interactions within your web applications. By harnessing the power of client-side storage, you can create more responsive and personalized web experiences.
Happy coding!

To know more - subscribe to the Tech Read channel in Telegram.
Also I’ll add a link to the article with an interesting interview question.
Likes, shares and recommendations are welcome.

#javascript #sessionstorage

Links:
https://javascript.plainenglish.io/interviewer-can-sesstionstorage-share-data-between-multiple-tabs-a8d850328e89
JS: Generators

Hey fellow developers! Today, let's dive into the fascinating world of generators in JavaScript and explore how they can level up our programming skills and enhance our code.

***
Before you continue reading - subscribe to the Tech Read channel in Telegram.
Likes, shares and recommendations are welcome.
***

Generators are a unique feature introduced in ES6 (ECMAScript 2015) that allows us to define a function that can be paused and resumed at any time, yielding multiple values over time. They provide a powerful and elegant way to work with sequences and asynchronous operations in JavaScript.

To define a generator function, we use the “function*” syntax. Within this function, we can use the “yield” keyword to pause the function and produce a value to the caller. When the generator is invoked, it returns an iterator object, which can be used to control the execution of the generator function.

One of the key benefits of generators is their ability to generate values on-demand, lazily computing them only when requested. This is in contrast to traditional functions that compute and return values immediately. This lazy evaluation enables us to work with infinite sequences or process large datasets efficiently.

Generators also excellent in handling asynchronous operations. With the help of the “yield” keyword, we can easily write code that looks synchronous but behaves asynchronously. By yielding promises, we can wait for asynchronous tasks to complete and resume the generator once the results are available.

Additionally, generators offer two-way communication between the caller and the generator function. The caller can send data back into the generator by using the “next()” function with an argument. This feature opens up possibilities for building cooperative and interactive code, making generators ideal for scenarios such as event handling or state machines.

To iterate over the values produced by a generator, we use a “for...of” loop, which automatically calls the “next()” function on the iterator until the generator is exhausted. Alternatively, we can manually control the iterator by calling “next()” explicitly and inspecting the “value” and “done” properties of the returned object.

In conclusion, generators are a valuable tool in the JavaScript developer's toolbox. Their ability to create iterable sequences, handle asynchronous operations, and facilitate two-way communication make them a powerful abstraction. By leveraging generators, we can write cleaner, more expressive code that is easier to reason about and maintain.

So, let's embrace the power of generators and unlock new possibilities in our JavaScript projects. Happy coding, everyone!

PS. Link to the article ”JavaScript’s (Secret) Superpower — No One Ever Cared to Teach You” below.

#javascript #generators

Links:
https://javascript.plainenglish.io/javascripts-secret-super-power-no-one-ever-cared-to-teach-you-1331b252acf7
JS: few words about regular expressions

Today, let's dive into the powerful world of regular expressions in JavaScript and unravel their potential. Regular expressions are an incredibly versatile tool for pattern matching and manipulating text data. Whether you're validating user input, parsing strings, or searching for specific patterns, regular expressions have got you covered.

***
Before you continue reading - subscribe to the Tech Read channel in Telegram.
Likes, shares and recommendations are welcome.
***

In JavaScript, regular expressions are represented by the RegExp object. You can create a regular expression pattern by enclosing it in forward slashes (/). For example, /hello/ is a simple regular expression that matches the word "hello" in a string.

Here are a few common use cases where regular expressions shine:
String Matching: Regular expressions allow you to check if a string matches a particular pattern. For instance, you can use /[A-Z]+/ to find all uppercase letters in a string or /^\d{4}$/ to validate a four-digit number.
Replacing Text: With regular expressions, you can perform powerful find-and-replace operations. By using the replace() method of a string, you can replace specific patterns with desired values. For instance, str.replace(/\s/g, "_") replaces all whitespace characters in a string with underscores.
String Splitting: Regular expressions enable you to split strings based on complex patterns. By using the split() method, you can divide a string into an array of substrings based on a given regular expression. For example, str.split(/[,.]/) splits a string at every comma or period.

Remember, regular expressions come with a rich set of syntax and metacharacters to define complex patterns. Some commonly used metacharacters include . (matches any character except newline), * (matches zero or more occurrences), + (matches one or more occurrences), ? (matches zero or one occurrence), and many more.

In addition to the basic syntax, JavaScript provides numerous built-in methods for working with regular expressions, such as test(), exec(), and match(), which further enhance their usability.

However, be cautious when working with regular expressions, as they can become quite complex and hard to read. It's always a good practice to add comments and break down complex patterns into smaller parts to improve readability and maintainability.

In conclusion, regular expressions are a valuable tool for text manipulation in JavaScript. By mastering their usage, you can unlock a whole new level of string handling capabilities in your projects. So, embrace the power of regular expressions, experiment, and explore the vast possibilities they offer!

PS. Link to the article ”Regular expressions in JavaScript” below.

#javascript #regex

Links:
https://www.honeybadger.io/blog/javascript-regular-expressions