Top Node JS Interview Questions & Answers

There are a few steps to create a server in Node.js:
a) First, import the HTTP module.
b) Then, use the createServer() function with a callback function using request and response as parameters
c) Type “Hello Ajay Kumar"
d) Set the server to listen to port 5000
                                    
                                        const http = require("http");

const server = http.createServer((req,resp)=>{

  resp.writeHead(200,{"Content-Type":"text/plain"});
  resp.end("Hello Ajay Kumar")
})

const PORT = process.env.PORT ||  5000;
server.listen(PORT,()=>{
console.log(`my server start on this port ${PORT}`)
});
                                    
                                

Feature Express.js Node.js
Type Framework Runtime Environemnt
Language JavaScript JavaScript
Purpose To build web applications To run JavaScript code outside of a browser
Features Routing, middleware, template engines, etc. Event-driven, non-blocking I/O, etc.
Dependencies Node.js N/A
Popularity Very popular Very popular
Examples GitHub, Uber, Netflix PayPal, LinkedIn, Walmart

There are a few steps to create a server using Express in Node.js:
a) Write this command in your terminal, to create a nodejs application, because our express server will work inside the node application.
Syntax :
                                    
                                        npm init
                                    
                                
This will ask you for few configurations about your project you can fill them accordingly, also you can change it later from the package.json file.
Note : Use `npm init -y` for default initialization
b) Install the Express.js framework as a dependency for our project. Run the this command:
                                    
                                        npm install express
                                    
                                
c) Set the server to listen to port 8000
                                    
                                        const express = require('express');
  
                                        const app = express();
                                        const PORT = 8000;
                                          
                                        app.listen(PORT, (error) =>{
                                            if(!error)
                                                console.log(`My server start on this port ${PORT}`)
                                            else 
                                                console.log(" Server can't start", error);
                                            }
                                        );

                                    
                                
d) Step to run the application :
                                    
                                        node index.js
                                    
                                

-save -save-dev
The package installed is core dependency. The package installed is not a core rather development dependency.
All core dependency is listed under dependencies in package.json. All development dependency is listed under devDependencies in package.json.
It will be installed if a third person tries to install or clone your package. It will be installed if a third person tries to clone your package.
Example: express, body-parser etc. Example: nodemon

Synchronous function Asynchronous function
These are the function that block the execution of the program whenever an operation is performed. Hence these are also called blocking operations. These are the operations that do not block the execution of the program and each command is executed after the previous command even if the previous command has not computed the result.
We use these functions to perform lightweight tasks We use these functions to perform heavy tasks.

In Node.js Application, a Module can be considered as a block of code that provide a simple or complex functionality that can communicate with external application. Modules can be organized in a single file or a collection of multiple files/folders. Modules are useful because of their reusability and ability to reduce the complexity of code into smaller pieces. Some examples of modules are. http, fs, os, path, etc.

  • Fast runtime environment
  • Asynchronous features
  • Uses caching to reduce loading time
  • Requires only JavaScript to handle both front-end and back-end development
  • Support from a large community of Node.js developers
  • Below are descriptions of two libraries Node.js developers often use:
  • Express.js : This flexible web application framework for Node.js offers several features that support mobile and web application development
  • Mongoose: This web application framework for Node.js enables developers to connect their applications to a database.
  • Node.js modules are similar to JavaScript libraries
  • Developers can include them in a Node.js application if they want to use specific functions
  • Programmers should use the require() function and add the module’s name in the parentheses to include modules in the application
  • Undeclared variables are not declared and don't exist in a program. A runtime error occurs if the software tries to read the value of an undefined variable.

    Variables declared in the program but do not have a value are considered undefined variables. An undefined value is returned if the software tries to read the value of an undefined variable.

    By pressing the appropriate key, typically the F12 key, all contemporary web browsers, including Chrome, Firefox, and others, feature an integrated debugger that can be used anytime. The debugging tools provide users with a number of functions.

    The different ways to remove duplicates in Javascript are mentioned below:

    Filter method:
    Three arguments are specified to call the filter() function. These are the array, element in use, and element index.

    For loop:
    All the recurring elements are kept in an empty array.

    The symbols for comments are given below:
                                
                                    // for Single line comments and
    
                                    /* Multi
                                    Line
                                    Comment
                                    */
                                
                            
    Note that you can use an arrow function to define an IIFE:

    Example 1 :
                                
                                    (function(){
                                        let x="Ajay"
                                        console.log(x) // Ajay
                                      })();
                                
                            
    Example 2 :
                                
                                    (function(a,b){
                                        console.log(a+b)  // 30
                                        return a + b;
                                    })(10,20);
                                
                            
    Example 3 :
                                
                                    (function() {
                                        var counter = 0;
                                    
                                        function add(a, b) {
                                            return a + b;
                                        }
                                    
                                        console.log(add(10,20)); // 30
                                    }());
                                
                            
    Example 4 :
                                
                                    (function() {
                                        var counter = 0;
                                    
                                        function add(a, b) {
                                            return a + b;
                                        }
                                    
                                        console.log(add(10,20)); // 30
                                    }());
                                
                            
    Important Point
  • IIFE follow their own scope like any other function/variable in JavaScript.
  • The part of the name immediately invoked is sometimes confusing to new developers as they expect the IIFE to execute irrespective of function scope, this is wrong. For example, let us take the following example where the IIFE is defined within a function and will only be immediately invoked if we call it the Parent Function.
  • Example 5 :
                                
                                    function myFunc()
                                    {
                                        console.log("Welcome to");  // Welcome to
                                        // This will be executed after executing the previous log.
                                        (function() { 
                                            console.log("Ajay Kumar"); // Ajay Kumar
                                        })();
                                        console.log("Hi There!");  // Hi There!
                                    }
                                      
                                    
                                    myFunc();
                                
                            
  • 1. IIFEs have their own scope i.e. the variables you declare in the Function Expression will not be available outside the function.
  • 2. Similarly to other functions IIFEs can also be named or anonymous, but even if an IIFE does have a name it is impossible to refer/invoke it.
  • 3. IIFEs can also have parameters. For example,
  • Example 6 :
                                
                                    // Declaring the parameter required.
                                    (function(dt) {
                                     console.log(dt.toLocaleTimeString());  // 6:12:57 PM
                                     // Passing the Parameter.
                                 })(new Date());