DEV Community

Cover image for Types of function and Threads & Process and Synchronous vs Asynchronous in javascript
Kamalesh AR
Kamalesh AR

Posted on

Types of function and Threads & Process and Synchronous vs Asynchronous in javascript

Types of function:

1. Named Function

A function that has its own name when declared. It’s easy to reuse and debug because the name shows up in error messages or stack traces.

Example:

function greet() {
  return "Hello!";
}
console.log(greet());
Enter fullscreen mode Exit fullscreen mode

Output:

Hello!
Enter fullscreen mode Exit fullscreen mode

2. Anonymous Function

A function that does not have a name. It is usually assigned to a variable or used as a callback. Since it has no name, it cannot be called directly.

Example:

const greet = function() {
  return "Hi there!";
};
console.log(greet());
Enter fullscreen mode Exit fullscreen mode

Output:

Hi there!
Enter fullscreen mode Exit fullscreen mode

3. Function Expression

When you assign a function (can be named or anonymous) to a variable. The function can then be used by calling that variable.

Example:

const add = function(a, b) {
  return a + b;
};
console.log(add(2, 3));
Enter fullscreen mode Exit fullscreen mode

Output:

5
Enter fullscreen mode Exit fullscreen mode

4. Arrow Function (ES6)

A new way to write functions using the => syntax. They are shorter and do not have their own this binding, which makes them useful in some cases.

Example:

const square = n => n * n;
console.log(square(4));
Enter fullscreen mode Exit fullscreen mode

Output:

16
Enter fullscreen mode Exit fullscreen mode

5. Immediately Invoked Function Expression (IIFE)

IIFE functions are executed immediately after their definition. They are often used to create isolated scopes.

Example:

(function () {
    console.log("This runs immediately!");
})();
Enter fullscreen mode Exit fullscreen mode

Output:

This runs immediately!
Enter fullscreen mode Exit fullscreen mode

Process

Process is a program that is currently in execution within an operating system. It operates in an independent environment and is managed by the OS for proper scheduling and execution. Processes form the basis of program execution in a multitasking system. Its Properties are:

  • Each process has a unique Process ID (PID) for identification.
  • Every process moves through different states such as new, ready, running, waiting, and terminated.
  • Processes communicate with each other using Inter-Process Communication (IPC) methods.

Real-Time Example of Process

Imagine you have Google Chrome, Spotify, and VS Code running on your computer.

Chrome = Process
Spotify = Process
VS Code = Process

Each application has its own memory and resources.

If Chrome crashes, Spotify and VS Code continue running because they are separate processes.

Easy understanding:
Process = Building
Each building has its own electricity, water, and rooms.

Thread

Thread is a smallest unit of execution within a process. It enables a program to perform multiple tasks concurrently while sharing the same memory and resources. Threads improve application performance and responsiveness in multitasking environments. Its properties are:

  • Each thread has its own Thread ID (TID) for identification.
  • A thread also moves through states such as new, runnable, running, waiting, and terminated.
  • Threads within the same process share memory and resources, enabling faster communication.
  • Context switching can occur between threads to allow multiple tasks to execute efficiently.

JavaScript is traditionally single-threaded, meaning it executes one task at a time using a single call stack.

Example:

console.log("Start");
console.log("Middle");
console.log("End");
Enter fullscreen mode Exit fullscreen mode

Output:

Start
Middle
End
Enter fullscreen mode Exit fullscreen mode

Real-Time Example of Thread

Inside Chrome, many tasks run simultaneously:

Rendering a webpage
Playing a YouTube video
Downloading a file
Handling user clicks

These tasks are performed using multiple threads within the Chrome process.

Easy understanding
Thread = Employees inside the building
Employees share the building's resources and work together on different tasks.

Synchronous and Asynchronous in JavaScript

JavaScript is a single threaded programming language used for web development. It supports synchronous and asynchronous execution. In synchronous execution, statements run one after another, and each task waits for the previous one to finish. In asynchronous execution, some tasks run in the background without stopping the execution of other code.

Synchronous JavaScript

Synchronous programming executes code in sequence, where each statement waits for the previous one to complete before running. This makes the flow simple and predictable.

"Synchronous means tasks are executed one after another. The next line of code waits until the current line finishes executing."

  • Tasks run one after another in a fixed order.
  • Time-consuming operations can block the execution of other code until they finish.

Example:

console.log("Hi");
console.log("Vicky");
console.log("How are you?");
Enter fullscreen mode Exit fullscreen mode

Output:

Hi
Vicky
How are you?
Enter fullscreen mode Exit fullscreen mode

In the above code, “Hi” is logged first, then “Vicky”, and finally “How are you”. Each statement executes only after the previous one completes.

Asynchronous JavaScript

Asynchronous programming, on the other hand, allows multiple tasks to run independently of each other. In asynchronous code, a task can be initiated, and while waiting for it to complete, other tasks can proceed. This non-blocking nature helps improve performance and responsiveness, especially in web applications.

"Asynchronous means some tasks can start now and finish later without blocking the execution of other code."

  • Call Stack: Functions are executed in the order they are called. Each function is added to the stack and completed before the next one runs.
  • Web APIs: Functions like setTimeout, HTTP requests, and event listeners are handled by browser Web APIs without blocking the call stack.
  • Callback Queue: After a Web API completes its task, the callback function is moved to the callback queue.
  • Event Loop: The event loop checks the call stack continuously. If it is empty, it moves functions from the callback queue to the stack for execution.

Exapmle:

console.log("Hi");

setTimeout(() => {
    console.log("Vicky");
}, 2000);

console.log("End");
Enter fullscreen mode Exit fullscreen mode

Output:

Hi
End
Vicky
Enter fullscreen mode Exit fullscreen mode

So, what the code does is first it logs in Hi then rather than executing the setTimeout function it logs in End and then it runs the setTimeout function.

At first, as usual, the Hi statement got logged in. As we use browsers to run JavaScript, there are the web APIs that handle these things for users. So, what JavaScript does is, it passes the setTimeout function in such web API and then we keep on running our code as usual. So it does not block the rest of the code from executing and after all the code its execution, it gets pushed to the call stack and then finally gets executed. This is what happens in asynchronous JavaScript.

References:

  1. https://www.geeksforgeeks.org/javascript/functions-in-javascript/
  2. https://www.geeksforgeeks.org/operating-systems/difference-between-process-and-thread/
  3. https://www.geeksforgeeks.org/javascript/synchronous-and-asynchronous-in-javascript/
  4. https://www.scholarhat.com/tutorial/javascript/functions-in-javascript
  5. https://dev.to/jaamaalxyz/different-type-of-function-in-javascript-364l
  6. https://www.backblaze.com/blog/whats-the-diff-programs-processes-and-threads/

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

There are a number of things that are not correct in this post. Can I ask where you learned about functions? Where you taught this as part of a course, or have you just sourced information from the various sites you've posted links to above?

Presumably this is also an assignment of some kind?