What is a JSON feed? Learn more

JSON Feed Viewer

Browse through the showcased feeds, or enter a feed URL below.

Now supporting RSS and Atom feeds thanks to Andrew Chilton's feed2json.org service

CURRENT FEED

DEV Community

A constructive and inclusive social network for software developers. With you every step of your journey.

JSON


A Visual Guide to React Rendering - Cheat Sheet

Permalink - Posted on 2021-10-19 09:05

When does react component re-renders? What can cause the re-render, and how to prevent unnecessary renders? Here is a quick cheat sheet you can refer to whenever you find yourself asking these questions.

This article serves as a table of content for a Visual Guide to React Rendering series. Every section of the cheat sheet links to the correspondent chapter of the guide that explores a topic in depth.

Standard rendering and memo

By default, when the state of the component changes, this component and all its children re-render. You can wrap React component with memo to prevent an entire subtree from re-rendering.

Image description

A Visual Guide To React Rendering - It Always Rerenders (Chapter 1)

Primitive vs Non-primitive props

Non-primitive values in javascript are compared by reference.

{display: "flex"} === {display: "flex"} // false

Keep that in mind when passing props to memoized components. Memoized components re-render when their props change.

Image description

A Visual Guide To React Rendering - Props (Chapter 2)

Stable reference with useMemo

You can preserve a reference to a non primitive value with useMemo. It won't change on re-renders.

Image description

A Visual Guide To React Rendering - useMemo (Chapter 3)

Stable reference with useCallback

You can preserve a reference to a function with useCallback

Image description

A Visual Guide To React Rendering - useCallback (Chapter 4)

Rendering and Context

The component right under your context provider should probably use memo

Image description

A Visual Guide To React Rendering - Context (Chapter 5)

Rendering and DOM

React component render does not mean DOM update. React is smart enough to update only those parts of DOM that need to change.

Image description

A Visual Guide To React Rendering - DOM (Chapter 6)

Originally published at alexsidorenko.com

Articles on the topic:


Embold to integrate with Codesphere to bring advanced code analysis to the cloud

Permalink - Posted on 2021-10-19 08:46

We are happy to announce our collaboration with Embold!

emboldlogo

Embold offers a static code analysis tool that checks your code for bad coding practices, anti-patterns, and style issues so you know exactly where to start debugging. We also plan to integrate the embold ai code completion and automatic documentation into our pipelines as part of our vision for the future of the Codesphere IDE. We hope to assist the programmer in their coding style as well as to predict and prevent errors.

When we first met with founders in late 2020 we were immediately impressed with the capacity of their systems for deep code analysis. It also excels at showing coupling, bad architecture, and the quality of real (not syntactic) code patterns. Our aim is to provide a complete development experience with everything our users love in their home environment but without any of the setup or installation. Collaboration with, and the integration of, tools like Embold are helping us get closer to that vision every day.

We look forward to implementing the embold solution to our IDE in the near future.

In the meantime, check out Embold to help improve your code!

And of course, happy coding from Codesphere, the most intuitive cloud provider on the market.


Blade Runner 2049, but it is in your Windows Terminal

Permalink - Posted on 2021-10-19 08:31

My lab assistant once said, "Make your terminal feels like your home!" and proceed to show me a cool terminal during lab session. I didn't have the time to do it back then but now I get a chance to. So here's how I make my Windows Terminal looks like I using it from the movie Blade Runner 2049 since it feels like a futuristic home to me ๐Ÿ˜‰.

1. Install Windows Subsystem Linux 2 (WSL2)
2. Install Windows Terminal
3. Install Z Shell (zsh) as the default shell
4. Prepare the image or GIF for the background
5. Change the background and text

1. Install Windows Subsystem Linux 2 (WSL2)

The first thing is to install WSL2 on the device since I'm using Windows as my OS and WSL2 provide more than the previous version. You might ask, why don't you use PowerShell or Windows Command Prompt instead? The reason is I'm not used to it since my college and my work environment mostly depends on Windows. Go to step 2 if you don't wanna install. You need to install WSL1 before you could install WSL2. I'm not gonna explain it further here since it is out of this scope. There's just no shortcut to install WSL2. Follow this instruction on WSL installation first, then this instruction on WSL2 installation.

WSL2

2. Install Windows Terminal

This is quite easy. Go to the Microsoft Store and type Windows Terminal on the search bar. Click the product and click the Get or Install button. Let the process finish. Once it's done you're on set. Hold Win + R and type wt to run Windows Terminal. We are installing this after WSL2 so Windows Terminal could instantly register WSL2 on it.

Windows Terminal

3. Install Z Shell (zsh) as the default shell

This step is just for WSL users only. Go to step 4 if you are not. The reason I choose this shell is for these 2 primary reasons. First, zsh is the second-fastest shell as far as I know. Second, it has a great framework that improves usability, Oh-My-Zsh, no pun intended. Follow this article on how to install zsh and its plugins. When it comes to choosing a zsh theme, just go for the jonathan orย  agnoster theme. For me personally, the terminal designs fit perfectly with the futuristic nuance of the movie ๐Ÿค–.

zsh

4. Prepare the image or GIF for the background

This part, I leave it to you, whether to choose a static image or gif for the background. For me personally, I want something alive accompanying me while I'm doing some code or script on the terminal ๐Ÿ˜‚. So I go with the gif. Usually the gif itself I get from a certain movie scene. I look for the scene on YouTube, download it, trim it if it's too long and convert it into a gif. I'll use this gif below from a hilarious movie RocknRolla directed by one of my favourite directors Guy Ritchie on my PowerShell. This scene depicts perfectly what I thought about PowerShell in case I must use it for effectiveness. Handsome Bob (Tom Hardy) once came out to his friend OneTwo (Gerard Butler) and then said, "I told you, you wouldn't understand!". It might apply as well when I was told to explain my code to my colleagues. And believe me. it is way funnier in the movie context ๐Ÿคฃ๐Ÿ˜ญ.

Handsome Bob

5. Change the background and text

Here's come the neat part ๐Ÿ˜Ž. On Windows Terminal, hold ctrl + , to open Settings. There's a lot of options here but we just focus on these 2 things, background and font style. Under Profiles Section, choose your CLI program, in this case, I choose PowerShell first. Go to Appearance and then scroll down until you find Retro toggle and switch it on. Then scroll down once more and you will get to the Background image and browse for the gif file path. Don't forget to adjust the background through its stretch mode, alignment and opacity. I'm using "uniform to fill", "center" and 40% respectively.

Appearance configuration

And that configuration yield this result which is perfect! ๐Ÿ‘Œ. Programmer tends to look on the darker work environment so that's why I only use 40% opacity.

Windows Terminal - Powershell

Okay, that was PowerShell I rarely use. This one is for my WSL2. First, I could use any scene with Joe or Agent K from Blade Runner 2049 movie for my background. But then the longer I stare at this terminal, the more depressing I've become to think about my existential crisis regarding my code and myself. Then I come to terms with this background. Instead of thinking about depressing stuff, why don't I turn it into something positive, let's say a therapy session ๐Ÿ’ก? I ended up using Pat from Silver Lining Playbook on his therapy session since it's spark a hilarious and refreshing moment when I stare at it ๐Ÿ˜.

Windows Terminal - WSL2

Okay, that's it. One might say I don't really use the Blade Runner 2049 reference on this but for me, mine is enough to hype the vibe and keep me motivated. How about yours? ๐Ÿ˜Ž


fractal.build as an atomic design tool

Permalink - Posted on 2021-10-19 08:20

Recently, I discovered a tool that helped me build a design system: fractal.build. Described in by Rachel Andrew in her article Pattern Library First back in 2018, fractal does look a little old school, but it can be customized and does a good job without getting into your way.

alternatives to fractal

Fractal looks less shiny than Storybook, that I have used for ReactJS projects, but it can easily be used for projects without any JavaScript framework.

Fractal seemed easier, at least to me, to understand and maintain, than PatternLab, which I failed to install due a bug in the current installer (and when I managed to install the grunt version, I was already told that there is fractal as a possible alternative).

atomic design and design systems

So what are design systems and what is atomic design?
Much has been said and written about CSS methodologies like BEM, ABEM, ITCSS, and utility-based approaches like Tailwind or Bootstrap. Follow the links for further reading, if you like.

agnostic fractal

Fractal is quite agnostic about tools, methods, and coding style. Which also allows for a pragmatic approach that does not adhere to one single methodology.

The default setup allows you to build and compose components using handlebars, HTML, and CSS. Fractal can be customized to use any other markup language like Twig or Nunjucks, so you could probably use it for a JAMStack setup with 11ty as well.

boilerplates to start with

Other users have created boilerplates for using ABEM CSS in fractal or ditching handlebars to use fractal with twig templates instead.

To use CSS on a component level, you can add a tool chain of your choice (or just the first copy-and-paste-able example you find on Google), like SASS or PostCSS, together with a build process based on Webpack, Gulp, or plain Node.js.

In my first fractal.build example, I used a gulp setup with SASS for a quick proof of concept. In a future JAMStack project, I would go for PostCSS to use native CSS 3 / CSSnext features and try to avoid unnecessary tool depencies.

But still, after changing one's mind about tools or language choices, any existing code could be refactored easily while keeping the same folder structure.

advantages and suggestions

Apart from its agnostic and pragmatic approach, fractal has some other advantages.

preview theme customization

Fractal's user interface can be themed / customized, so we do not have to stick to the original UI. We can set colors, logo, and fonts to match our customers' corporate design before a presentation.

component composition

Components can include other components, so we can build a design system bottom-up starting with colors, icons, buttons etc. to be used in forms, paragraphs, sliders, navigation which can then be composed to larger blocks and pages.

variants

Components can have variants, either by configuration (in a config file) or by using file names accordingly, like in this example:

src/coponents/my-component/
  my-component.config.yml (or .json)
  my-component.hbs (default variant)
  my-component.css (classes used by my component)
  my-component--with-arrow.hbs
  my-component--with-arrow-without-borders.hbs

This can get confusing quickly, but you can (mis)use the default variant to display an overview page.

<!-- my-component.hbs -->

<h2>Component with Arrow</h2>
{{> \@my-component--with-arrow }}

<h2>Component with Arrow but without Borders</h2>
{{> \@my-component--with-arrow-without-borders }}

disadvantages

Some aspects to consider before choosing fractal:

invalid markup breaks the preview

Some invalid markup can break the whole preview. One single mistyped character inside a handlebars include will show an error message instead of the preview.

component names must be unique

This might be an advantage or a disadvantage, according to your own point of view: while components can be nested and composed, there is no hierarchy.

Instead, all components exist on the same level and share the same namespace, so their technical names have to be unique.

you must do it by yourself

Apart from its agnostic and pragmatic approach being an advantage for me, it might be a disadvantage to you.

Fractal is just a tool, and quite a simple one, at least when you have experience with other tools and frameworks. It is up to you to complete the setup by making further choices and implementations.

conclusion

Despite fractal being not the latest fad (or maybe even because of that) I have discovered it as a practical development and preview tool that does not get in your way.


React with Typescript

Permalink - Posted on 2021-10-19 07:58

At present react js has been a very popular library to build beautiful and scalable user interfaces. Today I would like to build a demo react project with typescript.

Project setup

We would like to use the create-react-app environment built by facebook developer team to create our project. Our project will have a form to add favorite tv series and show the list. It will be a single page website. At first we will run the following command

npx create-react-app --template typescript fav-tv-series
cd fav-tv-series
npm run start

The first command will create a react app named fav-tv-series having typescript template. Then after going to that directory we will run the third command which will create a process running on port number 3000 and look like this
Alt Text

Creating Interface

In typescript our main concern will be defining strict type to every data that will be used. interface is a pretty good way to define a data and use that as a type in ts. In the src folder of the root folder we will create a directory named interfaces and inside it we will create a file named SeriesProps.tsx. Here we will create an interface named SeriesProps like following

export interface SeriesProps {
    seriesList: {
        name: string;
        imdb: number;
        cover: string;
        seasons: number;
        genre: string;
      }[]
}

Updating App

At first we will update the existing App.tsx file by removing the existing code. Our single page web application will contain two components. One is a form where a user will give necessary inputs about his favourite series and another is a list containing those serieses. The data will be stored in a state named seriesList and updated with the help of setSeriesList method.

import React, { useState } from 'react';
import { SeriesProps } from './interfaces/SeriesProps';
import './App.css';
import List from './components/List';
import Form from './components/Form';

function App() {
  const [seriesList, setSeriesList] = useState<SeriesProps["seriesList"]>([]);

  return (
    <div className="App">
      <h1>My Favourite TV Series</h1>
      <Form seriesList={seriesList} setSeriesList={setSeriesList} />
      <List seriesList={seriesList} />
    </div>
  );
}

export default App;

Creating List

In src directory of root folder we will create a directory named components and there we will create the List.tsx file. Our component will look like below

import React, { FC } from "react";
import { SeriesProps } from "../interfaces/SeriesProps";

const List:FC<SeriesProps> = ({seriesList}) => (
    <div className="series-list">
        {seriesList.map((series) => (
            <div className="series-item">
                <img src={series.cover} alt="Series-cover" />
                <p><b>{series.name}</b></p>
                <p>{series.genre}</p> 
                <p>{series.seasons} seasons</p>
                <p>โ˜…โ˜…โ˜…โ˜…โ˜… {series.imdb}</p>
            </div>
        ))}
    </div>
);

export default List;

Here we can have a look at FC which means Functional Component and it guides us with types. Here we have passed SeriesProps as props and finally we have used map function to render tv series list.

Creating Form

Now we are left with creating the form element where we will give necessary inputs. Here we will use controlled components to build input elements. For simplicity we will create a state object where the necessary input values will be kept. We will use useState for this.

const [input, setInput] = useState({
        name: "",
        genre: "",
        cover: "",
        imdb: 0,
        seasons: 0
    });

Now we will render the components. Here we will have five input fields having three text and two number type inputs.

return (
        <div className="form-container">
            <div className="form-div">
                <label htmlFor="name">Name</label>
                <input type="text" name="name" id="name" value={input.name} onChange={handleChange} />
            </div>
            <div className="form-div">
                <label htmlFor="genre">Genre</label>
                <input type="text" name="genre" id="genre" value={input.genre} onChange={handleChange} />
            </div>
            <div className="form-div">
                <label htmlFor="cover">Cover Link</label>
                <input type="text" name="cover" id="cover" value={input.cover} onChange={handleChange} />
            </div>
            <div className="form-div">
                <label htmlFor="imdb">IMDB Rating</label>
                <input type="number" name="imdb" id="imdb" value={input.imdb} onChange={handleChange} />
            </div>
            <div className="form-div">
                <label htmlFor="seasons">Total Seasons</label>
                <input type="number" name="seasons" id="seasons" value={input.seasons} onChange={handleChange} />
            </div>
            <button type="button" onClick={handleClick}>Add Series</button>
        </div>
    );

Here we can see that the value of each input field will be stored to the state object. We can see that all input fields have a function named handleChange which will be invoked as an onChange listener and the button has an onClick listener named handleClick. We will implement these two methods now. The handleChange method is quite straight forward. Here we destructure the input state and update the particular state element needed to be updated. One important thing to notice is that the type of event we are passing to that function. Here the type is ChangeEvent<HTMLInputElement> which means our handleChange method will only accept html input element change event. One thing to notice is that we have kept the name and value of each input same for which we can use [name]: value statement.

const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
        const { value, name } = e.target;
        setInput({
            ...input,
            [name]: value
        });
    };

Before implementing the handleClick method we need to define a props which will be used to update and store the series list. As we have already defined a state in our App.tsx using useState, we need to pass those in this Form component and use in our handleClick method. Lets have a look at the following interface.

interface Props {
    seriesList: SeriesProps["seriesList"],
    setSeriesList: Dispatch<SetStateAction<SeriesProps["seriesList"]>>
}

Now we will implement our handleClick method.

const handleClick = (e: MouseEvent<HTMLButtonElement>) => {
        const { name, genre, cover, imdb, seasons } = input;
        if(!name && !genre && !cover && !imdb && !seasons) return;
        const series = { name, genre, cover, imdb, seasons };
        setSeriesList([...seriesList, series]);
        setInput({
            name: "",
            genre: "",
            cover: "",
            imdb: 0,
            seasons: 0
        });
    };

Our method only accepts a mouse event coming from an html button element. At first we have destructured our input state. Then we have checked whether any input field is empty. If so then we won't move further. Otherwise we have created a series object and appended it to the series list. After that we have made all fields empty. So our complete Form.tsx looks like this

import React, { FC, useState, ChangeEvent, MouseEvent, Dispatch, SetStateAction } from "react";
import { SeriesProps } from "../interfaces/SeriesProps";

interface Props {
    seriesList: SeriesProps["seriesList"],
    setSeriesList: Dispatch<SetStateAction<SeriesProps["seriesList"]>>
}

const Form: FC<Props> = ({ seriesList, setSeriesList }) => {

    const [input, setInput] = useState({
        name: "",
        genre: "",
        cover: "",
        imdb: 0,
        seasons: 0
    });

    const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
        const { value, name } = e.target;
        setInput({
            ...input,
            [name]: value
        });
    };

    const handleClick = (e: MouseEvent<HTMLButtonElement>) => {
        const { name, genre, cover, imdb, seasons } = input;
        const series = { name, genre, cover, imdb, seasons };
        if(!name && !genre && !cover && !imdb && !seasons) return;
        setSeriesList([...seriesList, series]);
        setInput({
            name: "",
            genre: "",
            cover: "",
            imdb: 0,
            seasons: 0
        });
    };

    return (
        <div className="form-container">
            <div className="form-div">
                <label htmlFor="name">Name</label>
                <input type="text" name="name" id="name" value={input.name} onChange={handleChange} />
            </div>
            <div className="form-div">
                <label htmlFor="genre">Genre</label>
                <input type="text" name="genre" id="genre" value={input.genre} onChange={handleChange} />
            </div>
            <div className="form-div">
                <label htmlFor="cover">Cover Link</label>
                <input type="text" name="cover" id="cover" value={input.cover} onChange={handleChange} />
            </div>
            <div className="form-div">
                <label htmlFor="imdb">IMDB Rating</label>
                <input type="number" name="imdb" id="imdb" value={input.imdb} onChange={handleChange} />
            </div>
            <div className="form-div">
                <label htmlFor="seasons">Total Seasons</label>
                <input type="number" name="seasons" id="seasons" value={input.seasons} onChange={handleChange} />
            </div>
            <button type="button" onClick={handleClick}>Add Series</button>
        </div>
    );
};

export default Form;

Now we are only left with adding css styles. For simplicity we have made change only in the App.css files which looks like

.form-container {
  width: 400px;
  margin: auto;
}

h1 {
  text-align: center;
}

.form-div {
  margin-bottom: 10px;
}

input[type='text'],
input[type='number'] {
  float: right;
  width: 70%;
  padding: 3px;
}

input[type='checkbox'] {
  margin-left: 110px;
}

button {
  margin: 10px 0;
  padding: 10px 0;
  width: 100%;
  cursor: pointer;
  font-weight: bold;
  text-transform: uppercase;
  font-size: 16px;
}

p {
  line-height: 5px;
}

.series-list {
  display: flex;
  flex-flow: wrap;
  margin: 50px auto;
  width: 90%;
}

.series-item {
  padding: 0 20px 20px 0;
  width: 300px;
}

After we are finished with all coding, we can have a look at our browser's http://localhost:3000/ link. After adding some data it should look like following
Image description
The whole project is in github. You can very well have a look in it here.

Happy Coding ๐Ÿ˜€๐Ÿ˜€๐Ÿ˜€๐Ÿ˜€๐Ÿ˜€


Installation of GDAL on jupyter notebook

Permalink - Posted on 2021-10-19 07:54

Installation of GDAL in windows machine is always a challenging task. But anaconda environment on python makes it easier to install through conda distribution. In this blog, I will write about the installation of GDAL on jupyter notebook.

Step 1: Create conda environment

conda create --name venv

After creating the virtual environment, by default it will install some of the packages.

Step 2: Installation of gdal

conda install -c conda-forge gdal

Step 3: Installation of ipykernel

conda install -c anaconda ipykernel

Step 4: Add ipykernel and run jupyternotebook

python -m ipykernel install --user --name=venv
jupyter notebook

Congratulations! You successfully installed the GDAL on jupyter notebook.

If you like this blog, please subscribe to my youtube channel: https://www.youtube.com/c/iamtekson


JavaScript. Memory. Architecture and Lifecycle.

Permalink - Posted on 2021-10-19 07:13

I'll start this article with a quote that changed the way I think of memory. The way I perceive memory lifecycle in major modern languages (those that have automatic memory release aka garbage collection).

Garbage collection is simulating a computer with an infinite amount of memory.
-- Raymond Chen

This is exactly how we think of memory in JavaScript. We don't...

Indeed, since I stopped writing C++ code I forgot about memory management. And I couldn't be bothered. Why would I? I mean it just works. Here's a variable, here's another one, no worries at all... Nowadays memory leak is rarely an issue. Most of the time you need to put an effort to create a one...

But it wouldn't be JavaScript if there were no interesting quirks and features hidden behind this area...

Further, we'll explore JavaScript memory architecture, main concepts and organization. And memory lifecycle, from allocation to release.
Also, we'll look through some common memory leaks and how to avoid them.

Memory

In programming everything requires space. Number, string, object, function. Even in the abstract Computer Science algorithmic department, there's a measurement for a space complexity.

Memory is different

In JavaScript (similarly to many other languages) there are two main types of memory Stack and Heap. Both are managed by the JavaScript Engine, both are for storing runtime data.
The difference lays in speed and size. Heap is bigger and slower, Stack is smaller and faster.

How does the engine know which one to use? The rule of thumbs is: if the engine is not sure about the size it uses Heap. If the engine can calculate the size beforehand, it uses Stack.

All the primitives like number, boolean, string, Symbol, BigInt, null and undefined always go to the Stack. Also, references are stored there, we'll talk about references in a minute.
What's left will end up in the Heap. This includes arbitrary objects and functions.

two jars

๐Ÿ’ก The data that goes in the Stack is usually called static because it has a static size that won't change, hence it is allocated at the compile-time.
The data that goes in the Heap is usually called dynamic because it has unpredictable size (and potentially can change throughout the program execution) and is allocated dynamically at the runtime.

โ„น๏ธ Have you heard of the term Hoisting?

Memory allocation in the Stack (aka static memory allocation) happening right before the code (next lexical scope) execution. References are stored in the Stack, thus they are allocated before the code is executed. Hence if we declare the variable it will be available even before the actual declaration in the code. Although value will be undefined because it doesn't have value to point to yet...

console.log(yolo); // undefined

var yolo = "hello!";

Variables declared with let, var, const are hoisted, although let and const won't return undefined.

References

The referencing concept is a major pillar of the JavaScript memory organization. It indirectly impacts how most of the key operations (such as assignment and equation) work.
However often it is poorly understood and thus results in occasional surprises and confusions.

Imagine a big bookshelf with multiple compartments. Each compartment has a label with a unique number on it. Every time you place something in the compartment you take a piece of paper and write down the number of the compartment and a short description of what is stored there.

bookshelf

This is the gist of how references work. The short description is a variable name, the shelf number is a memory address. The address is stored in the variable, which is stored in the Stack. And the actual object on the shelf is an object stored in the Heap, referenced by the variable...

Every time we use the assign (=) operator we are not assigning the value... We are creating a pointer to the memory where the value is stored. Your variable storing the address, that pointing to the memory where the actual value is stored.

Some personal opinion here...๐Ÿคช

I think the language we use matters. Therefore I think the word "assign" and operator = is evil misleading and creates cognitive confusion and unnecessary simplification. I think a huge amount of bugs came from such confusion.

I'd personally prefer to be more explicit about what is happening and suggest using a term like "pointing" or "referencing" instead of "assigning" and operator like -> instead of =.

But we have what we have ๐Ÿคท

Now that we have an idea of memory organization, let's reinforce it with some examples. We will start with primitive values and gradually move toward objects...

let answer = 42;

42

As we figured before we are not setting value we are pointing to it... Pretty straightforward so far, let's make it a bit more complicated...

let answer = 42;
let true_answer = answer;
answer = 43;

console.log(answer); // 43
console.log(true_answer); // 42

42 43

Same principle here. First both answer and trueAnswer point to the same address where value 42 is stored. Once we do answer = 43 we change not the value, but memory where we pointing...

Primitives are immutable. It kinda becomes obvious and almost redundant to mention if we talk it through. If we try to change 42 (e.g. add 1 to it), we will simply get another number, which is not 42...we won't change 42 (42 will still exist)... Hence it is immutable.
Nor we can extend it. E.g. 42.value = 22 won't work, although it will if 42 would be an object...

Hope it all made sense lol ๐Ÿ˜…

Let's do another example with primitives... null and undefined are primitives. What does that mean? They act like all primitives...

const null1 = null;
const null2 = null;
console.log(null1 === null2); // true

let undefined1;
let undefined2;
console.log(undefined1 === undefined2); // true

null and undefined

Now we see why both values are strictly equal, pointing to the same value.

Funny fact

console.log(typeof null); // object

It is not true, null is not an object. It is a bug that can't and won't be fixed...

Let's do the last one on primitives...

const a = true;
const b = false;
const c = true;
const d = false;
const e = true;

boolean

Everything looks very familiar.

Now let's try something new. Objects. Objects are different, they represent a more complex tree-structure ๐ŸŒณ. And unlike primitives, objects are mutable. This property produces some interesting effects.
This is where the = operator will reveal its full evilness ๐Ÿ˜ˆ.

const catzilla = { name: "Catzilla", breed: "Bengal Cat" };

const peanut = catzilla;
peanut.name = "Peanut";

console.log(catzilla); // { name: "Peanut", breed: "Bengal Cat" }
console.log(peanut); // { name: "Peanut", breed: "Bengal Cat" }

catzilla

Probably not what was intended...
Remember that the = actually points to the data. We are just routing pointers here.

Luckily we can fix it easily...

const catzilla = { name: "Catzilla", breed: "Bengal Cat" };

const peanut = { ...catzilla };
peanut.name = "Peanut";

console.log(catzilla); // { name: "Catzilla", breed: "Bengal Cat" }
console.log(peanut); // { name: "Peanut", breed: "Bengal Cat" }

With a help of ... (spread operator) we managed to clone whatever catzilla was pointing to in the new address and made peanut point to it. This is not the original intention, how this operator should be used. But (as it usually happens with JavaScript) this side-effect was warmly accepted by the JavaScript community as a way to perform shallow cloning.

Things start to get really messy with more complicated objects...

const breed = {
  name: "Bengal Cat",
  origin: "United States",
  color: { pattern: "spotted", name: "brown" },
};

const catzilla = { name: "Catzilla", breed: breed };

const peanut = { ...catzilla };
peanut.name = "Peanut";
peanut.breed.color.name = "marble";

console.log(catzilla);
/*
  {
    name: "Catzilla",
    breed: {
      name: "Bengal Cat",
      origin: "United States,
      color: {
        pattern: "spotted",
        name: "marble"
      }
    }
  }
*/
console.log(peanut);
/*
  {
    name: "Peanut",
    breed: {
      name: "Bengal Cat",
      origin: "United States,
      color: {
        pattern: "spotted",
        name: "marble"
      }
    }
  }
*/

It happened again... Both cats have the same color, although it wasn't the intention...

catzilla again

We are performing the so-called shallow clone only top layer (first level of the tree), to make it work properly we need to perform so-called deep cloning. The easiest way would be doing something like...

// ...

const peanut = JSON.parse(JSON.stringify(catzilla));

// ...

Ugly, but does the job. It forces the engine to allocate a new chunk of memory and fill it with object data.
Unfortunately, JavaScript does not provide a good cloning mechanism out of the box. Hence this is the approach to clone the object without employing extra tools.
If you are after a more elegant and efficient solution, I'd recommend using something like underscore.js.

Alright, here's a curly one โšพ... Can you guess why this happening?

console.log({} === {}); // false

Surprised?
Let's try to re-write this example a bit...

const value1 = {};
const value2 = {};

console.log(value1 === value2); // false

Does it make more sense?

To understand it completely we need to understand how the equals == and the strictly equals === operators work, unfortunately, it is not very trivial. However, to prevent this article from bloating, let's just say that comparison happening by actual value in the variable. As we know now it is an address of the object, rather than value. Because we are pointing to two different objects, located by two different addresses. Values are not equal...

two objects

Garbage Collection

The concept of reference (which we just discussed) is what the process of memory releasing/cleaning (aka garbage collection) is based on. Using references garbage collector can determine what is "garbage" and requires a collection and what is not yet.

There are two main algorithms used for that matter.
The "new" one: its variation is used in all modern browsers
And "old" one: nowadays its variation is rarely used anywhere, because of its built-in flaws (we'll talk about them further)

New: Mark And Sweep

Principle lays in finding unreachable objects...
The unreachable object is any object that can't be reached via traversal through references from the so-called root. In browser-world root is represented by the window object (aka Global Scope).

๐Ÿ“ Just a side-note, that all global variables in JavaScript are not hanging in the air, they are rather attached with references to the window object...

Every now and then, garbage collector starts. And follows these phases

  • Start phase: Once started, it assumes that all objects are unreachable.
  • Mark phase: Then the actual tree traversal from the root (through references) starts. Every object found on the way is marked as reachable.
  • Sweep phase: Once traversal is finished all unreachable objects are eliminated.

garbage collection diagram

Optimization

Mark and Sweep algorithm belong to the Tracing Garbage Collection family. There are few family-dedicated optimizations (like tri-color marking). These are low-hanging fruits ๐Ÿ.

Nevertheless, most JavaScript Engines will perform some additional optimizations that are usually borrowed from other garbage-collected languages.

One such classic optimization is the so-called garbage collection based on generations.
The principle is based on one observation. Old objects are less likely to be garbage-collected. They proved it by surviving multiple garbage collections. Thus statistically we can assume these objects will be kept in use.
With this knowledge, we can improve the garbage collection time significantly by simply rarely bothering old objects ๐Ÿ‘ด.

Here is how it works. Each object is assigned to a generation. All objects start at the zero generation. If an object survives garbage collection it moves up, to the next generation. The garbage collection is happening on the young generations more frequently than on old ones.
The more garbage collections object survive the older generation it is assigned to and the less likely it will be collected.
Ultimately this approach reduces traversals through statistically "low-chance-collection" candidates. And focus on those who statistically have higher chances to be collected...

Old: Reference Counting

This algorithm was last used in IE 7 and deprecated since 2012. So this section serves purely historical purposes.

Unlike the Mark and Sweep, this one will try to find unreferenced objects instead of unreachable...
This algorithm does not try to determine whether the object is still needed (in the previous example reachable from the root). Instead, it only checks if anything references the object.

This might not look like a big difference, but this approach is less restrictive. And due to this fact comes with a major flaw.

Major flaw

The major flaw is circular references. Two objects might not be reachable, but as long as they reference each other they won't be collected.

Let's look at the following example...

function catdog() {
  let cat = {};
  let dog = {};

  cat.dog = dog;
  dog.cat = cat;

  return "hello";
}

catdog();

The above code (if used with the current algorithm) creates a memory leak. Because memory allocated for variables cat and dog will never be collected, even though it never used in outer scope...๐Ÿฑ๐Ÿถ

Memory Leaks

๐Ÿค” Why do memory leaks still exist?

Because the process of determining whether a certain piece of memory is used or not is a so-called undecidable problem. Sounds scary, but it means that there's no good way to program a machine to determine if memory can be safely released. Thus only a human can make a real complete judgment about it.

While we were exploring the old garbage collection algorithm we saw an example of a memory leak. It appears that a memory leak is just an accidentally forgotten reference to an object. An object that never going to be garbage-collected. And will keep uselessly occupy memory as long as the application is running. There are quite a few ways to create a memory leak.
Since we know how the memory is allocated and garbage-collected we can look through few most common examples

Global variables

Nowadays usage of global variables is a mauvais ton (bad practice). If happens, it is usually accidental. This problem can be easily caught by the linter ๐Ÿ‘ฎ. Or prevented from happening by adding use strict at the beginning of the file.

The leak happens like this.

  1. We create a global variable (it is automatically referenced by window).
  2. And it forever stays there...

The Fix

Don't use global variables.
It has been recognized as a bad practice for a reason. So the best way to avoid this problem is simply to avoid global variables.

Observers or Forgotten interval timers

This one is harder to trace, we forget to release timers once we don't need them.

This leak happens like this.

  1. We create an interval timer with a callback like setInterval(() => {}, 1000);
  2. We make sure we referencing something from the outer scope
  3. The thing we reference will never be garbage-collected
const memoryLeak = {
  counter: 0,
  massiveData: new Array(100).join('I am your memory leak!');
};

setInterval(() => memoryLeak.counter++, 1000);

The memoryLeak object will never be released even though we might not need the whole object anymore.

The Fix

The best way to prevent this from happening is

// ...

const timerId = setInterval(() => memoryLeak.counter++, 1000);

// do stuff

clearInterval(timerId);

A Camouflaged version of the global variable or Detached DOM elements

Another classical one. If you are working with something like React or Angular, there's no reason to worry. Nevertheless, it is an interesting way to lose some memory ๐Ÿง ...
It is a camouflage version of the global variable memory leak. And it happens even nowadays pretty often, usually in-between the script tags.

This leak happens like this.

  1. We reference arbitrary DOM elements in the code (e.g. by calling document.getElementById('i-will-leak'))
  2. Even though we delete the element from the DOM it still hangs in the lexical scope or global scope (e.g. by calling document.body.removeChild(document.getElementById('i-will-leak')))
<script>
  var memoryLeak = document.getElementById('i-will-leak');
  document.body.removeChild(memoryLeak);
</script>

The memoryLeak will never be garbage-collected, the removeChild here is very misleading, it seems like it will remove the element from everywhere, but it does it only for the DOM tree.

The Fix

The fix is the same as for the Global Variables leak. Don't use global variables ๐Ÿ˜€ Instead, we can use child lexical scope, e.g. function

<script>
  function doStuff() {
    var memoryLeak = document.getElementById('i-will-leak');
    document.body.removeChild(memoryLeak);
  }();
</script>

This is self-executable function will create a local lexical scope and after it will finish execution, all local variables will be garbage-collected.

P.S.

If you've read my previous JavaScript-Runtime-related articles, you know that JavaScript Runtime differs between browsers. Therefore the way memory is managed from browser to browser might be different. Although it would be unfair not to mention that in the past decade more and more commonalities appearing. And reduces a headache for us...
Moreover, given the unstoppably growing JavaScript infrastructure, including various linters, module bundlers, and well-matured frameworks for DOM interactions, problems with memory leaks are reduced to a bare minimum.

But...Garbage collection is still listed as an undecidable problem, hence there's always a way to make a boo-boo. Understanding the way JavaScript organizes the memory and how references are managed might save you hours and hours of debugging.

Anyhow, hope you enjoyed the read and found something new for yourself ๐Ÿ˜€


How we created a web-based typing experiment

Permalink - Posted on 2021-10-19 07:11

We had little time, an experience to build and now to spread.

๐ŸŽฏ The goal of the experiment

The objective of this study is to determine the optimal way to display and to type alphanumeric sequences (such as identifiers, order numbers, etc.). According to research in cognitive psychology, it is easier to read and copy elements that are grouped in chunks of 2 or 3, rather than placed one after the other without grouping. Can we prove it ?
So we made a tiny app everyone can try: https://ux-typing-experiment-five.vercel.app

๐Ÿ› How we created it ?

We had 3 well-known challenges to build this project:

  1. create a web interface
  2. store the data of the experiment
  3. make it available

and a little time dedicated to it :'(

There is a lot of web framework around here (Vue, React, ...Angular) but we wanted to try something different and new. As Svelte becomes well-tooled, we wanted to give it a try. Its minimalist architecture, while being efficient, convinced us. The learning curve is fast. Perfect ! Add a slider and here we go to design each pages.

Hosting the data must be fast and easy. The free tier of Firestore fits our need for this project. Drawing and setup a relational database was overkill for it. Its document-based approach to store data is efficient for our need. One user: one document.

Then we deploy the whole project with Vercel. It is easy, fast and already automated. Moreover Vercel deploy the app for every Pull Request, allowing to make a quick test on the user interface. Thanks for it Vercel.

That's a summary of it. Here some highlights on this project.

๐Ÿšง Some obstacles that we met and how we solved them

svelte-i18n is not reactive. So we stored the i18n keys instead of their value in the objects that we pass around the components. The translated string is handled directly in the view with text expression. Okay ยฏ\(ใƒ„)/ยฏ

Mixing reactivity inside a callback is no good idea. We don't know why but a reactive value inside a callback was not updated on time on keypress. Moving it into a reactive statement solved the problem (see: #adcedf5).

Focusing the first input on the next slide is a must-have for such an experience. It was not so trivial as we thought. We ended up with a small-efficient function, leveraging the Javascript power of DOM manipulation ๐Ÿ˜…๐Ÿ’ช (see: Experiences.svelte#44)

๐Ÿ’ซ Each slide (or page) runs smoothly to the next one

This is a key point to a good experience: it has to be smooth. Any superfluous actions must be avoided and the necessary ones must fit in the flow.

When a user fills a form, a smooth button is displayed to validate the input. So they knows everything is ok and they can go on.

After finishing to type, it transitions to the next one. No button is needed as the input does not have to be checked. Fill the appreciation form after the typing session and go on.

We want to scroll and go further. Thus every slide contains a small amount of information and are reviewed quickly.

We hope these thoughts we had are making the experiment, well, smooth.

Give it a try โค๏ธ

You can participate in this experience too with the following link: https://ux-typing-experiment-five.vercel.app/. You can quit at every moment or you can stay until the end. You choose what the best fit for you ;)
If you find any issues, please feel free to submit an issue on the Github repository.

You can see some results too: https://ux-typing-experiment-five.vercel.app/results

It is again a work in progress. We need first to gather more data, and improve the app.

Original post by Lyokolux --> https://dev.to/lyokolux/how-we-created-a-web-based-typing-experiment-1mdk


Variables Comparison JSโœ

Permalink - Posted on 2021-10-19 07:10

๐Ÿ‘‰ var -> Var can be re-assigned, re-defined and has a function-scope. When we declared outside the function, it has a global scope and it attached itself to the window object.

๐Ÿ‘‰ let -> Let can be re-assigned. Itโ€™s scope is within a block of code.

๐Ÿ‘‰ const -> Const cannot be re-assigned or re-defined. Itโ€™s scope is within a block of code.


Top 5 Best Online Code Editors

Permalink - Posted on 2021-10-19 07:02

Hello Guys ๐Ÿ‘‹ In this blog post i will tell you the top 5 best online code editors (No Downloads!).

Before we move further please subscribe to my youtube channel ( i post coding tutorials ) - https://youtube.com/codingfire?sub_confirmation=1

No 1. Stackblitz

Stackblitz claims to be the fastest, most secure
dev environment on the planet and in my opinion it is actually very fast.. Stackblitz is also very easy to use.

Website Link - https://stackblitz.com/

StackBlitz Image

No 2. Codesandbox

Codesandbox it is pretty famous and i guess many of you who know this website right ?. But for those who dont know let me tell you. it is an online editor for rapid web development. With CodeSandbox, you can prototype quickly, experiment easily, and share creations with a click. Use it to create static sites, full-stack web apps, or components on any device with a web browser.

The best part of codesandbox is that codesandbox is not only available for pc but also for tab / android devices. Good thing right ? ๐Ÿ˜Š

Website Link - https://codesandbox.io/

Codesandbox Image

No 3. Replit

Replit allows users to write code and build apps and websites using a browser. Not only apps and websites but you can also code python in the browser and more. The site also has various collaborative features, including capability for real-time, multi-user editing with a live chat feed. Coooolll...

Website Link - https://replit.com/

Replit image

No 4. Codepen

Now codepen is not just an online code editor. in codepen you can also share your projects with others, discover other projects, follow each other, fork pens and more

Website Link - https://codepen.io

Codepen

No 5. Jsfiddle

JSFiddle is an online IDE service and online community for testing and showcasing user-created and collaborational HTML, CSS and JavaScript code snippets, known as 'fiddles'.

Website Link - https://jsfiddle.net/

jsfiddle

So i think all done. Thankyou for giving your time and reading this blog i hope you liked it

Also dont forget to subscribe to my youtube channel ๐Ÿ˜Š - https://youtube.com/codingfire?sub_confirmation=1 ๐Ÿ™


Fetch both price and product data from stripe in a single api call

Permalink - Posted on 2021-10-19 06:52

Use Case

  • I want to display products in my web app that show the product's name, description and price. Similar to the below screenshot

product card that shows plant picture, product name and price

  • I want to use the Stripe Dashboard as my source-of-truth.

  • Upon visiting my simple store, I would like my customers to receive the latest product information.

The Problem

I tried to fetch all the product data, but that didn't work since it doesn't contain the prices for those products.

I tried to fetch the price data, but the product field only contains an ID for the product and not the rest of the data.

๐Ÿค” "Do I really have to get all of my price data, then iterate over each price just to get the product data?"

Neither the Stripe Price docs or the Product docs address this use case. A quick google search confirmed my initial approach:

StackOverflow answer confirming my initial assumption

But for such a common task, it just wasn't sitting right with me.

The Solution

Special shoutout goes to my buddy Nick (@dayhaysoos). He let me know that prices can use the expand parameter to get the corresponding product information.

After a quick search through the Stripe docs for "expand", the solution became clear:

import Stripe from 'stripe'

const Home = ({ productPriceData }) => {
    console.log({ productPriceData })

    return <div>display stripe data</div>
}

export async function getServerSideProps() {
    const stripe = new Stripe(process.env.STRIPE_SECRET_KEY)

    const productPriceData = await stripe.prices.list({
        expand: ['data.product'], // ๐ŸŽ‰ Give me the product data too
    })
    console.log(JSON.stringify(productPriceData, null, 2))

    return {
        props: { productPriceData },
    }
}

export default Home

๐Ÿ—’๏ธ Quick Notes

  • Expand can be used for just about any API call, but will only go 4 levels deep on what it returns.
  • It's showcased here, but just to be clear, you can dig into an object with dot-notation: data.product.nestedKey.nestedKey2
  • I was going to use the revalidate key in getStaticProps to be cool, but then I realized that if a user refreshes the page, they should always see the correct price.


Infix, prefix, postfix. Is it Matter?

Permalink - Posted on 2021-10-19 06:49

When learning a programming language, of course there are some mandatory things that should not be missed, such as understanding syntax, data types, operators, etc. So in this article, I will discuss about operators.

Operator is actually just a symbol used to perform certain mathematical or logical operations. There are many types of operators, for example: (+), (*), (++). The fact that we will not be able to escape from mathematics in life, especially in mathematical programming language that is functional programming. As one mathematician blogger say:

"After my involving myself in the subject, one thing that stands out is the relatively low distance between thought expressed in my ordinary day-to-day mathematical discourse, and thought expressed in Haskell code."

Most of the time we write mathematical expressions like this:

> 2 + 3

This is a common method used both in programming languages โ€‹โ€‹and in schools. If you look at the code above, the position of the operator (+) is in the middle operand, this is in accordance with the principle The main point of fp is that the value of an expression depends only on the value of its sub-expression.

Infix

Infix is โ€‹โ€‹basically just a method used to perform an operation, where the operator position is placed between the operands, for example like this:

ฮป> 3 + 5 * 2

That's operation is actually interpreted as "First multiply 5 * 2, then add the result by 3, then the final result is 13". Here some questions begin to arise, why the first operation evaluated is `() first, not (+)? Shouldn't the result be 3+5=8*2=16`??*

Ok, the answer is because all these operators have their own priority, in this table 9 is the highest. I found this out while reading fixity declarations on haskell.

+--------+----------------------+-----------------------+-------------------+
| Prec-  |   Left associative   |    Non-associative    | Right associative |
| edence |      operators       |       operators       |    operators      |
+--------+----------------------+-----------------------+-------------------+
| 9      | !!                   |                       | .                 |
| 8      |                      |                       | ^, ^^, **         |
| 7      | *, /, `div`,         |                       |                   |
|        | `mod`, `rem`, `quot` |                       |                   |
| 6      | +, -                 |                       |                   |
| 5      |                      |                       | :, ++             |
| 4      |                      | ==, /=, <, <=, >, >=, |                   |
|        |                      | `elem`, `notElem`     |                   |
| 3      |                      |                       | &&                |
| 2      |                      |                       | ||                |
| 1      | >>, >>=              |                       |                   |
| 0      |                      |                       | $, $!, `seq`      |
+--------+----------------------+-----------------------+-------------------+

The table above relates to the order in which operations will be evaluated first.

After seeing how the priority/precedence/precedence is for each of the operators above, this time the case is slightly different, namely by adding brackets ( )

ฮป> (3 + 5) * 2

That's operation mean's "first add 3 and 5, then multiply by 2, then the final result is 16. The question arises again, instead of `() having priority 7 > 6 (+)`??*

Ok, this is because infix notation has a rule that if there is a parenthesis ( ) then the highest priority is ( ) which is worth 13. So the result is 16.

Prefix (aka Polish)

Prefix otherwise known as "Polish notation", where the position of the operator is written before the operand. The expression is like this /* A + B C D. Take a look at the code below:

> (+) 3 5 * 2

In the prefix operation, evaluation is carried out from left to right, based on the two values โ€‹โ€‹closest to the right. If you refer to the code above, it means "first add 3 and 5, then multiply by 2, then the final result is 16". The first evaluation occurs at (3 + 5) because these two numbers are close to each other, just multiply by 2."

I give another case, an example of an expression like this + * 2 10 / 14 2. Evaluation happens "First multiply 2 and 10, divide 14 by 2, last 20 + 7 = 27".

By the way the prefix notation doesn't support brackets ( ), so it won't have any effect. Haskell has no prefix operators, with the exception of minus (-), which is both infix and prefix.

Postfix (aka !Polish)

Postfix is โ€‹โ€‹called "reverse polish notation", where the operator is at the end of the operand. This notation is used in several old programming languages โ€‹โ€‹such as Forth and Postscript . Take a look at the code below:

ฮป> (!) :: Bool -> Bool
ฮป> (!) = not
ฮป> (True !)

In haskell itself to support postfix operators, yo've to use syntax extensions on GHC, so you don't get scolded by the compiler.

Yes, that's 3 kinds of notation used in writing expressions. Although prefer to infix syntax because it is easier to read, each has its own purpose and purpose. This article is important for you, especially those who are learning functional programming, where mathematics happens everywhere.

But most importantly, I hope this article is useful, Thanks!