Fresh Resources for Web Designers and Developers (August 2019)

It’s time for another monthly round of featuring some top resources for our fellow web developers. Previously, in the Fresh Resources series, we have mostly featured tools and apps for designers and developers.

This month, however, we have more resources that help you brush up your skills as a web developer. We have a tip for using SVG, a resource to learn more about TTFB, information on creating an accessible UI, and many other interesting subjects. Let’s take a look

SVG Role Image

Here is a handy tip on using SVG. SVG is used to display a graphical presentation on your website like an image. Yet, unlike the img element, SVG may consist of multiple elements like the path, g, or circle.

svg role imagesvg role image

What is TTFB?

Ever wondered why your site seems to be loading slow, even though you’ve done all the optimization advised on the Internet? Well, the problem might be detected on the site TTFB or “Time to First Byte”. So, this article from CSS Wizardry will give a full insight on TTFB and how you may be able to optimize it.

what is ttfbwhat is ttfb

Custom Accessible Radio Input

The Accessibility feature is what makes the web great. It allows people with disabilities to browse and interact with the web. This article from Lindsey will teach you how to create a nice looking accessible radio input. You’ll see that creating an accessible UI does not necessarily mean it has to look dull.

custom accessible radio inputcustom accessible radio input

Simple Entity Decode

A small JavaScript library that allows you to decode characters from their HTML form to their human-readable form. For example, you can convert & to &.

simple entity decodesimple entity decode

Gatsby Theme Authoring

Creating a static site is on the rise (again) because it’s blazing fast. One of the tools that are on the rise among web developers is the Gatsby. Egghead provides a screencast to learn how to create a theme for Gatsby. And it’s free.

gatsby theme authoringgatsby theme authoring


Postwoman is a web-based tool to compose an API request. You can set the request method, URL, path, parameters, authentication etc., and see the response — a convenient tool.



It’s a modern Shell built with Rust. It enhances a few Shell commands, for example, the ls command. Nushell can show the output of the ls command with enriched data as we can see from the following image.


What is ES2019

JavaScript has vastly improved in the past few years. It seems the ES6 or ES2015 was just yesterday, but we now have a new spec codenamed ES219. This video from JSConf EU will show you a glimpse of what we can do in JavaScript with the ES2019 specification.

what is ES2019what is ES2019


A collection of tutorials that’ll teach you Docker and Kubernetes. Not only that it provides text-based tutorial, but you can also try them right in your browser.

Moreover, you do not need to install anything on your computer. All you need to experience Docker like Docker Engine, Docker Compose & Docker Machine are already set so you can start learning.



Kanboard is a PHP-based application for Kanban board. Using Kanban board is a popular style to manage tasks and projects. There are a few commercial applications that you can immediately use like Trello. If you’re the type of person who prefers full control over your app, using Kanboard may be a good alternative as you can install it in your server.


Tech Interview Handbook

A collection of examples, tips, and cheatsheets to help you better prepare for an interview in the tech sector. If you’re in the process of job search, you might find this useful.

tech interview handbooktech interview handbook

Vuestic Admin

An admin dashboard template built on top of Vue.js. It comes with UI components that you’ll usually need to build a useable Admin dashboard like the Chart, data tables, forms, and many more.

vuestic adminvuestic admin

Git Training Kit

Here is an in-depth reference for using Git provided by Github. A useful reference to learn Git whether you’re just getting started or has already some experience.

git training kitgit training kit

Nginx Admin Handbook

A collection of tips on making most of nginx. The nginx covers many topics including security, debugging, and of course, the basics.

nginx admin handbooknginx admin handbook


A JavaScript library that allows you to create a Terminal-like interface that you can run on the web.


Pure Bash Bible

Tips, code examples, best practices, and basically a complete package of learning materials to master Bash.

Pure Bash BiblePure Bash Bible


Polka is a simple HTTP server built with Node. It supports routing, middleware, and sub-applications. It’s a great alternative to Express.js. In fact, it performs faster by 30-50%.


Design Patterns PHP

“Design Pattern” is created to solve common problems when developing an application. This is one of the most complete references to learn Design Pattern in PHP.

Design Patterns PHPDesign Patterns PHP

Code Samples

As the name implies, this is a collection of code samples provided by Microsoft. It is pretty extensive, ranging from C to PHP programming language.

Code SamplesCode Samples


A collection of UI component based on Vue.js framework. Like a typical framework, iView is equipped with UI Components, from an essential element like a button to a more complicated component like a Carousel.


The post Fresh Resources for Web Designers and Developers (August 2019) appeared first on Hongkiat.

Read more:

Read More

10 Most Common Types of Web Developers

How many developers do you know in your life? If you work with a group of them, you might notice that they have particular quirks or personalities that you can actually group together, which is what I’m going to do with this post.

Developers have their individual preferences and work style that are very different – even if they do the same jobs. We’re going to take a look at the 10 most common groups of developers out there; see if you’re able to either spot yourself or one of your colleagues in there.

1. The Purists

Purists by definition are people who stick to traditional rules, you might know an English teacher or two who is purist by nature. The purists in my list though aren’t that strict, they are just the kind of developers who aren’t very keen on using frameworks and libraries.

They’ll pick Vanilla JavaScript over JQuery every time. They don’t see any trouble in using pure languages and traditional ways; in fact, they get annoyed when they stumble upon yet-another-framework or library. Extra libraries equal bloat for them.

The PuristsThe Purists

Mind you, this does not mean that they don’t use those in real life. It’s hard not to, when job vacancies these days ask for “expertise in jQuery”. No matter how uptight or close minded they may seem, you can’t turn a blind eye to the truth in their argument.

2. The Doers

Sure everyone has to get their job done, no matter what, but for the Doers, their list of priorities start with getting the job done. You can bet they have the latest and fastest framework, libraries and workflow set up. They have premade modules for modules, all sorted for quick use in projects.

Doers dwell in start-ups while implementing all those tools for smooth production. A typical doer’s telltale symptom is the use of a task runner like grunt or gulp.

3. The Polyglots

Polyglots are the ones who use multiple programming languages; some even are full stack developers juggling SQL and SASS like a circus juggler. That said, working in only one programming language is near impossible in web development; you can’t escape that fate, even if you’re a backend developer. So only when you know at least 4-5 programming languages, do you get to boast that you’re a polyglot.

The PolyglotsThe Polyglots

Most polyglots are who they are because of their work situation rather than by choice. Not everyone gets to have separate frontend developers or designers. Either way, they approach a new language with a lot more confidence than anyone else and are quick learners. No need to feel overwhelmed by them though, because some of them might be Jack of all trades but are masters of none.

4. The Perfectionists

What comes to mind when I say perfectionist programmer? Well, I don’t mean the ones who aim to write the most perfect, flawless of codes. The real perfectionists are the ones who look, code and go beyond coding. They leave comments, pay attention to naming variables and do the dirty work aka documentation (among other things).

Let’s face it, when was the last time you left a detailed comment or wrote a manual for your software? Not anytime recently I believe, not unless and until you’re a perfectionist. They’re rare in my opinion. Most developers don’t pay attention to those (though documentation is real important. Here’s Thoriq Firdaus’s take on it).

5. The Artsy

In terms of web development, let’s just say their mother tongue is CSS. Shapes, colours, animations, filters and all the other visual stuff matter to them the most. Wanna meet them? Codepen is their usual hub.

The ArtsyThe Artsy

They’re not designers, or maybe they are, but at ground level they are developers. They express their art with code rather than Adobe Illustrator or After Effects. Pairing them with a designer is like spreading butter on bread, resulting in a smooth and great combination.

6. The Reuser

Not every one of us are keen to jump in first thing to write a generic class or method to handle repeating blocks of code. We leave that part out until the optimization stage which occurs only after we’ve gracefully crossed the big red solid 10px deadline and the brief relaxation period following that.

Reusers know better than that, they make a solid foundation of reusable code snippets from the beginning itself and saves plenty of optimizing time later. They’re mostly experienced developers who can foresee a block of code that is bound to make multiple appearances. There is probably not a single project of theirs that is without a fully filled global file or a utility class.

7. The Bookworms

A day before my very first VB Lab, my Professor gave us a set of brief instructions, to put together a form. She ran a demo at the beginning of the class, which I unfortunately missed because I got in late. The bits of instructions I managed to jot down was not enough to save me and I was seated too far from my friends for any sign language or lip reading to help.

The BookwormsThe Bookworms

So I did the only thing I could do – I opened my good old textbook. I became a bookworm. As a result, not only did I get a praise from my Professor at the end of the class for managing to put all the requirements together in my form, I also added a background image – which no one else in class did – based on what I learned from the textbook.

It is not uncommon for me to find some of my associates who are really good at programming and logic to have desks that are stacked and covered with books. Bookworms take to the texts in pursuit of in-depth knowledge, sometimes gained serendipitously, which is ultimately the best kind!

8. The Debuggers

Debugging is a skill in itself. Its true power can only be brought out when the page shows “Internal Server Error 500”. Debuggers are not only capable of catching and squashing the bugs in their own code but in codes written by others too (which is a developer’s nightmare in its own right)!

The DebuggersThe Debuggers

They are well versed with all debugging tools and options whether it’s on a browser or an IDE. But tools aside, debugging requires the clear knowledge of a flow of events and the ability to spot the trigger in that chain.

If the code belongs to someone else, that’s when Debuggers show their true observation prowess, going through lines upon lines of code, looking for any missing ‘if’, ‘else’, ‘or’, ‘and, or a semi-colon

9. The Researchers

For the Researchers, code is not just a code for them; it becomes a topic; a topic for forum discussion, a topic for a blog post, a topic for a StackOverflow Q&A. No preaching, no judging, just a sharing of knowledge that they put an effort into dissecting. Every code we write has a use and a purpose and unfortunately a side effect, sometimes.

The Researchers among us try to understand that aspect of code. They dig out documentations, conduct experiments and most importantly share their findings for the rest of us who will be eternally grateful for what they do.

10. The Sociables

Despite copying codes off one another, we still stick together as part of a community who eats, breathes and lives code. Physically though, we sit in front of the computer by ourselves, alone though not lonely. Our social skills do take a hit though, whether we like it or not.

The SociablesThe Sociables

And then, there are the Sociables. They meet up with you for drinks, tell geeky jokes, talk about the latest and greatest about the field, are excited about upcoming releases, hardware or soft, engage in opportunities, networking possibilities, and if time permits, swap phones with you so you can both try out a different OS. Do you know a Sociable amongst your developer friends?

Wrap Up

Some of you are bound to find a friend, yourself, as part of a few groups, sometimes overlapping, other times contradicting – we don’t judge, in the end, we are all developers. But we are curious to know which of the groups of developers you find yourself most allied to. Let us know in the comments.

The post 10 Most Common Types of Web Developers appeared first on Hongkiat.

Read more:

Read More

Why All Developers Should Learn Command Line

Some developers cringe at the mere thought of opening a terminal window. For the uninitiated it can be daunting, stressful, and downright annoying. But devs who understand the command line would argue it’s one of the best tools at your disposal.

So how necessary is the command line for modern development? I’d argue it’s imperative to success, working with either frontend or backend code. The command line has become a Swiss Army knife of features locked behind simple commands. If you take time to learn these commands you may be surprised how much power is available from that little black rectangle with the flashing white cursor.

You Gain Greater Control over System Functions

Perhaps the most obvious reason to learn the command line is for its original function: greater control. There are commands accessible only via shell that can control very complex operations on Unix/Linux and Windows machines.

command linescommand lines

Basic commands might involve changing permissions on a certain file or browsing to a directory that’s hidden from view. More complicated examples could involve server administration for a local server setup like Apache/MySQL.

It’s worth at least exploring the possibilities of shell commands just to understand how they work. Ignoring a piece of technology just because it’s too confusing is rarely a good idea.

But looking beyond system functions we have a slew of web developer tools which operate through the command line. Not everything can be downloaded & installed like an application, so an understanding of shell commands will save you the headache of learning how to install the latest new tools for developers.

You Can use NPM for Package Installs

Node Package Manager is easily the most popular tool for modern developers. This is built on top of Node.js which behaves as a JavaScript framework for other scripts (like NPM).

One thing to note is that NPM does not have a GUI. There’s no way to click a little “install” button like you’d find on the Mac App Store. Every package must be installed manually via the npm command in a terminal window.


This may seem annoying to non-shell users but it actually offers much more control. The NPM library contains over 200,000 packages with more added every week. It’s just easier to host these externally and let the user decide what to install.

Keep in mind that some of these tools can be installed separately via their own binary installers. But NPM centralizes everything so you can pull all of your favorite tools with one friendly command: npm install.

With NPM you have instant access to a number of tools like:


Another popular choice is to install Ruby gems alongside NPM packages. However Ruby gems are not exactly part of a package manager – though they can act in a similar fashion.

ruby gemsruby gems

Either way both techniques require an understanding of rudimentary CLI commands. You can be working with NPM in less than an hour if you make time to practice and really understand how it works.

You Can Utilize Git Version Control

Programmers and developers alike should understand the power of version control. The ability to split/merge a project into separate versions is simply unparalleled.

Unfortunately Git is also difficult to learn if you don’t already understand how it operates. Now add the confusion of working inside the command line and it’s clear why Git scares off so many developers.

Thankfully there are many free resources online to help you understand the basics.

Try Git is a free learning tool on GitHub to help you toy around in Git without installing it locally. This is a guided tutorial for developers with absolutely no knowledge of version control.

try github tutorialtry github tutorial

The difficulty of Git is memorizing version control commands while simultaneously learning the command line. There are desktop apps that offer a GUI but they still expect you to understand the fundamentals of version control (cloning, branching, merging, etc).

For a beginner the learning curve for Git can be steep. With regular practice it still might take a couple months to solidify the concepts. But Git is an indispensable tool for every developer and it’s one more good reason to learn the command line.

You Need It To Use Preprocessors & Task Runners

Frontend development has changed a lot in recent years. We have preprocessors like Sass/Less for CSS and Haml/Jade for HTML. We also have task runners like Gulp and Grunt for automating tasks via JavaScript. It’s almost a completely new landscape where these techniques are practically required to build modern websites.


CSS Preprocessors compared: Sass vs. LESS
The battle of build scripts: Gulp vs. Grunt

If you aren’t already aware, tools like Sass and Haml run directly through the command line. Both of those preprocessors are built on Ruby and require terminal commands for compiling code. Granted you could setup a Gulp task to automate preprocessing, but this also requires command line knowledge.

With these tools becoming necessary to the development process it’s vital to understand even the basics of shell scripting and the command line.

It’s For Local Backend Development

Everything from PHP to Rails and Python requires some command line interaction. Installation tools like MAMP have made things easier, but there’s no substitution for the raw power of working in the command line.


While PHP can be installed using software like MAMP, frameworks like Laravel require Composer which is a dependency manager. This installation process takes place almost entirely via the command line.

The Django framework requires a similar CLI install process on top of pip, a free Python package manager. Also consider the process of setting up your own local server on Node.js. To do this you’ll want to first understand your computer’s environment(Unix or Windows). Then you’ll want to understand the basics of Node.js.


With some comfort in shell scripting you’ll have more control over your machine to install packages, check for updates, restart a local server, and install modules for enhanced features.

No matter what language you’re using or trying to learn, the command line will prove to be a powerful tool in your arsenal. Even a very basic understanding of shell scripting can improve your confidence and workplace value in a market of talented web developers.

Moving Forward

No matter what type of development you do, there’s value in understanding the command line. Even basic concepts like installing Ruby or Composer will prove immeasurably useful during your career as a web developer.

To get started just find something you want to learn and dive in. This could be compiling with Sass, installing Laravel, or configuring a local Node.js server. Naturally you’ll face challenges along the way but websites like Stack Overflow contain all the programming answers you need.

As more tools rise to popularity in the years to come you’ll be glad to have an understanding of command line syntax. The future of web development is not in IDEs, but in open source tools that optimize the way we code and build websites.

The post Why All Developers Should Learn Command Line appeared first on Hongkiat.

Read more:

Read More

How to Teach Kids to Code with MIT Scratch Language

Children learn differently than adults, therefore if we want to teach them to code, we need to use an approach suitable to their needs. Adults’ coding courses usually start with explaining building blocks, such as data types, variables, and functions, however this teaching method doesn’t fit well with most kids.

Visual block languages offer a solution to this issue by introducing learners to coding with the help of visual building blocks. Block languages (sometimes also called bubble languages) focus on logic rather than on syntax, and teach coding via creative projects.

A handful of great apps teaching block languages, such as Scratch,, and Tynker, are available on the net (Scratch and are free, and Tynker comes at a friendly price).

One of the best thing about them is that you don’t necessarily have to be a programmer to help your kids get started with them. In this article, we’ll have a look into Scratch, a visual block language developed by Google and the MIT Media Lab.

Scratch Home PageScratch Home PageGet started

Scratch is a programming language created for educational purposes, in which you need to snap blocks together in order to create different projects, such as animations, games, and interactive stories.

Scratch is primarily created for children and teenagers between the ages of 8 and 16, but in some cases it can work for younger kids and adult learners as well.

Scratch is available in more than 40 languages, its latest version is Scratch 2 that runs in more recent web browsers on Windows, Mac, and Linux machines. If you have problems with the system requirements, you can use its earlier version, Scratch 1.4, as well.

You can use Scratch in 3 different ways:

Create an online account, and use the online editor. If you choose this, you can save your projects online, and share them with the Scratch community.
Use the online editor anonymously. If you choose this, you can save your projects only to your computer.
Download the Scratch Offline Editor, and work locally.

To get started, click the Create menu in the top menu bar, and the Scratch editor will appear on your screen.

Scratch EditorScratch EditorCreate the design

First, let’s add the design elements to our program. The workflow of real-life programming is basically the same, first we need to create the design elements, such as backgrounds, buttons, and navigation (this part is usually done by a designer), then we need to add functionality to them with code (this part is done by a programmer).

Sprites and backdrops

Scratch offers two different kind of design elements: backdrops and Sprites.

The term “backdrop” stands for the background, and the term “Sprite” stands for the characters (the default character is the cat you can see on the screenshot above). Their related settings are in the bottom left corner, below the stage.

There are four ways to add a new backdrop or Sprite to the stage, you can choose one from a predefined library, paint one, upload one from your computer, or take a photo with your web camera.

Now let’s use the quickest solution, and choose a backdrop from the Backdrop Library.

Backdrop LibraryBackdrop Library

Also let’s choose one or more Sprites from the Sprite Library by clicking on the little sprite icon next to the “New sprite” label in the bottom left corner of the screen.

Sprite LibrarySprite Library

If you want, you can edit both the backdrop and the Sprites with the help of a handy image editor that automatically appears after you add a new design element to the stage.

Below, you can see my screen right after I added the “Night city” backdrop to my stage — if I wanted I could change the looks of the backdrop with the drawing tools of the image editor.

Night City BackdropNight City Backdrop

In this article, I will create a simple animation about a girl who is scared by a ghost in a night city (I know…). I already have the night city backdrop, and now I need two Sprites: a girl and a ghost.

I don’t need the default cat, therefore I right-click on it, and remove it. I add the girl and the ghost from the Sprite library. As the ghost is bigger than the girl, and they look awkward next to each other, I resize the ghost using the image editor.

Resize GhostResize Ghost

Now I have all the design elements I need. Below you can see how my stage looks like right now. In the next section, we’ll add functionality to the two Sprites (the girl and the ghost) by using Scratch blocks.

Initial SetupInitial SetupAdd functionality

The Scratch blocks that can be found under the “Scripts” tab. Behind each block there is an underlying code snippet.

Blocks are grouped into 10 categories (Motion, Looks, Sound, Pen, Data, Events, Control, Sensing, Operators, More blocks), each of them use a different color, this way the block groups are easily distinguishable.

Scripts PanelScripts Panel

We will add functionality to each Sprite (specifically we’ll animate them), which means each Sprite will have its own script (sequence of Scratch blocks).

Note that we could add a separate script to the backdrop as well, for instance change its colors from day to night, however for the sake of simplicity we won’t change the backdrop in this example.

Create a human-readable algorithm

It can be helpful to plan out on paper what your Sprites will do. Here is the algorithm of our girl-ghost example program.

The girl’s algorithm:

The user starts the script.
The girl thinks about how much she’s afraid.
The girl is waiting until the ghost attacks her.
The girl screams.
The girl runs away.

The ghost’s algorithm:

The user starts the script.
The ghost is waiting while the girl is thinking.
The ghost approaches the girl.

You can see that the girl’s algorithm is written from the girl’s perspective, and the ghost’s algorithm is written from the ghost’s perspective. While one character acts, the other one needs to wait, as we need to synchronize the actions of the two characters.

The ghost’s script

Let’s start with the ghost’s script, as it’s only 3 steps. Click on the Ghost in the bottom-left corner, and you can start dragging the blocks to the Script area. First we need to make the user to start the program. We can easily do this by adding the “when green flag clicked” block from the “Events” category.

Next, the ghost waits 2 seconds while the girl is thinking. We program this action with the “wait 2 secs” block that can be found in the “Control” category.

Finally, the ghost needs to approach the girl, which we can achieve with the “go to Abby” block from the “Motion” category. “Abby” is the girl’s name, Scratch automatically adds the names of the other Sprites to the dropdown menu of this block.

Ghost's scriptGhost's script

This is how the ghost’s script look like. By now, you’ve certainly realized that Scratch works similarly to LEGO, you need to join the blocks together.

The girl’s script

The girl’s script is a little more complicated. Click on the girl’s Sprite in the bottom left corner, and you can start adding the blocks related to the girl’s behaviour.

The girl’s script also starts with the “when green flag clicked” block. I show you now how the girl’s script will finally look like, so that you can follow the explanation more easily.

Girl's scriptGirl's script

After the green flag is clicked, the girl is thinking for 2 seconds (the program will show a thinking bubble for this period), this is the same 2 seconds while the ghost is waiting in the corner — programmed with the waiting block in the ghost’s script.

Then, the girl needs to wait until the ghost touches her. This is done by a composed waiting block. You can see on the above screenshot that this block includes an inner diamond-shaped block you need to join separately. You can add only diamond-shaped blocks to this waiting block.

Remember, Scratch is similar to LEGO, you need to pay attention to the shapes of the blocks as well. This feature prevents you from adding blocks that shouldn’t be there in order to avoid a wrong coding logic.

By now, the ghost touched the girl, and the ghost’s script ended. Now we need to make her scream with a “play sound” Sound block (I added the female scream sound from the built-in Sound Library), and finally make her move away from the ghost by using the “move 200 steps” Motion block.

You can have a look at the final project on its Scratch page. If you want to have a look into the building blocks, click the See inside button on the top right corner.

Final project pageFinal project pageNext Steps

Our “Ghost in the city” example is a very simple project. When your kids can safely create linear stories and animations, you can move towards more complicated coding structures, such as if-then blocks (conditional statements) and repeat blocks (loops), both can be found in the “Control” category.

If you want a more complicated example for a linear animation (still without conditional statements and loops) you can check out my other demo that features a simple dialogue, and uses 3 Sprites (two friends and a birthday cake), each of which has its own script.

Birthday cake demoBirthday cake demo

You can also inspire your children by printing Scratch Cards to them, that they can hold in their hands while programming. Scratch Cards also have great project ideas on them. It’s also worth learning from others by exploring existing projects, or taking part in discussion forums.

If you want to understand Scratch better, there’s a free Coursera course by The University of Edinburgh, that introduces beginners to Scratch programming in a very accessible, even enjoyable way.

You can also take leverage of the Scratch Wiki, and the Harvard University’s Creative Computing department also has some great resources for Scratch learners.

The post How to Teach Kids to Code with MIT Scratch Language appeared first on Hongkiat.

Read more:

Read More

Understanding Synchronous and Asynchronous JavaScript – Part 1

Synchronous and asynchronous are confusing concepts in JavaScript, especially for beginners. Two or more things are synchronous when they happen at the same time (in sync), and asynchronous when they don’t (not in sync).

Although these definitions are easy to take in, it is actually more complicated than it looks. We need to take into account what exactly are in sync, and what aren’t.

You’d probably call a normal function in JavaScript synchronous, right? And if it’s something like setTimeout() or AJAX that you’re working with, you will refer to it as being asynchronous, yes? What if I tell you that both are asynchronous in a way?

To explain the why, we need to turn to Mr X for help.

Scenario 1 – Mr X is trying synchronicity

Here’s the setup:

Mr X is someone who can answer tough questions, and carry out any requested task.
The only way to contact him is through a phone call.
Whatever question or task you got, in order to ask Mr X’s help to carry it out; you call him.
Mr X gives you the answer or completes the task right away, and lets you know it’s done.
You put down the receiver feeling content and go out for a movie.

What you’ve just carried out was a synchronous (back and forth) communication with Mr X.
He listened as you were asking him your question, and you listened when he was answering it.

Wire PhoneWire PhoneScenario 2 – Mr X isn’t happy with synchronicity

Since Mr X is so efficient, he starts receiving many more calls. So what happens when you call him but he’s already busy talking to someone else? You won’t be able to ask him your question – not till he is free to receive your call. All you will hear is a busy tone.

So what can Mr X do to combat this?

Instead of taking calls directly:

Mr X hires a new guy, Mr M and gives him an answering machine for the callers to leave messages.
Mr M’s job is to pass on a message from the answering machine to Mr X once he knows Mr X has completely finished processing all previous messages and is already free to take a new one.
So now when you call him, instead of getting a busy tone, you get to leave a message for Mr X, then wait for him to call you back (no movie time yet).
Once Mr X is done with all the queued up messages he received before yours, he will look into your issue, and call you back to give you an answer.

Now here lies the question: were the actions so far synchronous or asynchronous?

It’s mixed. When you left your message, Mr X wasn’t listening in to it, so the forth communication was asynchronous.

But, when he replied, you were there listening, which makes the return communication synchronous.

I hope by now you have acquired a better understanding of how synchronicity is perceived in terms of communication. Time to bring in JavaScript.

JavaScript – An Asynchronous Programming Language

When someone labels JavaScript asynchronous, what they are referring to in general is how you can leave a message for it, and not have your call blocked with a busy tone.

The function calls are never direct in JavaScript, they’re literally done via messages.

JavaScript uses a message queue where incoming messages (or events) are held. An event-loop (a message dispatcher) sequentially dispatches those messages to a call stack where the corresponding functions of the messages are stacked as frames (function arguements & variables) for execution.

The call stack holds the frame of the initial function being called, and any other frames for functions called via nested calls on top of it .

JavaScript Call StackJavaScript Call Stack

When a message joins the queue, it waits until the call stack is empty of all frames from the previous message, and when it is, the event-loop dequeues the previous message, and adds the corresponding frames of the current message to the call stack.

The message waits again until the call stack becomes empty of its own corresponding frames (i.e. the executions of all the stacked functions are over), then is dequeued.

Consider the following code:

function foo(){}
function bar(){
function baz(){

The function being run is baz() (at the last row of the code snippet), for which a message is added to the queue, and when the event-loop picks it up, the call stack starts stacking frames for baz(), bar(), and foo() at the relevant points of execution.

Pushing Frames into Call StackPushing Frames into Call Stack

Once the execution of the functions is complete one by one, their frames are removed from the call stack, while the message is still waiting in the queue, until baz() is popped from the stack.

Popping Frames from Call StackPopping Frames from Call Stack

Remember, the function calls are never direct in JavaScript, they’re done via messages. So whenever you hear someone say that JavaScript itself is an asynchronous programming language, assume that they are talking about its built-in “answering machine”, and how you’re free to leave messages.

But what about the specific asynchronous methods?

So far I’ve not touched on APIs such as setTimeout() and AJAX, those are the ones that are specifically referred to as asynchronous. Why is that?

It’s important to understand what exactly is being synchronous or asynchronous. JavaScript, with the help of events and the event-loop, may practice asynchronous processing of messages, but that doesn’t mean everything in JavaScript is asynchronous.

Remember, I told you the message didn’t leave until the call stack was empty of its corresponding frames, just like you didn’t leave for a movie until you got your answer — that’s being synchronous, you are there waiting until the task is complete, and you get the answer.

Waiting isn’t ideal in all scenarios. What if after leaving a message, instead of waiting, you can leave for the movie? What if a function can retire (emptying the call stack), and its message can be dequeued even before the task of the function is complete? What if you can have code executed asynchronously?

This is where APIs such as setTimeout() and AJAX come into the picture, and what they do is… hold on, I can’t explain this without going back to Mr X, which we’ll see in the second part of this article. Stay tuned.

The post Understanding Synchronous and Asynchronous JavaScript – Part 1 appeared first on Hongkiat.

Read more:

Read More