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.

 

In this post we will talk about timers and their usage in JavaScript

Timers are available in the Window object. It takes two parameters the time in milliseconds and expression or the function. We have 2 types of timers:

setInterval (func, milliseconds) – this timer is recursive and will evaluate the expression each time when the timespan that we have specified occurs.

setTimeout (func, milliseconds) – this timer is executes the expression once when the timespan we specified is passed.

We also have clear method available on both types of timers.

clearInterval (id) – takes the id of the timer to clear so that the specified code is not executed at specified intervals.

clearTimeout (id) – takes the id of the timer to clear so that the specified code is not executed at specified timeout time.

Another thing to keep in mind about the timers is that the timers run on the same thread as the UI events. All JavaScript in the browser executes in the single thread asynchronous events and this forces JavaScript asynchronous events to queue waiting for execution. So whenever we specify time for a timer we can be sure that it will not fire before the specified time. Generally the delays are unnoticeable by the end users.

Timeout

This type of timers are useful at places where we want to execute a block of code after a specified amount of time or at some timeout.

function setTimeoutSample() {

setTimeout(onTimeout, 2000);

}

function onTimeout() {

console.log("Timeout has occurred!!");

}

setTimeoutSample();

Recurring function call

This timer is useful when we want to call a function for multiple times at some specified interval. May be useful when we are performing some time based actions or animations.

var countInterval = 0;

function onTimeout() {

countInterval++;

console.log(countInterval + ". Interval has occurred!!");

}

function setIntervalSample() {

setInterval(onTimeout, 2000);

}

Clear Interval

This function clears the Interval timer and it will not execute any further.

var countIntervalClearable = 0;

function onTimeoutClearable() {

countIntervalClearable++;

console.log(countIntervalClearable + ". Interval has occurred!!");

if (countIntervalClearable >= 5) {

clearInterval(intervalId);

}

}

var intervalId = setInterval(onTimeoutClearable, 2000);

 

Instead of passing a global function we can also pass an anonymous function in the setInterval timer.

The code for this post can be found here.

Any questions, comments or feedback is most welcome.

Hi guys,

In this post we will walk through the Date object that is available in JavaScript and the various capabilities of that object and various ways can use it in our application

Date in JavaScript is powerful enough to suffice for most of the requirements we have in our applications. Interesting thing to note here is that numeric value of date is the number of milliseconds that have lapsed after 01Jan1970 UTC (all the leap time is ignored).

Another interesting thing that we can do with date in JavaScript is create a future date by adding days, hours, months, etc.

The various methods available on Date are:

getDate() Returns the day of the month (from 1-31)
getDay() Returns the day of the week (from 0-6)
getFullYear() Returns the year (four digits)
getHours() Returns the hour (from 0-23)
getMilliseconds() Returns the milliseconds (from 0-999)
getMinutes() Returns the minutes (from 0-59)
getMonth() Returns the month (from 0-11)
getSeconds() Returns the seconds (from 0-59)
getTime() Returns the number of milliseconds since midnight Jan 1, 1970
getTimezoneOffset() Returns the time difference between UTC time and local time, in minutes
getUTCDate() Returns the day of the month, according to universal time (from 1-31)
getUTCDay() Returns the day of the week, according to universal time (from 0-6)
getUTCFullYear() Returns the year, according to universal time (four digits)
getUTCHours() Returns the hour, according to universal time (from 0-23)
getUTCMilliseconds() Returns the milliseconds, according to universal time (from 0-999)
getUTCMinutes() Returns the minutes, according to universal time (from 0-59)
getUTCMonth() Returns the month, according to universal time (from 0-11)
getUTCSeconds() Returns the seconds, according to universal time (from 0-59)
getYear() Deprecated. Use the getFullYear() method instead
parse() Parses a date string and returns the number of milliseconds since midnight of January 1, 1970
setDate() Sets the day of the month of a date object
setFullYear() Sets the year (four digits) of a date object
setHours() Sets the hour of a date object
setMilliseconds() Sets the milliseconds of a date object
setMinutes() Set the minutes of a date object
setMonth() Sets the month of a date object
setSeconds() Sets the seconds of a date object
setTime() Sets a date and time by adding or subtracting a specified number of milliseconds to/from midnight January 1, 1970
setUTCDate() Sets the day of the month of a date object, according to universal time
setUTCFullYear() Sets the year of a date object, according to universal time (four digits)
setUTCHours() Sets the hour of a date object, according to universal time
setUTCMilliseconds() Sets the milliseconds of a date object, according to universal time
setUTCMinutes() Set the minutes of a date object, according to universal time
setUTCMonth() Sets the month of a date object, according to universal time
setUTCSeconds() Set the seconds of a date object, according to universal time
setYear() Deprecated. Use the setFullYear() method instead
toDateString( Converts the date portion of a Date object into a readable string
toGMTString() Deprecated. Use the toUTCString() method instead
toISOString() Returns the date as a string, using the ISO standard
toJSON() Returns the date as a string, formatted as a JSON date
toLocaleDateString() Returns the date portion of a Date object as a string, using locale conventions
toLocaleTimeString() Returns the time portion of a Date object as a string, using locale conventions
toLocaleString() Converts a Date object to a string, using locale conventions
toString() Converts a Date object to a string
toTimeString() Converts the time portion of a Date object to a string
toUTCString() Converts a Date object to a string, according to universal time
UTC() Returns the number of milliseconds in a date string since midnight of January 1, 1970, according to universal time
valueOf() Returns the primitive value of a Date object

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

Accessing the current date and parts of the date

We can create a Date object in Javascript that returns the current date time in current time zone. This happens when we do not pass any parameters while passing the Date object.

function getCurrentDate() {

var currentDate = new Date();

console.log(currentDate); // Mon Jul 29 2013 12:55:52 GMT-0500 (Central Daylight Time)

}

We pass different types of parameters to create the date we are looking for. We can pass

Number of milliseconds that have lapsed after 01 Jan 1970 00:00:00:000 UTC –> will return the date adding the lapsed milliseconds to base date of 01 Jan 1970 00:00:00:000 UTC.

dateFromMilliseconds = new Date(845351355547); // This will add milliseconds to base date 01 Jan 1970 00:00 UTC

console.log(dateFromMilliseconds); // Mon Oct 14 1996 22:49:15 GMT-0500 (Central Daylight Time)

String that is parseable into date –> will return the date that is parsed from the string.

var dateFromString = new Date('01Jan2000'); //string parse able into date

console.log(dateFromString); //Sat Jan 01 2000 00:00:00 GMT-0600 (Central Standard Time)

Year, Month, Day, Hours, Minutes, Seconds, Milliseconds –> A date will be created if we pass just the Year, Month and Day. The remaining parameters will be considered as 0.

var dateFromYMDHMSM = new Date(2000,5,26,6,6,6,6); //year, month, date, hour, min, sec, milliseconds

console.log(dateFromYMDHMSM); //Mon Jun 26 2000 06:06:06 GMT-0500 (Central Daylight Time)

We can use the methods that return the individual part of the date.

var currentYear = new Date().getFullYear();

console.log(currentYear); // 2013

var currentMonth = new Date().getMonth(); // Will return month from 0 (Jan) to 11 (Dec) so if it July it will return 6

console.log(currentMonth); // 6 // July

var todaysDate = new Date().getDate();

console.log(todaysDate); // 29

var currentDay = new Date(); //returns day as 0 (Sunday) to 6 (Saturday)

console.log(currentDay.getDay()); // 1 // Monday

Accessing dates in UTC timezone

We also have methods which return the UTC equivalent of the date. So whatever operations that we have done till now on the local date we can perform all of them to get the UTC time and date.

function getCurrentDateUTC() {

var currentDate = new Date(); // returns date in UTC timezone and has a , after the Day of week

console.log(currentDate.toUTCString()); // Mon, 29 Jul 2013 18:44:33 GMT

dateFromMilliseconds = new Date(845351355547); // This will add milliseconds to base date 01 Jan 1970 00:00 UTC

console.log(dateFromMilliseconds.toUTCString()); // Tue, 15 Oct 1996 03:49:15 GMT

var dateFromString = new Date('01Jan2000'); //string parse able into date

console.log(dateFromString.toUTCString()); //Sat, 01 Jan 2000 06:00:00 GMT

var dateFromYMDHMSM = new Date(2000, 5, 26, 6, 6, 6, 6); //year, month, date, hour, min, sec, milliseconds

console.log(dateFromYMDHMSM.toUTCString()); //Mon, 26 Jun 2000 11:06:06 GMT

var currentYear = new Date().getUTCFullYear();

console.log(currentYear); // 2013

var currentMonth = new Date().getUTCMonth(); // Will return month from 0 (Jan) to 11 (Dec) so if it July it will return 6

console.log(currentMonth); // 6 // July

var todaysDate = new Date().getUTCDate();

console.log(todaysDate); // 29

var currentDay = new Date(); //returns day as 0 (Sunday) to 6 (Saturday)

console.log(currentDay.getUTCDay()); // 1 // Monday

}

Get CurrentTime

It returns the number of milliseconds that have lapsed since 01 Jan 1970 00:00:00:000 UTC

function getCurrenttime() {

var currentTime = new Date().getTime(); //returns the milliseconds since 01 Jan 1970 00:00:00:000 UTC

console.log(currentTime); // 1375123786254

}

Converting Date To and From ISO 8601 format

Convert Date in ISO 8601 Format

There is a method (toISOString) available on the Date object. It returns the date in ISO format which looks something like below:

2013-07-29T18:56:20.370Z

This format separates the date and time by placing T in between them. Also if this string is in UTC timezone it is suffixed by Z and if it is not in the UTC timezone then it tells the time difference between the current timezone and UTC timezone by +hh:mm or –hh:mm.

function getDateInISOFormat() {

var dateInISO = new Date().toISOString();

console.log(dateInISO); // 2013-07-29T18:56:20.370Z

}

Convert ISO 8601 date into standard format accepted by Date method

If we are using older versions of the browser and we try to use the string date returned by the toISOString as a parameter to create a date then we will get an invalid date error. So before we pass this string to create a date we need to convert it into a format acceptable by the Date object. So could use the function below that will convert the ISO 8601 string into format acceptable by the date object.

function getDateFromISO_OldBrowsers() {

var isoDateString = '2013-07-29T18:56:20.370Z';

isoDateString = isoDateString.replace(/\D/g, " "); // replaces everything but numbers by spaces

isoDateString = isoDateString.replace(/\s+$/, ""); // trim white space

var datecompns = isoDateString.split(" "); // split on space

if (datecompns.length < 3) return "invalid date"; // not all ISO 8601 dates can convert, as is unless month and date specified, invalid

if (datecompns.length < 4) { // if time not provided, set to zero

datecompns[3] = 0;

datecompns[4] = 0;

datecompns[5] = 0;

}

datecompns[1]--; // modify month between 1 based ISO 8601 and zero based Date

var convdt = new

Date(Date.UTC(datecompns[0], datecompns[1], datecompns[2], datecompns[3], datecompns[4], datecompns[5]));

console.log(convdt);

}

However if we are running the latest browsers we could simply pass the ISO 8601 formatted string as a parameter to the date object and we will get the localized date.

function getLocalDateFromISO() {

var localDate = new Date('2013-07-29T18:56:20.370Z');

console.log(localDate);

}

Create future date

We can do that by either passing the individual parts of the date or use the set method available to set the values of the individual parts of the date.

function createFutureDate() {

var futureDate = new Date(2050, 01, 01);

console.log(futureDate); // Tue Feb 01 2050 00:00:00 GMT-0600 (Central Standard Time)

futureDate = new Date();

futureDate.setMonth(11);

futureDate.setFullYear(2075);

console.log(futureDate); //Sun Dec 29 2075 14:39:57 GMT-0600 (Central Standard Time)

}

Find time elapsed

There are times when we need to know how long a function takes to execute. So do that all we need to do is create a Date object before we call the function and then we create another object when the control returns back from the function and then we subtract both the times.

function trackFunctionExecTime() {

var firstDate = new Date();

var sum = doCalculation();

var lastDate = new Date();

console.log("Time elapsed in calculating sum of numbers from 1 to 1000000000 is " + (lastDate - firstDate) / 1000 + " sec and sum is " + sum);

//Time elapsed in calculating sum of numbers from 1 to 1000000000 is 1.235 sec and sum is 500000000067109000

}

function doCalculation() {

var j = 0;

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

j = j + i;

}

return j;

}

When we apply mathematical operations on date apart from subtraction we get different results.

Date + Date = string concatenation of date

Date – Date = Difference of milliseconds equivalent of date

Date / Date = Division of milliseconds equivalent of the date

Date * Date = Multiplication of milliseconds equivalent of date

The code for this post is available here.

Any comments, feedback or questions are most welcome!!

Hi guys,

 

I am currently reviewing Instant Dependency Management with RequireJS How-to by Greg Franko (PACKT Publishing).

Instant Dependency Management with RequireJS How-to

Instant Dependency Management with RequireJS How-to

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

I will be adding my finding and comments in this post soon.

Hi,

Below is the list of Apps delivered by me to the clients.

  • TruthOrDare

    Play the fun game of Truth or dare with friends and family! Perfect fun for Saturday game night that will get everyone in on the action and hilariousness.

    Fun challenging dares and interesting truths. Learn more about your friends and other players than you ever thought you knew! Great for an icebreaker game or just for having fun.            

Truth or Dare

Truth or Dare

Truth or Dare

Truth or Dare

Truth or Dare

Truth or Dare

Truth or Dare

Truth or Dare

 

 

 

 

 

 

 

 

 

App Store Link for the App –> http://www.windowsphone.com/en-gb/store/app/truthordare/4737969c-57f5-4398-acf5-b7b8fce0138e

  • ZenProverbs

     A Wise Man Once Said: Gain Wisdom from the masters with this collection of zen proverbs. Use them in your daily meditations to achieve enlightenment. Download these proverbs and enhance your  

     spiritual quest today!

Zen Proverbs

Zen Proverbs

 

 

 

 

 

 

 

 

 

 

 

Zen Proverbs

Zen Proverbs

 

 

 

 

 

 

 

 

 

 

 

Zen Proverbs

Zen Proverbs

 

 

 

 

 

 

 

 

 

App Store Link for the App –> http://www.windowsphone.com/en-gb/store/app/zenproverbs/a421aaea-c469-4350-8aa6-cc884222f491

I will keep this post updating regularly with the apps that are published in app store.