I recently came across a great tool for benchmarking your APIs. It’s a nodejs tool written by Matteo Figus. Complete documentation on the tool could be found here

In this post I will provide simple tutorial for anyone to use this tool for their API’s

 

  • Create a folder and run navigate to the folder using your tool of choice for running node commands. I use Git Bash. Run the following command to install the api-benchmark package. This would require node to be installed beforehand.
$ npm install api-benchmark

 

  •  Now let’s add a new JavaScript file and name it as mybenchmark.js. We will require the benchmark tool
var apiBenchmark = require('api-benchmark');

 

  •  In this example we will use the Giphy API. Giphy is a GIF search engine. So let’s define a few variables that we will use.
var service = {
  server1: "http://api.giphy.com/"
};
var apiKey = 'dc6zaTOxFJmzC'; // public beta key

 

  •  Let’s add the routes which we want to test. In this example we will get the trending gifs.
var routes = {
		trending: {
			method: 'get',
			route: 'v1/gifs/trending?api_key=' + apiKey,
			headers: {
				'Accept': 'application/json'
			}
		}};

 

  •  And finally we run the benchmark
apiBenchmark.measure(service, routes, function(err, results){
	console.log(results);
});

 

  •  Here is the complete code of mybechmark.js for your convinence
var apiBenchmark = require('api-benchmark');

var service = {
  server1: "http://api.giphy.com/"
};
var apiKey = 'dc6zaTOxFJmzC'; // public beta key

var routes = {
		trending: {
			method: 'get',
			route: 'v1/gifs/trending?api_key=' + apiKey,
			headers: {
				'Accept': 'application/json'
			}
		}};

apiBenchmark.measure(service, routes, function(err, results){
	console.log(results);
});

 

  •  To see this in action we will run the benchmark by running the following command in your console.
$ node mybenchmark.js

 

  •  And you should see something like below.
Api-Benchmark 1

Api-Benchmark 1

 

 

  • This does show that our benchmark ran but we cannot interpret the results from here. To see that we will have to use the getHtml method available on api-benchmark.
apiBenchmark.measure(service, routes, function(err, results){
  apiBenchmark.getHtml(results, function(error, html){
    console.log(html);
  });
});

 

  •  However this will dump the entire html on the console which is nearly impossible to understand.
API Benchmark 2

API Benchmark 2

 

  • We will now save this html to a file so that we can view the results like the way it was intended. Let’s require another package to help us do that
var fs = require('fs');

 

  •  Change the apiBenchmark.measure to save the html in a file
apiBenchmark.measure(service, routes, function(err, results){
  apiBenchmark.getHtml(results, function(error, html){
    fs.writeFileSync('benchmarks.html', html);
  });
});

 

  •  To see this in action we will run the benchmark by running the following command in your console.
$ node mybenchmark.js

 

  • This would create a new html file (benchmarks.html) in your current folder with the results. It would look something like below. You see the details of your requests and your api is performing.
API Benchmark 3

API Benchmark Stats

 

  • It also has 2 more tabs which show Request Details and Response Details as well. All of this provides great insight into your APIs.
API Benchmark 4

API Benchmark Request Response

 

  • However I felt that if we could get the distribution of the api calls then it would provide deeper insight into my APIs. So I added a new tab to the report to showcase the distribtion of api calls overtime. The pull request is merged. So you would notice additional tab in the report i.e. distribution tab and you should see something like below

 

API Benchmark 5

API Benchmark Distribution

 

  • We could also specify the available options to benchmark the API’s deeply. Let’s try out a few
apiBenchmark.measure(service, routes, {
			debug: false,
			runMode: 'parallel',
			maxConcurrentRequests: 10,
			delay: 0,
			maxTime: 100000,
			minSamples: 100,
			stopOnError: false
		}, function(err, results){
	apiBenchmark.getHtml(results, function(error, html){
		fs.writeFileSync('benchmarks.html', html);
	});
});

 

API Benchmark Stats 100

API Benchmark Stats 100

 

API Benchmark Distribution 100

API Benchmark Distribution 100

 

Hope this helps you in getting started with api-benchmark. The entire source code for this post can be downloaded at googledrive or onedrive

 

Any questions, comments or feedback is always welcome.

 

Grunt is a JavaScript Task Runner. Any task runner is used for automating the repetitive tasks to increase productivity and efficiency.

Some of the automated tasks include

  • Implement standards
  • Unit Testing
  • End to end testing
  • Compiling
  • Automated task execution
  • File watching

Grunt is a command line tool available on the node platform. Once you have installed node, you would need to run the following command to make grunt command line available in your project.

npm install -g grunt-cli

To run grunt commands we would also require to create a Gruntfile.js because depending on the make of the grunt tool it looks for this file. Once we have this file then we could configure tasks inline, load tasks from external sources (files and modules), etc.

It’s always easy for me when I do some hand on so that’s what we would do. Create a new file named Gruntfile.js and add the following code to it.

 

// Code example to automate minification of an existing javascript file

module.exports = function(grunt) {

                // Load the plugin that provides the "uglify" task.

                grunt.loadNpmTasks('grunt-contrib-uglify');

                // Project configuration

                grunt.initConfig({

                                uglify: {

                                                target1: {

                                                                src: 'jquery-2.1.4.js',

                                                                dest: 'jquery-2.1.4.min.js'

                                                }

                                }

                });

                // Define the default task. 'default' is the alias to 'uglify'

                grunt.registerTask('default', ['uglify']);

}

 

Now move the folder where you created the Gruntfile.js and add a new file named as package.json. We will add the package that we care about which is uglify.

{

    "devDependencies": {

        "grunt-contrib-uglify": "^0.9.1"

    }

}

 

 

Download jQuery.version.js file or any other JavaScript that you would want to minify and add to the same folder

Now run the following command in your command line tool

  1. npm install -g grunt-cli
$ npm install -g grunt-cli

C:\Users\cshukla\AppData\Roaming\npm\grunt -> C:\Users\cshukla\AppData\Roaming\npm\node_modules\grunt-cli\bin\grunt

grunt-cli@0.1.13 C:\Users\cshukla\AppData\Roaming\npm\node_modules\grunt-cli

├── resolve@0.3.1

├── nopt@1.0.10 (abbrev@1.0.5)

└── findup-sync@0.1.3 (lodash@2.4.2, glob@3.2.11)

 

  1. npm init – fills all details is package.json
$ npm init

This utility will walk you through creating a package.json file.

It only covers the most common items, and tries to guess sane defaults.

See `npm help json` for definitive documentation on these fields

and exactly what they do.

Use `npm install <pkg> --save` afterwards to install a package and

save it as a dependency in the package.json file.

Press ^C at any time to quit.

name: (FirstGruntTask)

version: (1.0.0)

description:

entry point: (Gruntfile.js)

test command:

git repository:

keywords:

author:

license: (ISC)

About to write to c:\FirstGruntTask\package.json:

{

  "devDependencies": {

    "grunt-contrib-uglify": "^0.9.1"

  },

  "name": "FirstGruntTask",

  "version": "1.0.0",

  "main": "Gruntfile.js",

  "scripts": {

    "test": "echo \"Error: no test specified\" && exit 1"

  },

  "author": "",

  "license": "ISC"

}

Is this ok? (yes) yes
  1. npm install grunt (for grunt dependencies.)
$ npm install grunt

npm WARN package.json FirstGruntTask@1.0.0 No description

npm WARN package.json FirstGruntTask@1.0.0 No repository field.

npm WARN package.json FirstGruntTask@1.0.0 No README data

grunt@0.4.5 node_modules\grunt

├── dateformat@1.0.2-1.2.3

├── which@1.0.9

├── eventemitter2@0.4.14

├── getobject@0.1.0

├── colors@0.6.2

├── rimraf@2.2.8

├── async@0.1.22

├── hooker@0.2.3

├── grunt-legacy-util@0.2.0

├── exit@0.1.2

├── nopt@1.0.10 (abbrev@1.0.5)

├── lodash@0.9.2

├── coffee-script@1.3.3

├── minimatch@0.2.14 (sigmund@1.0.0, lru-cache@2.6.2)

├── glob@3.1.21 (inherits@1.0.0, graceful-fs@1.2.3)

├── underscore.string@2.2.1

├── iconv-lite@0.2.11

├── findup-sync@0.1.3 (glob@3.2.11, lodash@2.4.2)

├── grunt-legacy-log@0.1.1 (underscore.string@2.3.3, lodash@2.4.2)

└── js-yaml@2.0.5 (esprima@1.0.4, argparse@0.1.16)

 

  1. npm install
$ npm install

npm WARN package.json FirstGruntTask@1.0.0 No description

npm WARN package.json FirstGruntTask@1.0.0 No repository field.

npm WARN package.json FirstGruntTask@1.0.0 No README data

grunt-contrib-uglify@0.9.1 node_modules\grunt-contrib-uglify

├── uri-path@0.0.2

├── chalk@1.0.0 (escape-string-regexp@1.0.3, ansi-styles@2.0.1, supports-color@1.3.1, has-ansi@1.0.3, strip-ansi@2.0.1)

├── uglify-js@2.4.21 (uglify-to-browserify@1.0.2, async@0.2.10, yargs@3.5.4, source-map@0.1.34)

├── maxmin@1.1.0 (figures@1.3.5, pretty-bytes@1.0.4, gzip-size@1.0.0)

└── lodash@3.8.0

 

 

  1. grunt
$ grunt

Running "uglify:target1" (uglify) task

>> 1 file created.

Done, without errors.

 

 

And boom we have created our first Grunt automated task to minify a JavaScript file.

You can download the source code @googledrive or @onedrive

 

An array is a collection of objects and these objects may be of different types. The difference between both these types of initialization is that JavaScript engine interprets the literals every time the array is accessed.

Initialization

We can also initialize the array to a specific size. We could also assign values particular elements of the array and when we do this the other elements will be undefined. You can see the same in the sample below where we have used for loop to show the elements of the array.

The elements of an array can be assessed directly by the 0 based index. We can use this 0 based index to get or set the value at a particular index.

function arrayDeclaration() {

var arrayObj = new Array("Item 1", 2, true);

var arrayObjWLiterals = ["Item 1", 2, false];

var arrayWithSize10 = new Array(10); // initializes array with size 10

var arrayWithUndefinedElements = ["Item 1", , "Item 3", , "Item 5"];

console.log(arrayObj); // ["Item 1", 2, true]

console.log(arrayObjWLiterals); // ["Item 1", 2, false]

console.log(arrayWithSize10); // [ ]

for (var i = 0; i < 5; i++) {

console.log("Element number " + (i+1) + " in array is " + arrayWithUndefinedElements[i]);

//Element number 1 in array is Item 1

//Element number 2 in array is undefined

//Element number 3 in array is Item 3

//Element number 4 in array is undefined

//Element number 5 in array is Item 5

}

}

When we pass an array in a function then it is a passed as a reference. This means if we change the values in the function then the value of the actual array are also modified. So we have modified the value of the 1st element of the array using array index of 0.

function passArrayInFunc() {

var arrayObj = ["Initial Value 1", "Initial Value 2"];

console.log("Array value before passing to function --- " + arrayObj); // Initial Value 1,Initial Value 2

modifyArrayFirstElement(arrayObj);

console.log("Array value after passing to function --- " + arrayObj); // Modified Value 1,Initial Value 2

}

function modifyArrayFirstElement(arrayObj) {

arrayObj[0] = "Modified Value 1";

}

Multidimensional

Multidimensional arrays have array as the elements of an array. In the previous section we saw we can access the element of an array by doing something like arrayObj[1] and this would return the element present at this index however if we do the same for a multidimensional array we will get back an array instead of an element.

var multidimArray = new Array(3);

multidimArray[0] = ["Item 0.1", "Item 0.2", "Item 0.3"];

multidimArray[1] = ["Item 1.1", "Item 1.2", "Item 1.3"];

multidimArray[2] = ["Item 2.1", "Item 2.2", "Item 2.3"];

console.log(multidimArray[0]); // ["Item 0.1", "Item 0.2", "Item 0.3"]

console.log(multidimArray[1]); // ["Item 1.1", "Item 1.2", "Item 1.3"]

console.log(multidimArray[2]); // ["Item 2.1", "Item 2.2", "Item 2.3"]

console.log(multidimArray[0][0]); // Item 0.1

console.log(multidimArray[0][1]); // Item 0.2

console.log(multidimArray[0][2]); // Item 0.3

We can use the concat method available on the multidimensional array to put all the arrays in the multidimensional array into a single array. This method takes one or more arrays and appends its elements to the new array.

var arrayObj = multidimArray[0].concat(multidimArray[1], multidimArray[2]);

console.log("Single dimensional array from multidimensional array -- " + arrayObj);

Array to string

We can convert an array into a string by simply using the join function on the array. We could simply pass nothing and comma (,) will become the delimiter for the array items or we can pass a parameter to the string function and that will act as a delimiter for each item of the string.

function arrayToString() {

var arrayObj = new Array("Item 1", "Item 2", "Item 3", "Item 4", "Item 5");

console.log("array join with no parameters - " + arrayObj.join()); // Item 1,Item 2,Item 3,Item 4,Item 5

console.log("array join with '||' as parameter - " + arrayObj.join("||")); // Item 1||Item 2||Item 3||Item 4||Item 5

}

It does not matter what types of objects does the array contains when we call the join methods it converts all the elements into its string equivalents and concatenates all the items of the array.

Sort and reverse sort an array

To sort an array of strings simply use sort method available for the array. We can see in the code below that we have sorted the list of months alphabetically.

function sortstringArray() {

var unsortedStringArray = new Array("jan", "feb", "mar", "apr", "may", "june");

console.log("sorted array --- " + unsortedStringArray.sort()); // apr,feb,jan,june,mar,may

}

Now let us try this sort function on an integer array.

function sortIntegerArray() {

var unsortedIntegerArray = new Array(5, 8, 9, 2, 6, 1, 0, 5, 6, 8, 7, 4);

console.log(unsortedIntegerArray.sort()); // [0, 1, 2, 4, 5, 5, 6, 6, 7, 8, 8, 9]

}

So it works perfectly find with single digit numbers. Now let’s try sorting with a combination of single and double digit numbers.

unsortedIntegerArray = new Array(5, 23, 13, 9, 8, 59);

console.log(unsortedIntegerArray.sort()); // [13, 23, 5, 59, 8, 9]

We get an improperly sorted array. The reason is that sort does not compare numbers but it compares the elements of the array lexically. So to fix this we need to implement our custom compare function which will return the difference of two numbers which we can use in sorting.

console.log(unsortedIntegerArray.sort(compare)); // [5, 8, 9, 13, 23, 59]

function compare(a, b) {

return a - b;

}

Now we get a properly sorted array because for each sort we are using the return value form compare method which is either +ve, -ve or 0. This same function will also work if we have numbers in form of strings. The reason is that the sort method is intelligent enough to convert these strings into numbers automatically and convert them back to string as well.

unsortedIntegerArray = new Array("5", "23", "13", "9", "8", "59");

console.log(unsortedIntegerArray.sort(compare)); // ["5", "8", "9", "13", "23", "59"]

We can achieve a reverse sort array by simply sorting the array and then reversing it as the sort function sorts the elements in the ascending order.

function reverseSortArray() {

var unsortedStringArray = new Array("jan", "feb", "mar", "apr", "may", "june", "july", "aug", "sep", "oct", "nov", "dec");

console.log("reverse sorted array --- " + unsortedStringArray.sort().reverse()); // sep,oct,nov,may,mar,june,july,jan,feb,dec,aug,apr

}

Array as a Stack and Queue

A stack is an object which adds the items in the linear order and when we retrieve the object we can access only the object that was added at the last and then the object that was added before that.

We can use the array object as a stack. We can use the push method of the array to add elements to the array and when we want to access the last added object we can use the pop method available in the array object.

function arrayAsStack() {

var arrayStack = new Array();

arrayStack.push("Item 1");

arrayStack.push("Item 2");

arrayStack.push("Item 3");

arrayStack.push("Item 4");

// This is equivalent to the code above

//arrayStack = new Array("Item 1", "Item 2","Item 3","Item 4" );

console.log(arrayStack.pop()); // Item 4

console.log(arrayStack.pop()); // Item 3

console.log(arrayStack.pop()); // Item 2

console.log(arrayStack.pop()); // Item 1

console.log(arrayStack.pop()); // undefined

}

 

A queue is a structure that allows us to enter the items into the queue in a linear way and access the item in the same order as they were added to the queue.

We can have the same behavior by using an array. We can use the push method of the array to add elements to the array and when we want to access the item in the same order they were added we can use the shift method available in the array object.

function arrayAsQueue() {

var arrayQueue = new Array();

arrayQueue.push("Item 1");

arrayQueue.push("Item 2");

arrayQueue.push("Item 3");

arrayQueue.push("Item 4");

console.log(arrayQueue.shift()); // Item 1

console.log(arrayQueue.shift()); // Item 2

console.log(arrayQueue.shift()); // Item 3

console.log(arrayQueue.shift()); // Item 4

console.log(arrayQueue.shift()); // undefined

}

Create an array from another array

We can create an array from another array by using the slice method available in the array. The slice method accepts two parameters: the start index of the array being sliced and the end index of the array being sliced.

function arraySlicing() {

var firstArray = new Array("Item 1", "Item 2", "Item 3", "Item 4", "Item 5");

var secondArray = firstArray.slice(2, 5);

console.log(secondArray); // ["Item 3", "Item 4", "Item 5"]

}

Now let us check whether the values that we copied into the array were copied as values or as references. We could check it by modifying the value of the array items and see if the changes were reflected in the array.

secondArray[2] = "modified item 5";

console.log(firstArray); // ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"]

console.log(secondArray); // ["Item 3", "Item 4", "modified item 5"]

We saw that slice copied the items into the list by copying the values. The reason was because we were copying a primitive type. Now let us create an array which has objects instead of values.

function objectArraySlicing() {

var objectArray = new Array(3);

objectArray[0] = ["Item01", "Item02", "Item03"];

objectArray[1] = ["Item11", "Item12", "Item13"];

objectArray[2] = ["Item21", "Item22", "Item23"];

var newObjectArray = objectArray.slice(1, 3);

console.log(newObjectArray.toString()); // Item11,Item12,Item13,Item21,Item22,Item23

newObjectArray[1][2] = "Modified Item 23";

console.log(objectArray.toString()); // Item01,Item02,Item03,Item11,Item12,Item13,Item21,Item22,Modified Item 23

console.log(newObjectArray.toString()); // Item11,Item12,Item13,Item21,Item22,Modified Item 23

}

So we see that when we slice the array with objects as items we see that the items are copied by references and when we change the value in any of the arrays then the value is changed in both of them.

Search in array

The array object provides us with two methods to search for items in an array. These two methods are indexOf and lastIndexOf. If the item has only one occurrence then both the methods will return the same index of the element and if there are multiple occurrences of the element then the indexOf will return the index of the first occurrence of the element and lastIndexOf will return the index of the last occurrence of the element.

function searchInArray() {

var arrayToSearch = ["jan", "mar", "may", "june", "dec", "apr", "may", "june"];

console.log(arrayToSearch.indexOf("june")); // 3

console.log(arrayToSearch.lastIndexOf("june")); // 7

}

//In both of these methods we can optionally specify the starting index of the search and will start searching for the element from that index.

console.log(arrayToSearch.indexOf("june", 4)); // 7

console.log(arrayToSearch.lastIndexOf("june", 4)); // 3

Now we specified the starting index in both our methods a 4 and we see that indexOf return 7 as the first occurrence of june which seems correct. But the lastIndexOf returns 3 which seem strange. Its correct because we said that the starting index of search is 4 and that’s where the search starts from but interestingly the lastIndexOf searches the whole array and then tells the last index and when we specified the start point of search as 4 we made the last index of array as 3 instead of 7.

Insert, replace and remove elements from array

The splice method is used to remove the elements form the array. So in the code below we have passed 3 and this will remove all the elements from the array but first three.

In the next block of code we have passed -3 and this will remove the last 3 elements from the array.

function removeFromArray() {

var arrayToSearch = ["jan", "mar", "may", "june", "dec", "apr", "may", "june"];

console.log("Array before -- " + arrayToSearch); // jan,mar,may,june,dec,apr,may,june

arrayToSearch.splice(3);

console.log("Array after -- " + arrayToSearch); // jan,mar,may

var arrayToSearch = ["jan", "mar", "may", "june", "dec", "apr", "may", "june"];

console.log("Array before -- " + arrayToSearch); // jan,mar,may,june,dec,apr,may,june

arrayToSearch.splice(-3);

console.log("Array after -- " + arrayToSearch); // jan,mar,may

}

We can insert an element at any index in the array. We can use the splice method to do that.

function insertInArray() {

var arrayToSearch = ["jan", "mar", "may", "june", "dec", "apr", "may", "june"];

console.log("Array before -- " + arrayToSearch); // jan,mar,may,june,dec,apr,may,june

arrayToSearch.splice(3, 0, "july");

console.log("Array after -- " + arrayToSearch); // jan,mar,may,july,june,dec,apr,may,june

}

Here we have passed 3 parameters to the splice method:

  • Index: We have passed 3 as the index where we insert the new element.
  • Element count to remove: We have passed 0 as number of elements we want to replace.
  • Element to add: We have passed “july” as the element we want to insert.

We can use a combination of splice and indexOf methods to remove and replace elements within an array.

function replaceInArray() {

var arrayToSearch = ["jan", "mar", "may", "june", "dec", "apr", "may", "june"];

console.log("Array before -- " + arrayToSearch); // jan,mar,may,june,dec,apr,may,june

arrayToSearch.splice(arrayToSearch.indexOf("june"), 1, "july");

console.log("Array after -- " + arrayToSearch); // jan,mar,may,july,dec,apr,may,june

}

We see here that we have passed 3 parameters to the splice method.

  • Index: We have passed the index by using the indexof method. This index is the place where we want to insert the new element.
  • Element count to remove: We have passed 1 as number of elements because I want to replace june.
  • Element to add: We have passed “july” as the element we want to insert.

Till now we have just passed one element that we want to add to the array. We can pass a list of elements we want to add to the array.

function addMultipleElements() {

var arrayToSearch = ["jan", "mar", "may", "june", "dec", "apr", "may", "june"];

console.log("Array before -- " + arrayToSearch); // jan,mar,may,june,dec,apr,may,june

arrayToSearch.splice(1, 7, "feb", "mar", "apr", "may", "june", "july", "aug");

console.log("Array after -- " + arrayToSearch); // jan,feb,mar,apr,may,june,july,aug

}

The code for this post can be found here.

Any questions, comments or feedback is really appreciated.

 

 

The math object in JavaScript does not have constructor so we cannot instantiate it. All the methods and properties can be assessed directly from the math object.

Math Object Properties

The following properties are available on the math object

E Returns Euler’s number (approx. 2.718)
LN2 Returns the natural logarithm of 2 (approx. 0.693)
LN10 Returns the natural logarithm of 10 (approx. 2.302)
LOG2E Returns the base-2 logarithm of E (approx. 1.442)
LOG10E Returns the base-10 logarithm of E (approx. 0.434)
PI Returns PI (approx. 3.14)
SQRT1_2 Returns the square root of 1/2 (approx. 0.707)
SQRT2 Returns the square root of 2 (approx. 1.414)

 

Math object methods

The following methods are available on the math object.

abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
atan2(y,x) Returns the arctangent of the quotient of its arguments
ceil(x) Returns x, rounded upwards to the nearest integer
cos(x) Returns the cosine of x (x is in radians)
exp(x) Returns the value of Ex
floor(x) Returns x, rounded downwards to the nearest integer
log(x) Returns the natural logarithm (base E) of x
max(x,y,z,…,n) Returns the number with the highest value
min(x,y,z,…,n) Returns the number with the lowest value
pow(x,y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Rounds x to the nearest integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle

Generating random number

We have a random method available in the Math class which can be used for the random number generation. The only restriction with this approach is that that the random method outputs a value between 0 and 1 which is not suitable with most of our needs.

function randomBetween0and1() {

console.log("Random number - " + Math.random()); // 0.6579966396093369

console.log("Another random number - " + Math.random()); // 0.5774516856763512

console.log("Yet another random number - " + Math.random()); // 0.7963233035989106

}

To increase the range of our randoms we can simply multiply then every time by the maximum value that we want for our random number. Let’s say we want random number between 0 and 999, so will multiply the output of random function by 999.

function randomBetween0and999Float() {

console.log("a random between 0 and 999 is " + (Math.random() * 999)); // 541.2334246176761

console.log("a random between 0 and 999 is " + (Math.random() * 999)); // 56.533659977372736

console.log("a random between 0 and 999 is " + (Math.random() * 999)); // 889.5993133583106

}

As you can see we got random numbers between 0 and 999 but these random number are not whole numbers to fix that all we need to do is use the floor function available in the math class which rounds of the decimals to nearest value.

function randomBetween0and999() {

console.log("a random between 0 and 999 is " + Math.floor((Math.random() * 999))); // 541

console.log("a random between 0 and 999 is " + Math.floor((Math.random() * 999))); // 56

console.log("a random between 0 and 999 is " + Math.floor((Math.random() * 999))); // 889

}

Now say we want to generate the random number between 99 and 999. We will use the same way but now instead of just multiplying the random number by upper range but we will multiply by upper range – (lower range – 1) and then multiply by lower range.

function randomBetween99and999() {

console.log("a random between 99 and 999 is " + (Math.floor((Math.random() * 901)) + 99)); // 541

console.log("a random between 99 and 999 is " + (Math.floor((Math.random() * 901)) + 99)); // 156

console.log("a random between 99 and 999 is " + (Math.floor((Math.random() * 901)) + 99)); // 889

}

The code for this post can be found here.

Any questions, comments or feedback is really appreciated.

 

 

Just like the string object the number object can behave as a value type or object.

The number in JavaScript is equivalent to the float in any other programming language but it behaves both as a float or an integer depending on whether the decimal is present.

Assign Value to number

We can either directly assign a value to the number or we use the number constructor to do that.

var num = 5;

console.log("Value assigned to num by initializing without constructor = " + num); // Value assigned to num by initializing without constructor = 5

num = new Number(25);

console.log("Value assigned num by initializing with constructor = " + num); // Value assigned num by initializing with constructor = 25

num = 3.14;

console.log("Float value assigned to num = " + num); // Float value assigned to num = 3.14

Maximum value of number

The maximum value of number in JavaScript is 1.7976931348623157e+308 and values larger then this are considered infinity.

console.log("maximum value of number in javascript is = " + Number.MAX_VALUE);

// maximum value of number in javascript is = 1.7976931348623157e+308

console.log("overflown value of number in javascript is = " + (Number.MAX_VALUE * 5));

// overflown value of number in javascript is = Infinity

Number properties

The various properties available on the number are:

constructor Returns the function that created the Number object’s prototype
MAX_VALUE Returns the largest number possible in JavaScript
MIN_VALUE Returns the smallest number possible in JavaScript
NEGATIVE_INFINITY Represents negative infinity (returned on overflow)
NaN Represents a “Not-a-Number” value
POSITIVE_INFINITY Represents infinity (returned on overflow)
prototype Allows you to add properties and methods to an object

Number methods

The various methods available on number are:

toExponential(x) Converts a number into an exponential notation
toFixed(x) Formats a number with x numbers of digits after the decimal point
toPrecision(x) Formats a number to x length
toString() Converts a Number object to a string
valueOf() Returns the primitive value of a Number objec

 

Source – http://www.w3schools.com/jsref/jsref_obj_number.asp

We can try to parse any string value into integer by using the parseInt method. It can also be used to parse string which contains number in the string.

function parseStringToInt() {
                console.log("string 3 is number " + parseInt("3")); // string 3 is number 3 
                console.log("string 3.14 is number " + parseInt("3.14")); // string 3.14 is number 3
                console.log("string '54454 meters' is number " + parseInt("54454 meters")); // string '54454 meters' is number 54454
                console.log("string '35 meters 542' is number " + parseInt("35 meters 542")); // string '35 meters 542' is number 35
                console.log("string xyz is number " + parseInt("xyz")); // string xyz is number NaN 
            }

Number as counter

The most common use of number in JavaScript is as a counter. We use it to keep track of as to how many times we have executed a particular block of code or loops like for, while, etc. Either the number the number is initialized at the start of a function or at global level and the number of times we execute the loop we increment the number and that’s how we know as to how many times we executed our loop.

function counterSample() {

var counter = 0;

while (counter <= 10) {

console.log(counter);

counter++; // equivalent to counter + 1

}

}

You will notice that we have used counter++. It is nothing special but a different notation for counter+1

There are situations when we need to use reverse counting in that case we can initialize the counter to some value and the decrement it each time.

function reverseCounterSample() {

var counter = 10;

while (counter >= 0) {

console.log(counter);

counter--; // equivalent to counter - 1

}

}

counter — is equal to counter – 1.

We could also use ++counter instead of counter++. The difference between them is that when we use ++ before counter then the value of counter is incremented before it is used and when we use ++ after counter the value is incremented after this value is used in the current statement. This will make lot more sense in the below code

function prePostOperandSample() {

var counter = 10;
console.log("Post Operand increment value = " + (counter++)); // 10

counter = 10;
console.log("Pre Operand increment value = " + (++counter)); // 11
}

Decimal – Binary – Octal – Hex Conversion

Using the number class we can convert the numbers in different formats using the toString() method.

function numberConverstion() {

var num = 109;

console.log("Hexadecimal format - " + num.toString(16)); // 6D

console.log("Decimal format - " + num.toString()); // 109

console.log("Octal format - " + num.toString(8)); // 155

console.log("Binary format - " + num.toString(2)); // 1101101

}

The code for this post can be found here.

Any questions, comments or feedback is really appreciated.