DEV Community

mohandass
mohandass

Posted on

Discuss about the topics of 1.what is callback function in js 2.Javascript is single threaded or multithreaded ? 3. Array iteration methods in js

  • A callback function in javascript is a function passed as an argument into another function.

  • Which is then executed or (callback) inside that outer function to complete the specific task.

  • Later is typically when a specific event occurs or an asynchronous operation completes.

BASIC CALLBACK:

OUTPUT:
Hello, thomas
Goodbye

Types of Callback

There are two primary ways callback are used:

  • Asynchronous callback

  • Synchronous callback

  1. ASYNCHRONOUS
  • Asynchronous callback is executed immediately during the execution of the main function,blocking further code until finish.

Example:Array.Prototype.forEach(),map(),and filter()-(TBD)

  1. SYNCHRONOUS
  • Synchronous callback is executed at a later time after an operation like fetching data or a time.Completes allowing the rest of the program to continue running in meantime.

Examples: setTimeout(), addEventListener(), and network requests (API calls)-(TBD)

Javascript is single threaded or Multithreaded

  • Javacsript is a single-threaded meaning it executes one task at a time on a single main thread.While the language itself dose not support multi threads for execution it achieves concurrency doing many things at once through an event-driven,non-blocking architecture.

Array Iteration Methods in javascript

A javascript in array iteration methods are built in tools that allow you to loop through array elements and perform operations on them.These methods typically take a callback function as a argument which is executed for each items in the array.

Array forEach
Array map()
Array flatMap()
Array filter()
Array reduce()
Array reduceRight()
Array every()
Array some()
Array from()
Array keys()
Array entries()
Array with()
Array Spread (...)
Array Rest (...) - (TBD)

1. forEach

  • The forEach() method calls a function (a callback function) once for each array element.It's used for side effects, and returns undefined.

Example:

Note that the function takes 3 arguments

  • The item value
  • The item index
  • The array itself

Above the example used the value and index parameters only.

OUTPUT:
50 0
30 1
25 2
10 3
60 4

Top comments (0)