Typescript generics are a way to take a function that has an argument that we can define when we call that argument - the same way we can change an argument of a function when we call it.
If you're new to the concept of Typescript generics, then read on to learn how they work.
It's something used in JavaScript, but it is often a mystery. In JavaScript, this works quite differently from other programming languages - and it works differently depending on if you are using strict mode or not.
If you find it hard, you aren't alone. Let's look at exactly how this works and remove any confusion about its meaning in various contexts.
In March 2022, Python made headlines in the programming world by becoming the most popular programming language. After years of hovering in the top ranks, it finally surpassed Java and C to reach the number one spot on the TIOBE index.
And why not? After all, it is such a fun and powerful language to work with. It is fast, user-friendly, open-source, and has a community comprising millions of programmers across the globe.
We must use the fetch API; if we want to get data from an API or post data to a server, I. As is implied by the name, fetch() gives us a way to send and receive HTTP requests through requests and responses.
The fetch() function is a global function, and it is most frequently used to interact with APIs. If you're new to it, you're not alone - so let's look at how fetch() works.
When we create a file or folder on a Unix-based system like Linux or MacOS, it has a set of permissions and access modes. These are most often manipulated using the chmod command, which allow us to change who can access and run different files.
Let's look at how chmod works. To begin, the chmod command has the following syntax, where [OPTIONS] are optional settings, [MODE] are the permissions we want to give the file or folder, and x is the file we want to apply chmod to.
On Linux and UNIX-like systems, like Mac, we use mkdir to make a new directory from the terminal. To do this, open up a new terminal, and make sure you're in the right directory using the cd command.
The syntax for mkdir looks like this, where dir_name is the name of your new directory, and [OPTIONS] are optional settings.
The cd command in Linux stands for change directory and is used to change directory when you have a terminal window open. It's used frequently, so it is useful to know.
When writing code, a reserved keyword is one you can't use as the name of a variable or identifier. As of 2022, this is the full list of valid reserved keywords in JavaScript.
All JavaScript Reserved Keywords
The below list cannot be used as variable names, as they are reserved keywords. Most of them have current functionality in JavaScript. Some do not, but they are words that may have some sort of functionality in the future. Avoid using these words in variable names.
One of the most important concepts in JavaScript, as with most programming languages, is the ability to define variables. A variable is a container of a value or data. Some types of variables can later be changed, based on the logic we use in our code. Let's take a look at how variables work in Javascript.
Think of a world where you don't need a separate testing environment, where you can test everything in production and capture valuable data that helps you improve along the way. The secret ingredient: feature flags.
What Are Feature Flags?
Features flags is a software engineering technique that lets developers integrate code constantly into the main trunk. It involves shipping incomplete features into production, which remain dormant until ready. Feature flags also take part in software delivery; when the feature is complete, the code can be activated at the flick of a switch.
In JavaScript, short-circuiting refers to the partial evaluation of expressions to avoid unnecessary computation. This blog post describes the short-circuiting operators and assignments in JavaScript and how to use them.
Short-Circuiting Operators: &&, ||, and ??
Short-circuiting operators only evaluate the right side of an expression when necessary.
MDC stands for Mapped Diagnostic Context. Mapped Diagnostic Context enriched the logs by providing more information about the event in the logs. By default, Mule logs two entries: processor which shows the location of current events, events which shows the correlation Id of the event.
Mule Runtime 4.4 introduced Tracing module and enables you to add more information to the logs by by adding, removing, and clearing variables from the logging context for a given Mule event.
A URL shortener is a service that is used to create short links from very long URLs. Usually, short links have the size of one-third or even one-fourth of the original URL, which makes them easier to type, present, or tweet. Clicking on a short link user will be automatically redirected to the original URL.
There are many URL shortening services available online, such as tiny.cc, bitly.com, and cutt.ly. Implementing a URL shortening service is not a complex task, and it is often part of system design interviews. In this post, I will try to explain the process of implementing the service.
Building quality APIs is essential to facilitating equally quality software. Think about it like this, If a waiter in a restaurant has terrible habits, then the restaurant’s overall quality will be affected. We don’t want that, right? This article will look at some tips and best practices you should remember when building and consuming APIs.
Tips to Remember When Building APIs
Is the API easily readable?
An API should be easy to read as this will make it easy to understand as well. Readability includes API definitions and response messages. Writing readable code also applies to software development as this will make it easier for further development and collaboration with other developers. Use readable response messages that include both error and success messages clearly stated out using standard error codes to give more understanding to the API users.
Let’s say we want to add something to a webpage after the initial load. JavaScript gives us a variety of tools. Perhaps you’ve used some of them, like append, appendChild, insertAdjacentHTML, or innerHTML.
The difficult thing about appending and inserting things with JavaScript isn’t so much about the tools it offers, but which one to use, when to use them, and understanding how each one works.
Let’s try to clear things up.
Super quick context
It might be helpful to discuss a little background before jumping in. At the simplest level, a website is an HTML file downloaded from a server to a browser.
Your browser converts the HTML tags inside your HTML file into a bunch of objects that can be manipulated with JavaScript. These objects construct a Document Object Model (DOM) tree. This tree is a series of objects that are structured as parent-child relationships.
In DOM parlance, these objects are called nodes, or more specifically, HTML elements.
<!-- I'm the parent element -->
<div>
<!-- I'm a child element -->
<span>Hello</span>
</div>
In this example, the HTML span element is the child of the div element, which is the parent.
And I know that some of these terms are weird and possibly confusing. We say “node”, but other times we may say “element” or “object” instead. And, in some cases, they refer to the same thing, just depending on how specific we want to be .
For example, an “element” is a specific type of “node”, just like an apple is a specific type of fruit.
Understanding these DOM items is important, as we’ll interact with them to add and append things with JavaScript after an initial page load. In fact, let’s start working on that.
Setup
These append and insert methods mostly follow this pattern:
Element.append_method_choice(stuff_to_append)
Again, an element is merely an object in the DOM Tree that represents some HTML. Earlier, we had mentioned that the purpose of the DOM tree is to give us a convenient way to interact with HTML using JavaScript.
So, how do we use JavaScript to grab an HTML element?
Querying the DOM
Let’s say we have the following tiny bit of HTML:
<div id="example" class="group">
Hello World
</div>
There are a few common ways to query the DOM:
// Query a specific selector (could be class, ID, element type, or attribute):
const my_element1 = document.querySelector('#example')
// Query an element by its ID:
const my_element2 = document.getElementbyId('example')
// Query an element by its class:
const my_element3 = document.getElementbyClass('group')[0]
In this example, all three lines query the same thing, but look for it in different ways. One looks at any of the item’s CSS selectors; one looks at the item’s ID; and one looks at the item’s class.
Note that the getElementbyClass method returns an array. That’s because it’s capable of matching multiple elements in the DOM and storing those matches in an array makes sure all of them are accounted for.
In this example, something is a parameter that represents stuff we want to tack on to the end of (i.e. append to) the matched element.
We can’t just append any old thing to any old object. The append method only allows us to append either a node or plain text to an element in the DOM. But some other methods can append HTML to DOM elements as well.
Nodes are either created with document.createElement() in JavaScript, or they are selected with one of the query methods we looked at in the last section.
Plain text is, well, text. It’s plain text in that it does not carry any HTML tags or formatting with it. (e.g. Hello).
HTML is also text but, unlike plain text, it does indeed get parsed as markup when it’s added to the DOM (e.g. <div>Hello</div>).
It might help to map out exactly which parameters are supported by which methods:
1 This works, but insertAdjacentText is recommended. 2 Instead of taking traditional parameters, innerHTML is used like: element.innerHTML = 'HTML String'
How to choose which method to use
Well, it really depends on what you’re looking to append, not to mention certain browser quirks to work around.
If you have existing HTML that gets sent to your JavaScript, it’s probably easiest to work with methods that support HTML.
If you’re building some new HTML in JavasScript, creating a node with heavy markup can be cumbersome, whereas HTML is less verbose.
If you want to attach event listeners right away, you’ll want to work with nodes because we call addEventListener on nodes, not HTML.
If all you need is text, any method supporting plain text parameters is fine.
If your HTML is potentially untrustworthy (i.e. it comes from user input, say a comment on a blog post), then you’ll want to be careful when using HTML, unless it has been sanitized (i.e. the harmful code has been removed).
Our final append places the new user at the end of the buddy list, just before the closing </ul> tag. If we’d prefer to place the user at the front of the list, we could use the prepend method instead.
You may have noticed that we were also able to use append to fill our <a> tag with text like this:
const buddy_name = "Dale"
new_link.append(buddy_name) // Text param
appendChild is another JavaScript method we have for appending stuff to DOM elements. It’s a little limited in that it only works with node objects, so we we’ll need some help from textContent (or innerText) for our plain text needs.
There’s no need to follow all of above JavaScript – the point is that creating large amounts of HTML in JavaScript can become quite cumbersome. And there’s no getting around this if we use append or appendChild.
In this heavy markup scenario, it might be nice to just write our HTML as a string, rather than using a bunch of JavaScript methods…
insertAdjacentHTML is is like append in that it’s also capable of adding stuff to DOM elements. One difference, though, is that insertAdjacentHTML inserts that stuff at a specific position relative to the matched element.
And it just so happens to work with HTML. That means we can insert actual HTML to a DOM element, and pinpoint exactly where we want it with four different positions:
Remember the security concerns we mentioned earlier. We never want to insert HTML that’s been submitted by an end user, as we’d open ourselves up to cross-site scripting vulnerabilities.
That’s what we want! But there’s a constraint with using innerHTML that prevents us from using event listeners on any elements inside of #buddies because of the nature of += in list.innerHTML += new_buddy.
You see, A += B behaves the same as A = A + B. In this case, A is our existing HTML and B is what we’re inserting to it. The problem is that this results in a copy of the existing HTML with the additional inserted HTML. And event listeners are unable to listen to copies. That means if we want to listen for a click event on any of the <a> tags in the buddy list, we’re going to lose that ability with innerHTML.
So, just a word of caution there.
Demo
Here’s a demo that pulls together all of the methods we’ve covered. Clicking the button of each method inserts “Dale” as an item in the buddies list.
Go ahead and open up DevTools while you’re at it and see how the new list item is added to the DOM.
Recap
Here’s a general overview of where we stand when we’re appending and inserting stuff into the DOM. Consider it a cheatsheet for when you need help figuring out which method to use.
1 This works, but insertAdjacentText is recommended. 2 Instead of taking traditional parameters, innerHTML is used like: element.innerHTML = 'HTML String'
If I had to condense all of that into a few recommendations:
Using innerHTML for appending is not recommended as it removes event listeners.
append works well if you like the flexibility of working with node elements or plain text, and don’t need to support Internet Explorer.
appendChild works well if you like (or need) to work with node elements, and want full browser coverage.
insertAdjacentHTML is nice if you need to generate HTML, and want to more specific control over where it is placed in the DOM.
Last thought and a quick plug :)
This post was inspired by real issues I recently ran into when building a chat application. As you’d imagine, a chat application relies on a lot of appending/inserting — people coming online, new messages, notifications, etc.
That chat application is called Bounce. It’s a peer-to-peer learning chat. Assuming you’re a JavaScript developer (among other things), you probably have something to teach! And you can earn some extra cash.
By default, Cypress resets the sessions before each test. If you are logged in scenario first test (ex: it() block), then in the second test (second it block), and you are performing some other task, you are automatically taken back to the login page. This happens because Cypress doesn’t keep the session; it creates a new session. In end-to-end testing, mostly, users will be logged first and then all the workflow will be checked. This article explains the simplest way to overcome this problem using just a few lines of code.