JavaScript Interview Day # 3: what is arguments object in a function

I am very sure that in JavaScript interviews, you must have gone through discussions on functions. It is obvious because functions are very core of JavaScript. Whenever there is a discussion on functions, discussion on arguments object is mandatory. If you do not understand, how arguments works, you do not understand how functions works in JavaScript.

Let us start with the function given below:

Above, you have created add function which takes two input parameters and returns a result adding these two numbers. It is the simplest JavaScript function you can think of.

In above functions besides num1 and num2 there is one local variable available arguments object. The arguments object is local variable, which is available within all functions. Therefore, each JavaScript functions has arguments object variable, which is used to access all the parameters passed to the function.

So, you can rewrite above add function to achieve same output using the arguments object as shown in the listing below:

image

In JavaScript, arguments object variable is local to the function and it is an ARRAY LIKE object but it is NOT AN ARRAY. It supports property like length and items can be accessed using square bracket. However, other array methods such as push, pop etc. are not supported.

Key features of arguments object are as follows:

  1. It is an array like object but not an array.
  2. Number of parameters passed to function can be find using the argument.length inside the function.
  3. Other arrays methods like push, pop etc. are not allowed on arguments object.
  4. If there are three parameters passed to function then using argument object they can be accessed as :
  1. arguments[0]
  2. arguments[1]
  3. arguments[2]

Consider the below function foo,

In above function, number of parameters passed to function foo is find-using arguments.length and all passed parameters are accessed in the loop using arguments[i]. For above code output would be as shown in the image below:

image

If you try to perform other array operations like pop, push etc. on the arguments object, JavaScript will throw exception.

Code listed above will throw you exception as shown in the image below:

image

Keep in mind that using the square bracket you can change value of a specific item in arguments object. Let us consider the code listed below:

In above code snippet,

num1= arguments[0]

num2 = arguments[1]

So, if we change value of arguments[0], value of num1 will be also changed. Also you seen that in the function value of passed parameter can be changed using the square bracket. Therefor output of above code snippet would be 10 instead of 5 as shown in the image below:

image

Now, you can say that arguments object is not an array; rather it is array like object. It does not have any array properties except of length property.

image

Besides length property arguments object has other properties argument.callee : It returns the currently executing function.

Output of above code would be function foo as shown in the below image:

image

Converting arguments object to array

You may come across requirement to convert arguments object to array. You can do that using the Array.from function.

Output of above code snippet would be 78, which last parameter is passed to the function. Other example, we could take to write a function, which will concatenate all the strings passed to it,

Above code snippet will give you output as shown in the image below:

image

In real scenarios, you may have to convert arguments object to array to use it in ways that are more effective. Last but not least keep in mind that arguments are an object. Therefore, when you print type of arguments, you will get output object.

image

Having understanding of arguments object will help you to write better JavaScript functions. This is one of my favorite feature and I have seen it used a lot. I hope now you will be able to answer questions around arguments object. Thanks for reading.

JavaScript Interview Day # 2: Can you explain undefined and null

Have they ever asked you? “Can you explain null and undefined in JavaScript?” This question is very trivial but important. As a JavaScript developer, you must have absolute understanding on undefined and null.

Let us start by looking at code below:

Output of above code listing would be “undefined” as shown in the image below:

image

What is going on here? Whenever you have created a variable in JavaScript and have not assigned any value to it, then that variable will contain a value “undefined”. So undefined is missing value in the JavaScript.

Let us consider another code snippet,

Output of above code listing would be “null” as shown in the image below:

image

So what is going on here? When you create a variable but not sure what should be the value, you may assign it with the value null. Therefore, null is a primitive value in the JavaScript.

What is null?

In JavaScript, null represents intentional absence of a value. It is a primitive JavaScript value. You can say null indicates an object with no value

image

You can assign null to a variable as indication of no value. It can be assigned to a variable. In JavaScript null can be assigned to any variable as representation of no value. Therefore, JavaScript very much allow you to perform the task shown in the listing below:

Every value has a type in JavaScript and type of null is object. Try running below code

You will get below output which shown type of null is object.

image

JavaScript never set value null to any variable automatically, If you want to set variable value null, it has to be done programmatically.

image

In JavaScript arithmetic operations, null becomes zero. So if you try to perform following operations

Output of above operation would be as below:

image

As you might have noticed that, JavaScript is converting null value to zero value for all the arithmetic operations.

image

JavaScript treats null as zero for comparisons. However, keep in mind null is not equal to zero. Try performing below operations :

You will get output as shown below:

image

You can see that JavaScript is treating null as zero for the comparison operations.

image

What is undefined?

In JavaScript undefined is created at run time and assigned as missing value. Therefore, if you have not assigned any value to a variable then at run time JavaScript will assign undefined to that variable.

Consider the code given below:

Since, you are not assigning any value to foo, at runtime JavaScript will assign undefined to foo. Output of above code listing would be as shown in the image below:

image

Therefore, in JavaScript undefined represents a missing value.

JavaScript assigns undefined in following scenarios:

1. When a variable is declared but not assigned any value

2. When a function parameter is missing. So in below code listing, you are not passing value of parameter b, therefor JavaScript will assign value undefined to b.

Output of above code listing would be “undefined” as shown in the image below:

image

3.  When you call a function as function invocation pattern and if explicitly function does not return any value then it returns undefined.

image

In above listing, you are calling a function as function invocation pattern. In FIP, when function does not return anything explicitly, JavaScript returns undefined for that. Therefore, output of above function would be as shown in the image below:

image

4. JavaScript also assigns undefined to out of array index in an array.

In above code snippet, you are trying to print fifth element of the array, however the size of the array is four. Therefore, JavaScript will print undefined for the fifth element. JavaScript will give you output as shown in the image below:

image

5. JavaScript returns undefined on accessing the object property, which does not exist. Let us consider below listed code

Student object does not have grade property, so JavaScript will print undefined for this. You will get below output for above code,

image

In arithmetic, operations if one of the operand is undefined then JavaScript will always evaluate result to NaN. Consider the code listing given below:

As output, JavaScript will evaluate all operations to NaN as shown in the image below:

image

Therefore, if any of the operand is undefined then JavaScript evaluates arithmetic operation to NaN.

image

Type of null was object, however, type of undefined is a special type undefined.

Above code will print type of undefined as undefined.

image

null and undefined

In strict comparison null and undefined are not same. Therefore, below code will give you output false.

However, in type-converting equality comparison null and undefined are same. Therefore, below code will give you output true

In this post, you learnt one of the most important concept of JavaScript undefined and null. Having a good understanding of undefined and null helps you in faster debugging and write better JavaScript codes. I hope, now you will able to answer undefined and null in the interviews.

JavaScript Interview Day # 1: How to create a Class

Have they ever asked you that “How you create class in JavaScript?” I am sure, regardless level of JavaScript interview; you must have come across this question. Well, there is no one answer of this question. However, before you go ahead and read detailed answer in this post, let me give you a gist in two bullet points,

  1. In ECMA 6, class can be created using the keyword class
  2. In earlier version like ECMA 5, calling a function using the new operator returns an object. So you can say , “when we call a function using the new operator (which is also known as ‘constructor invocation pattern’), function acts like a class and returns a newly created object ”

Class in ECMA 6

In ECMA 6, you can create a Student class as shown in the listing below:

ECMA 6 allows you to create a class using the keyword “class”. You can create object of Student class using the new operator as shown in the listing below:

Like function declaration and expression, class can also be created

  1. Class declaration
  2. Class expression

image

Above, you created Student class using the class declaration syntax. Same Student class can be created using the class expression syntax as shown in the listing below:

Above, you created Student class using the class unnamed expression syntax. Same Student class can be created using named class named expressions syntax as shown in the listing below:

Keep in mind that name given to class expression is local to the class body.

Hoisting of the class

Did you remember that functions declaration is hoisted? Means, you can call a function declaration before it is created.

In above listing you declared a function and that is hoisted, so you are able to execute it before it is created. However, class are not hoisted in JavaScript. Does not matter whether you are creating a class as declaration or expressions, they are not hoisted. So if you do something as shown in below listing

On running above code will throw you ReferenceError exception.

image

Therefore, conclusion is unlikely JavaScript functions classes are not hoisted.

image

A class can be referred in the function which comes before class declaration. However, you can call such function only after the declaration of the class. Let us consider below code

In above code, first function call will throw reference error, whereas second function call will work fine.

Methods in class

Most often you will create these three types of methods in the class,

  1. Constructor
  2. Static
  3. Prototype

Constructor method

A constructor method is a special method. Constructor method creates and initializes the object created with the class. A class can have only one constructor method. More than one constructor method in the class will throw exception. A class with constructor can be created as shown in the listing below:

image

Static methods

Like any other programming languages, JavaScript static methods are called without creating the object of the class. You can create a class with static method as shown in the listing below:

You can call static method with the class name as shown below:

When you try calling static method with instance of the class, JavaScript will throw exception. As of now JavaScript does not support static members or properties.

image

Prototype methods

JavaScript class prototypes methods are the methods used by the instances of the class. They are the normal methods, which can be inherited and used by the objects.

These prototype methods can be used with instance of the class as shown in the listing below:

These prototype properties are actually property of the Student.prototype.

image

In JavaScript, functions have prototype property, and class has prototype property. Because type of class is function. So when you execute below code,

Output of above code would be function.

image

Class in ECMA 5

You do not create class using the class keyword in ECMA 5. If you wish to create same class Student in ECMA 5, create a function with the name Student as shown in the listing below:

You can add prototype methods as shown in the listing below:

Now to create objects, call function Student using the new operator as shown in the listing below:

Calling a function using the new operator is also called as “Constructor Invocation Pattern”. Therefore, in ECMA 5, when you call a function using the new operator, function acts as a class and returns an object.

Here, you also learnt what constructor invocation pattern is. I hope now you should able to answer

  1. How to create class in ECMA 6
  2. How to create class in ECMA 5
  3. What is Constructor Invocation Pattern

I hope it helps. Thanks for reading.

Step by Step building Node.js based REST API to perform CRUD operations on MongoDB.

Download Source Code of this post from GitHub here

Node.js is one of the greatest platform to create backend of the application. Does not matter whether you are creating a mobile app for iOS or Single Page Web application using Angular, you will need a backend for the application. Usually you perform databases operations, authentications, authorizations, logging etc. in the backend. I am sure, you have heard about the term MEAN stack. If you have not, MEAN stands for MongoDB, Express JS, Angular, and Node.js.

image

In the MEAN stack, you create backend of the application using MongoDB, ExpressJS and NodeJS. In this article, you will learn to create a REST API to perform CRUD operations on MongoDB. You will use ExpressJS and NodeJS to create the REST API.

In this post, you are going to create a REST API to preform CRUD operations.

image

From the client, you will perform operations such as GET, POST, PUT, and DELETE to perform CRUD operations. Therefore, to create a record, you will perform HTTP POST operation and pass data to be inserted in the body of the HTTP request.

image

At the end of this post you will have a working API running which will perform CRUD operations.

Installation

To follow along this post, make sure you have following software installed on your machine.

To configure MongoDB , after installation make sure that you have in your primary drive where OS is installed(C drive in most of the cases on Windows) a folder called data\db. If you do not have create this folder. By default, MongoDB look for this folder to work with. Also, make sure to start MongoDB server by running Mongod.exe command as shown in the image below, to work with this post

image

After successful installation, create a blank folder in which you will create the project. Give whatever name you wish to give this folder. I am calling it as Project folder.

Step 1: Install dependencies

In the project folder, add a file with name package.json. We are going to use npm (Node Package Manager) to install all the dependencies. Node Package Manager (npm) reads package.json file to install the dependencies in the project. Add the below code in package.json.


{
    "name": "product-api",
    "main": "server.js",
    "dependencies": {
        "express": "~4.0.0",
        "body-parser": "~1.0.1",
        "cors": "2.8.1",
        "mongoose": "~3.6.13"
    }
}

In this, we are mentioning that, the project we are going to create will have following dependencies :

  • Express JS to create API routes.
  • Body parser to parse JSON data coming from the client.
  • CORS to enable the cross origin resource sharing support in your API.
  • Monogoose to work with MongoDB in NodeJS.

After updating package.json with above code, open the project in the command prompt and run the command npm install. I am assuming here that, you have already NodeJS installed on your system. If you haven’t installed it, click here and install.

Once you have successfully ran npm install command, you will find a node_modules folder which is created inside your project containing all the required dependencies to create REST API in NodeJS, performing CRUD operations on MongoDB.

Step 2: Create Model

When you work with RDBMS such as SQL Server or MySQL, you create model to perform CRUD operations on that particular table. MongoDB is a document-based database, and in this, you can insert, delete, update or read documents. MongoDB does not restrict you to create fixed model to perform database operations. However, to work with mongoose, you need a model. So, let us create a model of the document to perform CRUD operations.

In the project, add a file called product.js and create model with name Product as shown in the listing below :


var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ProductSchema = new Schema({
    title: String,
    price: Number,
    instock: Boolean,
    photo: String,
});
module.exports = mongoose.model('Product', ProductSchema);

As you might have noticed, Product model contains four properties of different data types.

Step 3: Create Server

In this step, we will create server for REST API. For creating a server, add a file in the project called server.js. Go back and examine package.json file, you will find that the value of main is set as server.js. Therefore, node server will look for server.js to start the server. We are going to put all the starting codes in the file.

To start with, in server.js, add the following required statements at the top of the file.

var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var app = express();
var mongoose = require('mongoose');
var product = require('./product');

After importing all the required modules, create route, assign port, and use body parser to parse incoming JSON data. To do these, after last require statement add the codes listed below in server.js file.


app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8090;
var router = express.Router();

In the above snippet, we are assigning port and creating the router. After this, at the end of the server.js file, add the code listed below :


app.use(cors());
app.use('/api', router);
app.listen(port);
console.log('REST API is runnning at ' + port);

In the above snippet, you are enabling CORS support, configuring port for the API, and also configuring that REST API would be created on baseurl/api/{routename}. At this point, you have configured server for various API settings and assigned port to work with that. Keeping everything together, at the end of this step, server.js file will look like below:

Server.js


var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var app = express();
var mongoose = require('mongoose');
var product = require('./product');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8090;
var router = express.Router();

// all other code will go here 

app.use(cors());
app.use('/api', router);
app.listen(port);
console.log('REST API is runnning at ' + port);

Step 3: Connect to MongoDB server

In this step, you will connect application to MongoDB database server. To do this, just after router creation code (or at the place where there is a comment “all codes goes here”), add the code mentioned below:


mongoose.connect('mongodb://localhost:27017/products');

You are connecting to product database of MongoDB server. By default, MongoDB runs on the port 27017.

Note:

At this point, make sure that your MongoDB server is running on this port, otherwise you will get an exception when running the API. On Windows, to run the server- navigate to c:\program files\mongodb\server\3.4\bin on the command prompt and run the command mongod.exe. This command will start the MongoDB server. Here I am assuming that, you already have MongoDB installed. If you do not have, you can download and install MongoDB from here

Step 4: Creating the middle route

Let us start with writing a route, which will be called before any route. In this route, you can perform various operations such as :

  • Authentication
  • Authorization
  • Logging

In Express JS, you can very easily create this route by adding a “use route” as shown in the listing below:


router.use(function (req, res, next) {
    // do logging 
    // do authentication 
    console.log('Logging of request will be done here');
    next(); // make sure we go to the next routes and don't stop here
});

Make sure to add above code in server.js, just after the code you created in step 3.

Step 5: Creating Record

To create the record or insert a new document, you need to create a route for the POST operation. In REST API, convention is that, whenever client will perform the POST operation, a new record will be created. So, let us start with creating a route for the POST operation. To create that, just below the “use route” line of code, add the code mentioned below :


router.route('/products').post(function (req, res) {

   
});

The above route will be called, whenever client will perform HTTP POST operation on baseurl/api/products

Next, you need to write the code to insert data in the database. For that, you need to perform two operations :

  1. Create model object using the request body. If you remember, we have created a model in the step 2.
  2. Call the save function on model object to save the record in the database.

To do the above tasks, you need to modify POST route as shown below:


router.route('/products').post(function (req, res) {
    var p = new product();
    p.title = req.body.title;
    p.price = req.body.price;
    p.instock = req.body.instock;
    p.photo = req.body.photo;
    p.save(function (err) {
        if (err) {
            res.send(err);
        }
        res.send({ message: 'Product Created !' })
    })
});

Run and Test

To test the Create API, run the command

image

Now your API is running on the port 8090. To test the API, open POSTMAN and perform a POST operation on URL baseurl/api/products.

image

Beside the above configuration, in Headers, a content-type is added as application/json. When you click on send, if everything happens as expected, you will be getting the response from the API as shown in the image below:

image

You might be wondering, in which database product it has been created? In the previous steps, you connected to database “products”. So all the operations will be performed with Products database. Also in step 2, while creating a model, since we have not provided any collection name, record will be created in products (plural of model name product) collection.

Step 6: Fetching Records

To fetch records, you need to perform GET operation. To do so, add a get route to the API. A GET route could be added as shown in the listing below:


router.route('/products').get(function (req, res) {
    product.find(function (err, products) {
        if (err) {
            res.send(err);
        }
        res.send(products);
    });
});

In above listing, you are using mongoose ‘find function’ to fetch all the records from the MongoDB collection.

The above route will be called, whenever client will perform HTTP GET operation on baseurl/api/products. To test API, open POSTMAN and perform a GET operation on URL baseurl/api/products.

image

In Postman, you will find that, HTTP GET operation returns all the records. To return to a particular record on basis of ‘product_id’, add a new route to the API such that, whenever you perform GET operation with product_id as query parameter on the same URL, you will fetch a particular record.


router.route('/products/:product_id').get(function (req, res) {

    product.findById(req.params.product_id, function (err, prod) {
        if (err)
            res.send(err);
        res.json(prod);
    });
});

To fetch a particular product, you are using mongoose findById() function which takes product_id as input parameter. To read input parameter from HTTP GET operation, we are using req.params property.

The above route will be called, whenever client will perform HTTP GET operation on baseurl/api/products/{product_id}. To test API, open POSTMAN and perform a GET operation on URL baseurl/api/products/{product_id}.

 

image

You will find that a particular product has been returned with matching product_id.

Step 7: Updating Record

To update a record, you need to perform HTTP PUT operation. While performing PUT operation,

  • Pass product_id need to be updated as query parameter.
  • Pass product object need to be updated as request body.

To perform PUT operation, create a PUT route as shown in the listing below:


router.route('/products/:product_id').put(function (req, res) {

    product.findById(req.params.product_id, function (err, prod) {
        if (err) {
            res.send(err);
        }
        prod.title = req.body.title;
        prod.price = req.body.price;
        prod.instock = req.body.instock;
        prod.photo = req.body.photo;
        prod.save(function (err) {
            if (err)
                res.send(err);

            res.json({ message: 'Product updated!' });
        });

    });
});

So, what is going on in above code listing? These are the operations that need to be done to perform the updated operation.

  • Fetch product to be updated from the collection.
  • Update fetched product properties with the request body object properties.
  • Save the product to the collection using save method.

The above route will be called to update a particular product, whenever the client will perform HTTP PUT operation on baseurl/api/products/{product_id}. To test API, open POSTMAN and perform a PUT operation on URL baseurl/api/products/{product_id}. You need to pass product object to be updated in the body of the request as shown in the image below:

image

Step 8: Deleting Record

To delete a particular record, client needs to perform HTTP DELETE operation. To do this, create a route for delete operation.


router.route('/products/:product_id').delete(function (req, res) {

    product.remove({ _id: req.param.product_id }, function (err, prod) {
        if (err) {
            res.send(err);
        }
        res.json({ message: 'Successfully deleted' });
    })

});

Client will pass product_id to be deleted in the query parameter. Note : Product remove method is used to remove a product from the collection.

The above route will be called to delete a particular product, whenever client will perform HTTP DELETE operation on baseurl/api/products/{product_id}. To test API, open POSTMAN and perform a DELETE operation on URL baseurl/api/products/{product_id} as shown in the image below:

image

You just created a full working REST API to perform CRUD operations on MongoDB using NodeJS. In next post, we will use this API with Angular application to complete an application using MEAN stack. Thanks for reading.

Download Source Code of this post from GitHub here