Sign In
Sign In

Arrow Functions in JavaScript

Arrow Functions in JavaScript
Hostman Team
Technical writer
JavaScript
24.11.2023
Reading time: 7 min

With the release of the ES6 standard in 2015, programmers have gotten several new features and functions in JavaScript. The new standard added arrow functions, ways to declare let and const variables, promises, and many other fundamental changes to the language. Today, we will focus on arrow functions.

Arrow functions in JavaScript are a new method of declaring functional expressions that is much more compact and convenient than its predecessor. If you are familiar with lambda functions in Python, you will definitely find similarities between them.

In this article, we'll look at arrow functions and their syntax, give usage examples, and learn the ins and outs of using them in code.

-

Functions

Before we study arrow functions, we should revise the traditional way of declaring functions and function expressions. This chapter will help users to remember what functions and function expressions are and to apprehend how their declaration differs from the arrow functions.

A function is a set of commands written to accomplish a specific task when called. It can be called from any part of the code as many times as you like.

The syntax of a standard function declaration is as follows:

function function_name(set_of_parameters) {
 set_of_commands;

A function declaration is always read first, meaning it can be called before it is declared. This process is called hoisting.

An example of an ordinary function:

console.log(multiplication(2,5));

function multiplication (x, y) {
 return x * y;
}

84ddebe8 2aa5 4294 89d9 B83526459d29

A function definition expression is another method of declaring a function by assigning it to a variable or constant. It can then be passed as an argument to another function or used as a return value.

The syntax for declaring a function expression is as follows:

var variable_name = function function_name (parameters) {
 commands;
}

The function_name parameter is optional. In its absence, the function will be considered anonymous.

Unlike regular functions, a functional expression can only be called after it has been declared in the code.

An example of a functional expression:

const multiplication = function (x, y) {
 return x * y;
}

console.log(multiplication(2,5));

Image5

The basics of arrow functions

Arrow functions (arrow function expressions) are the same as function expressions but anonymous and have some syntax peculiarities. Let's take a closer look at those peculiarities.

  • Concise and clear syntax

The syntax of arrow functions in JavaScript is intuitive and concise. Its basic version is as follows:

(set_of_parameters) => {
 set_of_commands;
}

As we can see, the main difference between arrow functions and normal functions is the absence of the function keyword and the addition of => characters after the argument list in brackets.

For example:

const multiplication = (x, y) => x * y;
console.log(multiplication(2,5));

Here, we did not use curly braces because the function's body contains only one operation. Also, we did not specify an explicit return of the result, as it will happen automatically.

When we execute this code, the result is as follows.

3b12e0af Dfaa 4ab1 9e3b E3676ccf9771

  • The this keyword

Arrow functions operate only in the scope in which they are declared, and do not have their own functional execution context. This implies that entities such as this or argument are inherited exclusively from parent functions.

For a more detailed understanding, here is an example where we will use both a regular function and an arrow function:

function Animal() {
    this.group = 'Mammals',
    this.name = 'Elephant',
    this.Animal1 = function () {
        console.log('Operation of a normal function:')
        console.log(this.group);

        function exampleFunction1() {
            console.log(this.name);
        }
        exampleFunction1();
    }
    this.Animal2 = function () {
        console.log('Operation of an arrow function:')
        console.log(this.group);

        let exampleFunction2 = () => console.log(this.name);
        exampleFunction2();
    }
}

let x = new Animal();
x.Animal1();
let y = new Animal();
y.Animal2();

In this example, this.group is available both inside this.Animal1 and inside this.Animal2, since these are two methods of the same object. However, inside these methods, in the first case this.name returns an undefined value, and the output is empty since this function has its own context (in this case, window). In the second case, however, it references the parent scope and returns this.name = 'Elephant'

When we execute the code, we receive the following output:

Operation of a normal function:
Mammals

Operation of an arrow function:
Mammals
Elephant
  • Constructors

Arrow functions cannot be used as constructors, nor can they have their own properties and methods because they lack the prototype property the normal functions have. When calling them with the new operator, the system will generate an error.

93257324 Ae14 4f5d 8c01 Bb0e7ff4e63e

Also, since the arrow is followed by curly braces denoting a code block with commands, the user will not be able to create an object inside the function or return an object literal from it in the usual way. For example, the following code fragment will generate an error:

(firstName, lastName) => {firstName: firstName, lastName: lastName};

The system considers it the function's body; that's why an error occurs in this code fragment. To fix this, we need to enclose the object literal in parentheses:

(firstName, lastName) => ({firstName: firstName, lastName: lastName});

Examples of use

Arrow functions are acceptable anywhere in a program but are especially useful in callback functions that take other functions as parameters. In the following example, we use it as a callback for the map method:

const example_numbers = [1, 2, 3, 4, 5];
const doubling = example_numbers.map(number => number * 2);
console.log(doubling);

2816e5f6 82d2 409d 9404 51eed418103b

Like with curly braces, we can omit parentheses if only one parameter is specified, as in the example above.

Another example of arrow functions is using them in the reduce method. In the following example, we use an arrow function to add up all the elements of an array:

const example_numbers = [1, 2, 3, 4, 5];
const sum = example_numbers.reduce((total, number) => total + number, 0);
console.log(sum);

As a result, we get the following:

E4549098 9d51 4a29 B6ee 4b4a056347c2

When to avoid using arrow functions

There are cases where regular functions are preferable to arrow functions. 

Mostly, they are related to the this keyword behavior and its peculiarities, because of which you shouldn't use arrow functions in object methods.

Let’s look at this example:

let animal = {
    group: 'Amphibians',
    name: 'Lake frog',
    infoAnimal: () => {        
console.log('Animal group -',this.group);
console.log('Animal name -',this.name);
    },
}

animal.infoAnimal(); 

Here, we have the infoAnimal method, which outputs information about the object when we call it with the animal.infoAnimal(). In this case, its lexical environment is window. Hence, it has nothing to do with the group and name object properties. 

This is the result we get:

Animal group - undefined 
Animal name - undefined

Now let's rewrite the code using a normal function and look at the result:

let animal = {
    group: 'Amphibians',
    name: 'Lake frog',
    infoAnimal: function () {        
            console.log('Animal group -',this.group);
    console.log('Animal name -',this.name);
    },
}

animal.infoAnimal();

We can see that this method works successfully:

Animal group - Amphibians 
Animal name - Lake frog

In addition to object methods, you shouldn't use the arrow functions for functions with a dynamic context, because they bind the context statically. For example, this applies to working with event handlers or event listeners.

What to remember

  • Arrow functions (arrow function expressions) are the same as function expressions, but anonymous and with some syntax peculiarities.

  • Their basic syntax is as follows:

(set_parameters) => {
 set_commands;
}
  • When using the arrow functions, you can remove parentheses around a parameter if it is a single parameter. If the function implements only one operation, you can also use implicit return, which means deleting curly brackets and the return keyword.

  • Arrow functions work only in the scope in which they were declared, and do not have their own functional execution context. So, entities such as this or argument are inherited exclusively from parent functions.

  • When working with object methods, dynamic context or constructors, you should use regular functions, not arrow functions.

JavaScript
24.11.2023
Reading time: 7 min

Similar

JavaScript

JavaScript Array Methods

Arrays in JavaScript are a data structure that stores various elements, often of the same type. Their main feature is storing multiple values in a single variable. Thanks to their integrated methods and properties, you can add, delete, process, or search the data based on your needs.  All array values are elements. In turn, they have their own index. Variables can be either of the same or different data types, allowing you to organize more complex data structures. Creating an array There are two ways to initialize an array: 1. Using a literal syntax. In this case, elements are listed inside square brackets and separated by commas.  const ExampleArr = [element0, element1, …, elementN]; 2. using the Array() constructor. Syntax: const ExampleArr = new Array(element0, element1[, …[, elementN]]);const ExampleArr = new Array(arrayLenght); In both methods, we pass elementN as parameters. These are the variables that create the set of ExampleArr values. ArrayLength is the number of elements. Their default value is not defined.  After creating the array, let’s fill it in. Let's create a set of values that stores employees' names. Using the first method: var EmployeeArr = [‘Alex’, ‘Bob’, ‘Oliver’]; Using the second one: var EmployeeArr = new Array(‘Alex’, ‘Bob’, ‘Oliver’); Access to array elements  To access an array element, we use square brackets with an integer value of its index inside them. Let's get the value of two elements of the previously created value set EmployeeArr: var EmployeeArr = new Array(‘Alex’, ‘Bob’, ‘Oliver’);console.log (EmployeeArr[1]);  The index numbering starts from 0, which we should remember when referring to the N-th element. Its index will be N-1. In our case, it will equal 1. To change the value of an element, you need to assign a new value to the variable, as shown below: var EmployeeArr = new Array(‘Alex’, ‘Bob’, ‘Oliver’);EmployeeArr[1] = ‘Jack’; Now EmployeeArr contains 'Alex', 'Jack', and 'Oliver.' Now let's look at length, an important property that returns the length of an array in JavaScript. var EmployeeArr = new Array(‘Alex’, ‘Bob’, ‘Oliver’);console.log (EmployeeArr.length);  The length of EmployeArr in our case will be 3. - Array methods Array methods in JavaScript allow developers to work with data more efficiently and conveniently. Their use will help with conversion, sorting, searching, adding or removing elements.  In this article, we'll look at most of the existing JavaScript array methods, grouped by their work logic. Adding and removing elements There are four main methods to add or remove elements from an array: push(), pop(), shift(), and unshift(). push() adds one or more elements to the end of the value set. pop() deletes the last element. shift() deletes the first element. unshift() adds one or more elements to the beginning. Let's look at examples. We'll indicate the output of each method in the comment. var arr = new Array(‘Alex’, ‘Bob’, ‘Oliver’);arr.push (‘Jack’); // ‘Alex’, ‘Bob’, ‘Oliver’, ‘Jack’arr.unshift (‘Jacob’, ‘George’); //; ‘Jacob’, ‘George’, ‘Alex’, ‘Bob’, ‘Oliver’, ‘Jack’arr.pop (); // ‘Jacob’, ‘George’, ‘Alex’, ‘Bob’, ‘Oliver’arr.shift (); // ‘George’, ‘Alex’, ‘Bob’, ‘Oliver’ The pop() and shift() methods return the value of the deleted element, while push() and unshift() return the length of the modified array. In addition to the above methods, we should mention the universal splice() method. It allows you to insert, delete, or replace elements. Syntax of the splice() method: array.splice(startIndex, deleteCount, element1, element2, ...); Parameters:  startIndex is the index where the splice should begin. If this parameter exceeds the array length, the startIndex value will equal the length or take the difference between array.length and this number if a negative number is entered.  deleteCount is the number of elements to delete starting from startIndex. It can be equal to 0. In this case, nothing happens.  element1, element2, .... are the elements we add to the array (optional parameter). The splice() method returns the set of deleted values. In the example, let's look at several ways to apply splice(). The comments will specify the set of values after the method is executed. Below, we will remove two elements, starting with 3: var Dog = new Array(‘Beagle’, ‘Boxer’, ‘Bulldog’, ‘Corgi’, ‘Dachshund’, ‘Dalmatian’);Dog.splice ( 2, 2 ); // ‘Beagle’, ‘Boxer’, ‘Dachshund’, ‘Dalmatian’ Now let's remove one element starting at 4 and add 'Doberman': var Dog = new Array(‘Beagle’, ‘Boxer’, ‘Bulldog’, ‘Corgi’, ‘Dachshund’, ‘Dalmatian’);Dog.splice (3, 1, ‘Doberman’); // ‘Beagle’, ‘Boxer’, ‘Bulldog’, ‘Doberman’, ‘Dachshund’, ‘Dalmatian’ Iterating through an array The forEach() method is responsible for iterating array elements. arr.forEach(function callback(currentValue, index, array), thisValue); Parameters: callback is the main parameter, namely the callback function that will be executed once for each element. Its arguments are currentValue, index, array. currentValue is the element to be processed in the set. index is this element's index. array is the array of the selected element. thisValue is an optional parameter. It takes the value used as this when calling the function. The returned value is always undefined. Here are two examples: one using thisValue and one without it. The example without thisValue parameter: var Dog = new Array(‘Beagle’, ‘Boxer’, ‘Bulldog’, ‘Corgi’, ‘Dachshund’, ‘Dalmatian’);var NewDog = [ ];Dog.forEach (function (element) {NewDog.push (element);}) The result will be a new set of NewDog values that completely replicates Dog. Example with the thisValue parameter: var numbers = [1, 2, 3, 4, 5];var doubleNumbers = [ ];var myObject = {    double: function(element) {        return element * 2;    }};numbers.forEach (    function (element) {        doubleNumbers.push(this.double(element));     }, myObject); The result is a doubleNumbers set, which consists of numbers multiplied by two. Searching for an element in an array Such methods as indexOf(), lastIndexOf(), includes(), find(), findIndex(), and filter() help to search for items.  The indexOf() and lastIndexOf() methods search for the required value among all the elements and return its index at the first match. The former searches from the beginning of the array, while the latter searches from the end. Both methods will return -1 if the searched value is not found. Syntax of indexOf() and lastIndexOf() methods: array.indexOf( searchElement, fromIndex )array.lastIndexOf( searchElement, fromIndex ) The searchElement parameter is the same in both cases. It is the element we need to find. This is not the case with the fromIndex parameter. This is the starting index of the element to search for. When indexOf() is used, the fromIndex parameter defaults to zero. In the lastIndexOf() method, it is equal to array.length.  Let's try using these methods in the example below.  var Employee = new Array(‘Jacob’, ‘George’, ‘Alex’, ‘George’, ‘Oliver’, ‘Jack’);Employe.indexOf (‘George’);Employe.lastIndexOf (‘George’); The result of the indexOf() method will be 1 because the first match occurred with an element whose index is 1. In the case of lastIndexOf(), the result will be 3. The next search method is includes(). It determines whether the set of values contains a certain element, returning true or false depending on the result. The syntax of the includes() method: array.includes(searchElement, fromIndex) The parameters are exactly the same as in the previously discussed indexOf() and lastIndexOf() methods. The only difference between them is the return value. The fromIndex parameter is 0 by default. Here's an example of using the includes() method: var Employe = new Array(‘Jacob’, ‘George’, ‘Alex’, ‘Bob’, ‘Oliver’, ‘Jack’);Employe.includes (‘Alex’);Employe.includes (‘Jacob’, 3); The result in the first case will be true. In the second case, false. In practice, JavaScript often uses arrays of objects. In this case, you should search using the find() and findIndex() methods. arr.find(function callback(currentValue, index, array), thisValue); arr.findIndex(function callback(currentValue, index, array), thisValue);  Parameters of find() and findIndex() methods are similar to forEach(), so you can find their descriptions above. Let's look at an example of using the find() and findIndex() methods: var Employee = new Array(‘Jacob’, ‘George’, ‘Alex’, ‘Bob’, ‘Oliver’, ‘Jack’);Employee.find (element => element == ‘Jacob’);Employee.findIndex (element => element == ‘Jacob’); The return value of the find() method is 'Jacob', and of the findIndex() method is 0. The find() and findIndex() methods are suitable for searching one object. If the task is to find several objects, we can use another method: filter().  Syntax of the filter() method: var filteredArray = arr.filter(function(currentValue, index, array), thisValue);  The parameters of this method are also similar to the parameters of the forEach() method. Let's try it. Here we will search for employees who have worked in the company for less than two years: var Employee = [ {name: “Jacob”, experience: 3},{name: “George”, experience: 1},{name: “Alex”, experience: 1},{name: “Bob”, experience: 4}];var result = Employee.filter(element => element.experience <2); The method will result in a new array consisting of two employees with less than two years of experience. Methods for converting arrays The last group of array methods in JavaScript that we will describe in this article are array transformation methods. These include map(), flat(), flatmap(), sort(), and reverse(). Let's look at each of them in more detail below. map() organizes a new set of values with the result of calling the specified callback function for each element. The syntax of the map() method: var newArray = array.map(function(currentValue, index, arr), thisValue);  Once again, we see the same parameters as in the previously discussed methods. The return value of this method will be a new array with the elements of the callback function result. Let's consider the example that we already used earlier with forEach(), where all the set data were doubled. Now, let's use map() instead of forEach(). var numbers = [1, 2, 3, 4, 5];var doubleNumbers = numbers.map(     function double( element ) {        return element * 2;    });console.log(doubleNumbers); The result is doubleNumbers, a new set of values consisting of numbers 2, 4, 6, 8, 10.  When we use the map() method, the number of lines of code is noticeably reduced compared to forEach(). Also, the forEach() method is used only for iteration and returns nothing. map() returns a new array of the same length as the original array. Flat() allows you to interact with a nested set of values. It returns a new array with all sub-array values merged into it recursively  up to the specified level. The syntax of the flat() method: var newArray = arr.flat(depth); Here, depth specifies the level, i.e. how deep a nested array structure should be flattened. If the nesting depth is unknown, you can set the value of the parameter as Infinity. By default, it is equal to one. Let's consider an example of using the flat() method: var arr = [1, 2, , [4, 5, [6, 7]]];var NewArr = arr.flat(Infinity); The result is NewArr [1, 2, 4, 5, 6, 7]. It is worth noting that one was missing in the set of arr values. The flat() method removed the empty slots. We can combine the previous two methods into one: flatmap().  The syntax of the flatmap() method: var new_array = arr.flatMap(function callback(currentValue, index, arr), thisValue) Here is an example of using flatmap(): var arr = [[1], [2], [3], [4], [5]];var NewArr = arr.flatMap(element => element * 2); The result will be NewArr [2, 4, 6, 8, 10]. The sort() method allows sorting the data set. The default sorting order corresponds to the order of Unicode code characters. Syntax of the sort() method: array.sort(function(firstValue, secondValue));  You can specify a function that determines the sort order as a parameter. Example: var EmployeeArr = new Array(‘Jacob’, ‘George’, ‘Alex’, ‘Bob’, ‘Oliver’, ‘Jack’);EmployeeArr.sort (); The result of sorting will be EmployeArr ['Alex', 'Bob', 'George', 'Jack', 'Jacob', 'Oliver']. The reverse() method is also worth mentioning.  Syntax of the reverse() method: array.reverse(); In the example, let's change the order of employees’ names in the previously sorted array. var EmployeeArr = new Array(‘Jacob’, ‘George’, ‘Alex’, ‘Bob’, ‘Oliver’, ‘Jack’);EmployeeArr.sort ();var reversed = EmployeeArr.reverse(); The result of the reverse() method is EmployeArr ['Oliver', 'Jacob', 'Jack', 'George', 'Bob', 'Alex']. Conclusion This article has covered the basic, but not all, array methods in JavaScript. It is not easy to memorize them all at once. But it will become easier with experience in solving problems and using the methods in code. The main thing is to memorize how they work and what they are used for, and if necessary, you can always refer to this article to remember the syntax or see examples. Frequently Asked Questions What are the most commonly used JavaScript array methods? In day-to-day dev work, .map(), .filter(), .reduce(), .forEach(), and .slice() are your best friends — powerful and versatile. What is the difference between map and forEach in JavaScript? .map() transforms and returns a new array. .forEach() just runs code for each element without returning anything. How do I remove elements from an array in JavaScript? Use .filter() or .splice() depending on whether you need immutability or not.
16 June 2025 Ā· 12 min to read
JavaScript

How to Use .map() in JavaScript

JavaScript supports several methods for iterating over arrays. Developers commonly use the traditional for loop and the less common .forEach() method. However, the most popular method is .map(). This method creates a new array by calling a function on every element of the original array. It avoids mutations and generates truly "clean" arrays.  This is different from mutation-based methods, which inevitably alter the original array in some way. In this article, we'll explore four ways to use .map() in JavaScript (though many more exist). Method 1: Calling Functions on Individual Array Elements When using .map() in JavaScript, the callback function is treated as an argument. The value of the array element at the time of execution becomes a required parameter of this function. You can use it to modify or create functions. Example: const sweetArray = [6, 7, 11, 13, 20]; const sweeterArray = sweetArray.map(sweetItem => {     return sweetItem * 2; }); console.log(sweeterArray); Output: [12, 14, 22, 26, 40] You can clean up and simplify the code: const makeSweeter = sweetItem => sweetItem * 2; const sweetArray = [6, 7, 11, 13, 20]; const sweeterArray = sweetArray.map(makeSweeter); console.log(sweeterArray); Output: [12, 14, 22, 26, 40] Using sweetArray.map(makeSweeter) makes the code more readable compared to the first version. Method 2: Converting Strings to Arrays You can use the .map() method from the Array prototype to convert strings. Instead of working directly with arrays, we use .call() to apply .map() to a string. Keep in mind that in JavaScript, strings can be treated like arrays of characters, allowing access to some array methods. Example: const name = "Hostman"; const map = Array.prototype.map; const newName = map.call(name, eachLetter => {     return `${eachLetter}e`; }); console.log(newName); Output: ["He", "oe", "se", "te", "me", "ae", "ne"] In this example, .map() is used to transform each character in the string by appending an "e". This works similarly to .split() and other methods that operate on string characters before transforming them back into an array. Method 3: Rendering Lists in JavaScript Libraries This use case is common in JavaScript frameworks like React. Here, you’ll need JSX syntax since .map() is used within it. For example: import React from "react"; import ReactDOM from "react-dom"; const names = ["cloud", "dbaas", "vps", "storage", "kubernetes"]; const NamesList = () => ( <div> <ul>{names.map(name => <li key={name}>{name}</li>)}</ul> </div> ); const rootElement = document.getElementById("root"); ReactDOM.render(<NamesList />, rootElement); In this example, the React component renders a <div> containing a list. The JavaScript .map() method is used to iterate over the array of names and generate individual list items. Rendering is handled by ReactDOM.render on a DOM element with the ID root. Method 4: Transforming Array Object Formats Another use case for .map() in JavaScript is transforming each object in an array and returning a new array of modified objects. This works much like traditional data processing. Example: const myUsers = [ { name: 'cloud', likes: 'scalability' }, { name: 'devops', likes: 'automation' }, { name: 'kube', likes: 'orchestration' } ]; const usersByLikes = myUsers.map(item => { const container = {}; container[item.name] = item.likes; container.popularity = item.name.length * 12; return container; }); console.log(usersByLikes); Output: [   { cloud: 'scalability', popularity: 60 },   { devops: 'automation', popularity: 72 },   { kube: 'orchestration', popularity: 48 } ] In this example, each object in the array is modified using bracket notation and object property assignments. This approach is useful for transforming and condensing incoming data before using it in client-side applications. Conclusion We reviewed four main ways to use the .map() method in JavaScript. You can expand its capabilities by combining it with other methods. For more detailed information, refer to the official documentation.
11 June 2025 Ā· 4 min to read
Microservices

Database Connection in Python, Go, and JavaScript

Databases are an essential part of almost any project today. Database interactions are especially familiar to system and database administrators, DevOps/SRE professionals, and software developers. While administrators typically deploy one or multiple database instances and configure the necessary connection parameters for applications, developers need to connect directly to the database within their code. This article explores how to connect to databases using different programming languages. Prerequisites We will provide examples for connecting to MySQL, PostgreSQL, Redis, MongoDB, and ClickHouse databases using Python, Go, and JavaScript. To follow this guide, you will need: A database deployed on a server or in the cloud. Installed environments for Python, Go, and JavaScript, depending on your application programming language. Additionally for Python: pip installed. Additionally for JavaScript: Node.js and npm installed. Database Connection in Python MySQL and Python For connecting to MySQL databases, we can use a Python driver called MySQL Connector. Install the driver using pip: pip install mysql-connector-python Initialize a new connection: Import the mysql.connector library and the Error class to handle specific connection errors. Create a function named create_connection, passing the database address (host), user name (user), and user password (password). To establish the connection, define a class called create_connection that receives the variable names containing the database connection details. import mysql.connector from mysql.connector import Error def create_connection(host_name, user_name, user_password): connection = None try: connection = mysql.connector.connect( host="91.206.179.29", user="gen_user", password="m-EE6Wm}z@wCKe" ) print("Successfully connected to MySQL Server!") except Error as e: print(f"The error '{e}' occurred") return connection def execute_query(connection, query): cursor = connection.cursor() try: cursor.execute(query) connection.commit() print("Query executed successfully") except Error as e: print(f"The error '{e}' occurred") connection = create_connection("91.206.179.29", "gen_user", "m-EE6Wm}z@wCKe") Run the script. If everything works correctly, you will see the "Successfully connected to MySQL Server!" message. If any errors occur, the console will display error code and description. Create a new table: Connect to the database using the connection.database class, specifying the name of the database. Note that the database should already exist. To create a table, initialize a variable create_table_query containing the SQL CREATE TABLE query. For data insertion, initialize another variable insert_data_query with the SQL INSERT INTO query. To execute each query, use the execute_query class, which takes the database connection string and the variable containing the SQL query. connection.database = 'test_db' create_table_query = """ CREATE TABLE IF NOT EXISTS users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, age INT NOT NULL ) """ execute_query(connection, create_table_query) insert_data_query = """ INSERT INTO users (name, age) VALUES ('Alice', 30), ('Bob', 25) """ execute_query(connection, insert_data_query) if connection.is_connected(): connection.close() print("Connection closed") Run the script. PostgreSQL and Python Python offers several plugins for connecting to PostgreSQL, but the most popular one is psycopg2, which we will use here. Psycopg2 is one of the most frequently used Python plugins for PostgreSQL connections. One of its key advantages is its support for multithreading which allows you to maintain the database connection across multiple threads. Install psycopg2 using pip (if not already installed): pip install psycopg2-binary Connect to PostgreSQL. Import the Python psycopg2 package and create a function create_new_conn, using the try block. Establish the connection with the psycopg2.connect function, which requires the database name, user name, password, and database address as input. To initialize the connection, use the create_new_conn() function. Here’s the full code example for connecting to a database: import psycopg2 from psycopg2 import OperationalError def create_new_conn(): conn_to_postgres = None while not conn_to_postgres: try: conn_to_postgres = psycopg2.connect( default_db="default_db", default_user="gen_user", password_for_default_user="PasswordForDefautUser9893#", db_address="91.206.179.128" ) print("The connection to PostgreSQL has been successfully established!") except OperationalError as e: print(e) return conn_to_postgres conn_to_postgres = create_new_conn() Run the script: python3 connect_to_postgres.py If successful, you will see the "The connection to PostgreSQL has been successfully established!" message. . Next, create a table named books, which will have three columns. Use the cursor class for SQL expressions, such as creating database objects. If the query involves adding or modifying data, you must call the conn_to_postgres.commit() function afterward to apply the changes. import psycopg2 from psycopg2 import OperationalError def create_new_conn(): conn_to_postgres = None while not conn_to_postgres: try: conn_to_postgres = psycopg2.connect( default_db="default_db", default_user="gen_user", password_for_default_user="PasswordForDefautUser9893#", db_address="91.206.179.128" ) except OperationalError as e: print(e) return conn_to_postgres conn_to_postgres = create_new_conn() cursor = conn_to_postgres.cursor() cursor.execute(""" CREATE TABLE books ( book_id INT PRIMARY KEY NOT NULL, book_name VARCHAR(255) NOT NULL, book_author VARCHAR(255) NOT NULL ) """) conn_to_postgres.commit() print("Table Created successfully") Run the script: python3 create_table.py Now, let’s run INSERT INTO to add a new line: cursor.execute(""" INSERT INTO books (book_id,book_name,book_author) VALUES (1, 'Long Walk to Freedom', 'Nelson_Mandela') """) The full code is below: import psycopg2 from psycopg2 import OperationalError def create_new_conn(): conn_to_postgres = None while not conn_to_postgres: try: conn_to_postgres = psycopg2.connect( default_db="default_db", default_user="gen_user", password_for_default_user="PasswordForDefautUser9893#", db_address="91.206.179.128" ) except OperationalError as e: print(e) return conn_to_postgres conn_to_postgres = create_new_conn() cursor = conn_to_postgres.cursor() cursor.execute(""" INSERT INTO books (book_id,book_name,book_author) VALUES (1, 'Long Walk to Freedom', 'Nelson_Mandela') """) conn_to_postgres.commit() conn_to_postgres.close() print("Data inserted successfully") Run the script: python3 insert-data.py Redis and Python Redis belongs to the class of NoSQL databases, where data is stored in memory rather than on hard drives. It uses a key-value format for data storage. Redis has a wide range of applications, from data storage and caching to serving as a message broker. We will use the redis-py (or simply redis) library for connecting to Redis. Install the Redis library using pip: pip install redis Connecting to a Redis instance: Use a try block structure for connection, specifying the function redis.StrictRedis where you provide the Redis address, port, and user password. import redis try: connect_to_redis_server = redis.StrictRedis( redis_db_host=91.206.179.128, redis_db_port=6379, redis_user_password='PasswordForRedis6379') print connect_to_redis_server connect_to_redis_server.ping() print 'Successfully connected to Redis Server!' except Exception as ex: print 'Error:', ex exit('Failed to connect to Redis server.') Run the script: python3 connect_to_redis.py If successful, you will see a message like "Successfully connected to Redis Server!". Unlike relational databases, Redis stores data in a key-value format. The key uniquely identifies the corresponding value. Use the set method to create a new record. The example below creates a record with the key City and the value Berlin: print('Create new record:', connect_to_redis_server.set("City", "Berlin")) Use the get method to retrieve the value associated with a key: print('Print record using record key:', connect_to_redis_server.get("City")) Use the delete method to remove a record by its key: print('Delete record with key:', connect_to_redis_server.delete("City")) The complete code fragment is below. import redis try: connect_to_redis_server = redis.StrictRedis( redis_db_host=91.206.179.128, redis_db_port=6379, redis_user_password='PasswordForRedis6379') print ('New record created:', connect_to_redis_server.set("City", "Berlin")) print ('Print created record using record key', connect_to_redis_server.get("City")) print ('Delete created record with key :', connect_to_redis_server.delete("City")) except Exception as ex: print ('Error:', ex) MongoDB and Python MongoDB is another widely used NoSQL database that belongs to the document-oriented category. Data is organized as JSON-like documents. To connect to a MongoDB database with Python, the recommended library is PyMongo, which provides a synchronous API. Install the PyMongo plugin: pip3 install pymongo Connect to MongoDB server using the following Python code. Import the pymongo module and use the MongoClient class to specify the database server address. To establish a connection to the MongoDB server, use a try block for error handling: import pymongo connect_to_mongo = pymongo.MongoClient("mongodb://91.206.179.29:27017/") first_db = connect_to_mongo["mongo-db1"] try: first_db.command("serverStatus") except Exception as e: print(e) else: print("Successfully connected to MongoDB Server!") connect_to_mongo.close() Run: python3 connect_mongodb.py If the connection is successfully established, the script will return the message: "Successfully connected to MongoDB Server!" Add data to MongoDB. To add data, you need to create a dictionary. Let's create a dictionary named record1, containing three keys: record1 = { "name": "Alex", "age": 25, "location": "London" } To insert the dictionary data, use the insert_one method in MongoDB. insertrecord = collection1.insert_one(record1) import pymongo connect_to_mongo = pymongo.MongoClient("mongodb://91.206.179.29:27017/") db1 = connect_to_mongo["newdb"] collection1 = db1["userdata"] record1 = { "name": "Alex", "age": 25, "location": "London" } insertrecord = collection1.insert_one(record1) print(insertrecord) Run the script: python3 connect_mongodb.py ClickHouse and Python ClickHouse is a columnar NoSQL database where data is stored in columns rather than rows. It is widely used for handling analytical queries. Install the ClickHouse driver for Python. There is a dedicated plugin for ClickHouse called clickhouse-driver. Install the driver using the pip package manager: pip install clickhouse-driver Connect to ClickHouse. To initialize a connection with ClickHouse, you need to import the Client class from the clickhouse_driver library. To execute SQL queries, use the client.execute function. You also need to specify the engine. For more details on supported engines in ClickHouse, you can refer to the official documentation. We'll use the default engine, MergeTree. Next, create a new table called users and insert two columns with data. To list the data to be added to the table, use the tuple data type. After executing the necessary queries, make sure to close the connection to the database using the client.disconnect() method. The final code will look like this: from clickhouse_driver import Client client = Client(host=91.206.179.128', user='root', password='P@$$w0rd123', port=9000) client.execute(''' CREATE TABLE IF NOT EXISTS Users ( id UInt32, name String, ) ENGINE = MergeTree() ORDER BY id ''') data = [ (1, 'Alice'), (2, 'Mary') ] client.execute('INSERT INTO Users (id, name) VALUES', data) result = client.execute('SELECT * FROM Users') for row in result: print(row) client.disconnect() Database Connection in Go Go is one of the youngest programming languages, developed in 2009 by Google.  It is widely used in developing microservice architectures and network utilities. For example, services like Docker and Kubernetes are written in Go. Go supports integrating all popular databases, including PostgreSQL, Redis, MongoDB, MySQL, ClickHouse, etc. MySQL and Go For working with the MySQL databases in Go, use the go-sql-driver/mysql driver. Create a new directory for storing project files and navigate into it: mkdir mysql-connect && cd mysql-connect Create a go.mod file to store the dependencies: go mod init golang-connect-mysql Download the MySQL driver using the go get command: go get -u github.com/go-sql-driver/mysql Create a new file named main.go. Specify the database connection details in the dsn variable: package main import ( "database/sql" "fmt" "log" _ "github.com/go-sql-driver/mysql" ) func main() { dsn := "root:password@tcp(localhost:3306)/testdb" db, err := sql.Open("mysql", dsn) if err != nil { log.Fatal(err) } defer db.Close() if err := db.Ping(); err != nil { log.Fatal(err) } fmt.Println("Successfully connected to the database!") query := "INSERT INTO users (name, age) VALUES (?, ?)" result, err := db.Exec(query, "Alex", 25) if err != nil { log.Fatal(err) } lastInsertID, err := result.LastInsertId() if err != nil { log.Fatal(err) } fmt.Printf("Inserted data with ID: %d\n", lastInsertID) } PostgreSQL and Go To connect to PostgreSQL, use the pq driver. Before installing the driver, let's prepare our environment. Create a new directory for storing the project files and navigate into it: mkdir postgres-connect && cd postgres-connect Since we will be working with dependencies, we need to create a go.mod file to store them: go mod init golang-connect-postgres Download the pq driver using the go get command: go get github.com/lib/pq Create a new file named main.go. In addition to importing the pq library, it is necessary to add the database/sql library as Go does not come with official database drivers by default. The database/sql library consists of general, independent interfaces for working with databases. It is also important to note the underscore (empty identifier) when importing the pq module: _ "github.com/lib/pq" The empty identifier is used to avoid the "unused import" error, as in this case, we only need the driver to be registered in database/sql. The fmt package is required to output data to the standard output stream, for example, to the console. To open a connection to the database, the sql.Open function is used, which takes the connection string (connStr) and the driver name (postgres). The connection string specifies the username, database name, password, and host address: package main import ( "database/sql" "fmt" "log" _ "github.com/lib/pq" ) func main() { connStr := "user=golang dbname=db_for_golang password=Golanguserfordb0206$ host=47.45.249.146 sslmode=disable" db, err := sql.Open("postgres", connStr) if err != nil { log.Fatal(err) } defer db.Close() err = db.Ping() if err != nil { log.Fatal(err) } fmt.Println("Successfully connected to PostgreSQL!") } Compile and run: go run main.go If everything works correctly, the terminal will display the message Successfully connected to PostgreSQL! Now, let's look at an example of how to insert data into a table.  First, we need to create a table in the database. When using Hostman cloud databases, you can copy the PostgreSQL connection string displayed in the "Connections" section of the Hostman web interface. Make sure that the postgresql-client utility is installed on your device beforehand. Enter the psql shell and connect to the previously created database: \c db_for_golang Create a table named Cities with three fields — city_id, city_name, and city_population: CREATE TABLE Cities ( city_id INT PRIMARY KEY, city_name VARCHAR(45) NOT NULL, city_population INT NOT NULL); Grant full privileges to the created table for the user: GRANT ALL PRIVILEGES ON TABLE cities TO golang; The function db.Prepare is used to prepare data. It specifies the query for insertion in advance. To insert data, use the function stmt.Exec. In Go, it's common to use plain SQL without using the ORM (Object-Relational Mapping) approach. stmt, err := db.Prepare("INSERT INTO Cities(city_id, city_name, city_population) VALUES($1, $2, $3)") if err != nil { log.Fatal(err) } defer stmt.Close() _, err = stmt.Exec(1, "Toronto", 279435) if err != nil { log.Fatal(err) } fmt.Println("Data inserted successfully!") } If all works correctly, you will see: Data inserted successfully! Redis and Go To connect to Redis, you need to use the go-redis driver. Š”reate a new directory: mkdir connect-to-redis && cd connect-to-redis Prepare the dependency file: go mod init golang-connect-redis And optimize them: go mod tidy Download the go-redis module: go get github.com/go-redis/redis/v8 To connect to Redis, use the redis.Options function to specify the address and port of the Redis server. Since Redis does not use authentication by default, you can leave the Password field empty and use the default database (database 0): package main import ( "context" "fmt" "log" "github.com/go-redis/redis/v8" ) func main() { rdb := redis.NewClient(&redis.Options{ Addr: "91.206.179.128:6379", Password: "", DB: 0, }) ctx := context.Background() _, err := rdb.Ping(ctx).Result() if err != nil { log.Fatalf("Couldn't connect to Redis: %v", err) } fmt.Println("Successfully connected to Redis!") } You should see the message «Successfully connected to Redis!» MongoDB and Go To work with MongoDB, we'll use the mongo driver. Create a new directory to store the project structure: mkdir connect-to-mongodb && cd connect-to-mongodb Initialize the dependency file: go mod init golang-connect-mongodb Download the mongo library: go get go.mongodb.org/mongo-driver/mongo Connect to MongoDB using the options.Client().ApplyURI method. It takes a connection string such as mongodb://91.206.179.29:27017, where 91.206.179.29 is the MongoDB server address and 27017 is the port for connecting to MongoDB. The options.Client().ApplyURI string is used only for specifying connection data. To check the connection status, you can use another function, client.Ping, which shows the success or failure of the connection: package main import ( "context" "fmt" "log" "time" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) func main() { clientOptions := options.Client().ApplyURI("mongodb://91.206.179.29:27017") client, err := mongo.Connect(context.TODO(), clientOptions) if err != nil { log.Fatalf("Couldn't connect to MongoDB server: %v", err) } fmt.Println("successfully connected to MongoDB!") ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() err = client.Ping(ctx, nil) if err != nil { log.Fatalf("Could not ping MongoDB server: %v", err) } fmt.Println("Ping MongoDB server successfully!") } You should see the message: successfully connected to MongoDB!Ping MongoDB server successfully MongoDB uses collections to store data. You can create collections using the .Collection function.  Below, we will create a database called first-database and a collection called first-collection. The collection will have a new document, containing three keys: user-name, user-age, and user-email. collection := client.Database("first-database").Collection("first-collection") document := map[string]interface{}{ "user-name": "Alice", "user-age": 25, "user-email": "alice@corporate.com", } insertResult, err := collection.InsertOne(ctx, document) if err != nil { log.Fatalf("Couldn't insert new document: %v", err) } fmt.Printf("Inserted new document with ID: %v\n", insertResult.InsertedID) if err := client.Disconnect(ctx); err != nil { log.Fatalf("Could not disconnect from MongoDB: %v", err) } fmt.Println("Disconnected from MongoDB!") } If successful, you will see the Inserted new document message with the document ID.  ClickHouse and Go To work with ClickHouse, use the clickhouse-go driver. Create a new directory to store the project files and navigate to it: clickhouse-connect && cd clickhouse-connect Create a go.mod file to store the dependencies: go mod init golang-connect-clickhouse Download the Clickhouse driver using the command: go get github.com/ClickHouse/clickhouse-go/v2 Create a new file named main.go, where you will specify the connection data to ClickHouse. package main import ( "database/sql" "log" "github.com/ClickHouse/clickhouse-go/v2" ) func main() { dsn := "tcp://localhost:9000?username=user1&password=PasswordForuser175465&database=new_db" db, err := sql.Open("clickhouse", dsn) if err != nil { log.Fatal(err) } defer db.Close() if err := db.Ping(); err != nil { log.Fatal(err) } log.Println("Connected to ClickHouse!") } Database Connection in JavaScript In JavaScript, all connections to external services are made using the Node.js platform. Make sure that you have Node.js and the npm package manager installed on your device. MySQL and JavaScript To work with MySQL, use the mysql2 driver. Create a directory where we will store the project files: mkdir js-mysql-connect && cd js-mysql-connect Initialize the project: npm init -y Install the mysql2 library: npm install mysql2 Use the following code to connect to MySQL: const mysql = require('mysql2'); const connection_to_mysql = mysql.createConnection({ host: 'localhost', user: 'root', password: 'PasswordForRoot74463', database: db1, }); connection_to_mysql.connect((err) => { if (err) { console.error('Error connecting to MySQL:', err.message); return; } console.log('Successfully connected to MySQL Server!'); connection_to_mysql.end((endErr) => { if (endErr) { console.error('Error closing the connection_to_mysql:', endErr.message); } else { console.log('Connection closed.'); } }); }); PostgreSQL and JavaScript Connecting to PostgreSQL is done using the pg library. Create a directory where we will store the project files: mkdir js-postgres-connect && cd js-postgres-connect Initialize the project: npm init -y Install the pg library: npm install pg To connect to PostgreSQL, first import the pg library. Then, create a constant where you specify variables for the database address, username, password, database name, and port. Use the new pg.Client class to pass the connection data. We will create a table called cities and add two records into it. To do this, we will use the queryDatabase function, which contains the SQL queries. const pg = require('pg'); const config = { postgresql_server_host: '91.206.179.29', postgresql_user: 'gen_user', postgresql_user_password: 'PasswordForGenUser56467$', postgresql_database_name: 'default_db', postgresql_database_port: 5432, }; const client = new pg.Client(config); client.connect(err => { if (err) throw err; else { queryDatabase(); } }); function queryDatabase() { const query = ` DROP TABLE IF EXISTS cities; CREATE TABLE cities (id serial PRIMARY KEY, name VARCHAR(80), population INTEGER); INSERT INTO cities (name, population) VALUES ('Berlin', 3645000); INSERT INTO cities (name, population) VALUES ('Paris', 2161000); `; client .query(query) .then(() => { console.log('Table created successfully!'); client.end(console.log('Closed client connection')); }) .catch(err => console.log(err)) .then(() => { console.log('Finished execution, exiting now'); process.exit(); }); } Use this command to run the code: node connect-to-postgres.js Redis and JavaScript To work with Redis, use the ioredis library. Create a directory to store the project files: mkdir js-redis-connect && cd js-redis-connect Initialize the project: npm init -y Install the ioredis library: npm install ioredis To connect to Redis, import the ioredis library. Then create a constant named redis and specify the Redis server address. Inserting data, i.e., creating key-value objects, is done using an asynchronous function named setData, which takes two values — key and value, corresponding to the data format of the Redis system. const Redis = require('ioredis'); const redis = new Redis({ host: '91.206.179.29', port: 6379, password: 'UY+p8e?Kxmqqfa', }); async function setData(key, value) { try { await redis.set(key, value); console.log('Data successfully set'); } catch (error) { console.error('Error setting data:', error); } } async function getData(key) { try { const value = await redis.get(key); console.log('Data retrieved'); return value; } catch (error) { console.error('Error getting data:', error); } } (async () => { await redis.select(1); await setData('user', 'alex'); await getData('user'); redis.disconnect(); })(); Run: node connect-to-redis.js MongoDB and JavaScript To work with MongoDB, use the mongodb driver. Create a directory for storing the project files: mkdir js-mongodb-connect && cd js-mongodb-connect Initialize the project: npm init -y Install the mongodb library: npm install mongodb To connect to MongoDB, import the mongodb library. Specify the database address in the constant uri and pass the address into the MongoClient class. const { MongoClient } = require('mongodb'); const uri = "mongodb://91.206.179.29:27017"; const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); async function connectToDatabase() { try { await client.connect(); console.log("Successfully connected to MongoDB!"); const database = client.db("myDatabase"); const collection = database.collection("myCollection"); const documents = await collection.find({}).toArray(); console.log("Documents found:", documents); } catch (error) { console.error("Error connecting to MongoDB:", error); } finally { await client.close(); console.log("Connection closed."); } } connectToDatabase(); ClickHouse and JavaScript To work with ClickHouse, use the clickhouse/client driver. Create a directory where we will store the project files: mkdir js-clickhouse-connect && cd js-clickhouse-connect Initialize the project: npm init -y Install the @clickhouse/client library: npm install @clickhouse/client To connect to ClickHouse, use the code below where we set the connection details and execute a simple SQL query that will return the first 10 records from the system table named system.tables: const { ClickHouse } = require('@clickhouse/client'); const client = new ClickHouse({ host: 'http://localhost:8123', username: 'default', password: 'PasswordforDefaultUser45435', database: 'default', }); async function connectAndQuery() { try { console.log('Successfully connected to ClickHouse Server!'); const rows = await client.query({ query: 'SELECT * FROM system.tables LIMIT 10', format: 'JSON', }).then((result) => result.json()); console.log('Query results:', rows); } catch (error) { console.error('Error Successfully connected to ClickHouse Server! or running the query:', error); } finally { console.log('Done.'); } } connectAndQuery(); Conclusion In today's article, we thoroughly explored how to connect to PostgreSQL, Redis, MongoDB, MySQL, and ClickHouse databases using Python, Go, and JavaScript. These languages can be used to create both web applications and microservices that utilize databases in their operation.
18 February 2025 Ā· 23 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support