Dates

JavaScript Date constructor helps in managing, displaying and parsing the data. The date API uses the term UTC ( Coordinated Universal Time) and it is the synonym of GMT ( Greenwich Mean Time) i.e, nearly to the time zone of London, UK.

The Date Constructor :

Date Constructor is can be invoked as follows :

new Date(year, month, date, hours, minutes, seconds, milliseconds);

This constructs a new Date from the given date. The parameters should have the ranges up to :

  • year : 0 <= year <= 99 (1900 is also added).
  • month : 0 to 11 (0 - January)
  • date  : 1-31
  • hours : 0-23
  • minutes : 0-59
  • seconds : 0-59
  • milliseconds : 0-999
Example :

new Date(2017,4,3,12,59,59,59);
Wed May 03 2017 12:59:59 GMT+0530

JavaScript has inherited the convention of interpreting 0-January,1-february and so on from Java.

new Date(dateStr) :

It parses a string with the date time string and then returns a time value.

For Example :
new Date('2017-04-03');
Mon Apr 03 2017 05:30:00 GMT+0530

If the date sent is illegal then NaN will be passed to the new Date(number).

new Date(timeValue)

This creates a date by passing the number of milliseconds as parameter and it is been identified from the year 1970 January 1st.

new Date(0)
Thu Jan 01 1970 05:30:00 GMT+0530

We can even get the inverse() of this constructor using the getTime() method, which will return back in milliseconds.

new Date(12345).getTime();
12345

NaN can also be used as an argument and it returns a special instance of Date i.e, an "invalid date".
var dat = new Date();
dat.getTime();
NaN
dat.getYear();
NaN
dat.toString()
Invalid Date
dat.toJSON()
null

new Date()

It creates a new date and time, it works same as new Date(Date.now()).

Constructor Methods For Date :
  • Date.now() : This returns the current date and time in milliseconds from 1st January 1970 00:00:00 UTC and it returns same result as new Date().getTime().
  • Date.parse(dateString) : This converts the dateString into milliseconds from 1st January 1970 00:00:00 UTC. 
       For Example :

        Date.parse('2017-04-03');
        1491177600000
        Date.parse('1970-01-01');
        0
If it can't able to parse the string, then it returns NaN.

Date.parse('abcd');
NaN

Date.UTC(year,month,date,hours,minutes,seconds,milliseconds) :
This doesn't return the date format, it converts the given date into the milliseconds from 1st January 1970 00:00:00 UTC.

For Example :

Date.UTC(2017,4,3,12,59,59,59);
1493816399059

Date Prototype Methods :

Getters and Setters Method for time units :

  • Local time :
            Date.prototype.get<>()returns Unit, according to the local time.
            Date.prototype.set<>(number) : This will set the Unit, according to the local time.
  • Universal time :
            Date.prototype.getUTC<>()returns Unit, according to the universal time.
            Date.prototype.setUTC<>() : This will set the Unit, according to the universal time.

Unit can be :
  • Full Year : four digit
  • Month : 0-11
  • Date : 0-31
  • Day (only getter) : 0-6 (0 is Sunday)
  • Hours : 0-23
  • Minutes : 0-59
  • Seconds : 0-59
  • Milliseconds : 0-999
For Example :

var dat = new Date('2017-04-15');
dat
Sat Apr 15 2017 05:30:00 GMT+0530
dat.getDate()
15

dat.getDay()
6

Getter and Setter Methods :

The following methods will get and set the time in milliseconds from 1st January 1970.

  • Date.prototye.getTime() : It returns the milliseconds from 1st January 1970 00:00:00 UTC.
  • Date.prototye.setTime(ms) : It sets the date as specified in milliseconds from 1st January 1970 00:00:00 UTC.
  • Date.prototye.valueOf() : This is same as the getTime() and this is called when getTime() is converted to number.
  • Date.prototye.getTimezoneOffset() : This returns the difference between local time and UTC time in minutes.
  • Date.prototye.getYear() :  This  method is been deprecated, instead of this we use getFullYear().
  • Date.prototye.setYear() : This method is also been deprecated, instead of this we use setFullYear().
Converting Date to a String :

Time in human-readable format :

  • toTimeString() :
             var a = new Date();
             a.toTimeString();
            "11:41:28 GMT+0530 (India Standard Time)"
  • toLocaleTimeString() : 
             a.toLocaleTimeString();
             "11:41:28"

Date in human-readable format :
  • toDateString() :
            a.toDateString();
            "Thu Dec 28 2017"
  • toLocaleDateString() :

            a.toLocaleDateString()
            "28/12/2017"

Date and Time in human readable format :
  • toString() :
            a.toString()
            "Thu Dec 28 2017 11:41:28 GMT+0530 (India Standard Time)"
  • toUTCString() :
           a.toUTCString()
           "Thu, 28 Dec 2017 06:11:28 GMT"

These all methods are been provided by the ECMAScript Internalisation API.

Date and Time in machine readable format :
  • toISOString() :
             a.toISOString()
             2017-12-28T06:11:28.552Z


Date Formats (no-time):

There date formats are:

YYYY-MM-DD
YYYY-MM
YYYY

YYYY-year, MM-month, DD-date

Time Formats (no-date) :

THH : mm:ss.sss
THH : mm:ss.sssZ

THH : mm:ss
THH : mm:ssZ

THH : mm
THH : mmZ


  • T is the prefix of the time part of a format.
  • HH is hours starts from 0-23 and 24 can also be given and it is hour 00 of the following day.
  • mm is minutes 0-59
  • ss is seconds 0-59
  • sss is milliseconds 0-999
  • z refers to the time zone i.e, Z for UTC and + or - will be followed by hh:mm
Arithmetic operations can also be done but leap seconds are ignored.

Example :


new Date('2017-04-13') - new Date('2017-04-03');
864000000





Occurrences of undefined and null

The following examples defined the Occurrences of undefined and null.

Occurrences of undefined :

If the variables are not initialized, then it is undefined.
var foo;
foo
undefined

Missing parameters are undefined.

function f(x) { alert(9); }
f()
undefined

If a property doesn't exist, then it returns undefined.

var a = {};
a.foo;
undefined

If a function doesn't has anything to return explicitly, then it returns undefined

function a() { }
a()
undefined

function b(){ return; }
b()
undefined

Occurrences of null :

1. null is the last element in the prototype chain.
      Object.getPrototypeOf(Object.prototype);
      null
2. null is returned even if the regular expression doesn't matches for the given regular expression in the string.

>/x/.exec('aaa')
null

To check whether the result is null or undefined...

if(a == null)....

if(a == undefined)...

Few Examples :

Number(null);
0

5 + null
5

Number(undefined)
undefined

5 + undefined
undefined

if( x == void 0 ) // Here, void 0 means, which is always undefined i.e, it is equivalent to if(x == undefined)




JavaScript Types

The JavaScript types are only six according to ECMA language specification. They are :

  • undefined, null
  • Boolean
  • Number
  • String
  • Object
And the Constructors don't introduce any new types.


Static VS Dynamic

Static means "at compile time" and dynamic means "at runtime".

Static Typing VS Dynamic Typing

In a static typed language, variables, parameters and members of the objects have types that the compiler knows at compile time.

Even in static type language, the variable also has dynamic type language. The dynamic type can differ from static type. For Ex :

Object a = 'hello';

The static type of a is Object and it's dynamic type is String. JavaScript is dynamically typed, types of variables are generally not known at compile time.

Automatic Semicolon Insertion (ASI)

The main target of this semicolon insertion is to make semicolon optional at the end of the line. It is invoked by the JavaScript to insert semicolon at the end of the line for you and internally the things are handled differently.

ASI parser identifies when the statement ends. Basically, the line ends by semicolon and it also identifies that the statement also ends based on these conditions :

1. A line terminator followed by illegal token.
2. If a closing brace is encountered.
3. If the end of file is reached.

ASI vs illegal token

The following code has an illegal token.

if( i < 1 ) i = 5
console.log(i)

Here, this comes under the section of illegal statement and it triggers ASI, then it adds the semicolonn at the end of the line as shown below :

if( i < 1 ) i = 5;
console.log(i);

ASI vs Closing brace

In the following code, the statement inside the braces is not ended with the semi colon.

function mul(a,b){ return a*b }

Now, the ASI is triggered and it creates a correct version of the preceding code :

function mul(a,b){ return a*b; }





Empty Statement

An Empty statement is a semi-colon and it does nothing. It can be appeared anywhere a statement is been expected. These can be used where the statement is not needed but just demanded. In these cases, blocks are also allowed.

Example :

while(i > 0);
while(i > 0){}

Both the two statements are same.


Primitive Value Vs Objects

The primitive values are booleans, numbers, string, null and undefined. All other values are objects.
The major difference is their comparison and each object has the unique identity.

var obj1 = {};
var obj2 = {};

obj1 === obj2
false
obj1 == obj1
true

All the primitive values which has same value are considered as same value.

var val1 = '123';
var val2 = '123';

val1 === val2
true

Characteristics of Primitive values:

These are compared by the given content i.e;

5 === 5
true

'hello' ==  'hello'
true

These are always immutable.

Properties cannot be added, changed or removed.

var str = 'hello';
str.length = 2;
console.log(ex.length);
5
If we try to change the value of the length, it doesn't get effected.

str.abc = 3;
console.log(str.abc);
undefined

Here, we are trying to create a property of 'abc', but there will not be any effect. Reading an unknown property always returns undefined.

Objects :

All non-primitive values are referred as objects. The common ways of objects are:

1. Plain Objects :
{
    "firstName" : "Josh",
     "lastName" : "John"
}

2. Arrays :
Arrays are been created as Array Literals.

[ "one", "two", "three"]

3. Regular Literals :
These are created by regular expression literals.

Comparing the reference :

Identities are compared, each and every value has it own identity.

{} == {}  // two different empty objects
false

var obj1= {};
var obj2 = obj1;
obj1 == obj2;
true

Mutable by default :

We can add, remove, change or update properties.

var obj1 = {};
obj1.num = 11;
console.log(obj1.num);
11

undefined and null

These two are known as "nonvalues".

undefined values means "no value". The values which are not initialized are undefined.
var num = {};
num
undefined

Missing Parameters are also undefined.

function num(x) { return x; }
num();
undefined

If the property doesn't exist, then the result is undefined.

var num = {};
num.abc;
undefined

null means "no value".

Different ways to empty an array

var arrayList = ['b','l','o','g','g','e','r'];

Method 1 :

arrayList = [];

This can be recommended only if you don't have references of the original array anywhere else. If the array is referenced to another variable and the original will remain unchanged.

var arrayList = ['b','l','o','g','g','e','r'];
var copy = arrayList;
arrayList = []; //empty array
console.log(copy); //  ['b','l','o','g','g','e','r']

Method 2:

var arrayList = ['b','l','o','g','g','e','r'];
var copy = arrayList;
arrayList.length = 0; 
console.log(arrayList); //empty array
console.log(copy);//empty array

output : 
[ ]

This way of emptying the array also updates the reference variables that points to the original variable.

Method 3:

var arrayList = ['b','l','o','g','g','e','r'];
var copy = arrayList;
arrayList.splice(0,arrayList.length);
console.log(arrayList); 
console.log(copy);

By using this method is also perfect one, as it updates value to the reference variable.

output :

[ ]
[ ]

Method 4 :

var arrayList = ['b','l','o','g','g','e','r'];
var copy = arrayList;
 while(arrayList.length){
  arrayList.pop();
console.log(arrayList); // [ ]
console.log(copy); // [ ]

Even this empty arrays but this is not been recommended much.

Examples with typeof :

var y = 1;
  if (function f(){}) {
    y += typeof f;
  }
  console.log(y);

In the above example, the output is 1undefined as the if statement code executes at runtime, and the statement inside the if condition is evaluated during run time.

var k = 1;
  if (1) {
    eval(function foo(){});
    k += typeof foo;
  }
  console.log(k);

output : 1undefined

The if condition evaluates this statement using eval and the eval(function foo(){}) returns true. But as the statement executes at runtime the output will be 1undefined.

var k = 1;
  if (1) {
    function foo(){};
    k += typeof foo;
  }
  console.log(k);

Here, the typeof returns function and the output is :

1function

Pre-increment and Post-increment

The pre-increment and post-increment results the same but the only difference is the result of evaluating the expression.

++i  : increments i and evaluates the new value of i.

i++ : evaluates the old value of i and then increments i.

for(var i=0;i<=10;i++){
console.log(i);
}

for(var i=0;i<=10;++i){
console.log(i);
}

Result for both for loops : 
0
1
2
3
4
5
6
7
8
9
10

Comparing Objects

In JavaScript objects are a reference type. Two distinct objects are never equal, even if they contain same properties. If the same object reference is compared, then it returns true.

For Example :

var veggies = { name : 'potato' };
var vegetable = { name : 'potato' };

Two variables and the two distinct objects with same properties :

veggies == vegetable // returns false;
veggies === vegetable // returns false;

Two variables and a single object :

var veggies = { name : 'potato' };
var vegetable = veggies ;

As the veggies and vegetable are pointing to the same object, it returns true.

veggies == vegetable // returns true;
veggies === vegetable // returns true;

If the name gets updated, then the changes are reflected in the reference object also.

veggies.name = 'carrot';
console.log(vegetable); // returns { name : 'carrot' }




Deleting Properties

A non-inherited property can be removed by using the delete operator.

For Example :

Create a new object, named myObject with two properties :

var myObject = new Object();
myObject.a = 7;
myObject.b = 8;

delete myObject.a;
console.log('a' in myObject) // false (As the object is deleted)

we can also delete a global variable if var keyword is not used to declare a variable.

a = 15;
delete a;

Getters and Setters

A getter is a method that gets the value of a specific property and setter is a method that sets the value of a specific property. The getters and setters method can be defined on any predefined core objects or the user defined objects that supports the addition of new properties.

Example :

var obj = {
a : 7,
     get b(){
          return this.a * 2;
      },
     set c(x){
          this.a =  x/ 5;
      }
};

console.log(obj.a); // 7
console.log(obj.b); // 14
obj.c = 100;
console.log(obj.a); // 20

The obj object properties are :

obj.a ==> a number

obj.b ==> a number multiplied with 2.

obj.a ==> a number sets the value of obj.c/5;

The getters and setters can extend the Date property to add a year property to all the instances of the predefined Date class. It uses getFullYear and setFullYear methods to support the year property's getter and setter.

var a = Date.prototype;
Object.defineProperty(a, 'year', {
  get: function() { return this.getFullYear(); },
  set: function(y) { this.setFullYear(y); }
});

var today= new Date();
console.log(today.year); //2017
today.year = 2001;
console.log(today); //Mon Dec 03 2001 20:45:11 GMT+0530 (India Standard Time)

The getters and setters can be defined in two ways :

  • It can be defined using object initializer.
  • It can be added later to any object at any time using getter or setter method.
when getter and setter methods are defined using object initiallizer, we just need to do is, add a prefix i.e, for getter method with get and setter method with set. The getter method must not take any parameters and setter methods exactly one parameters.

var obj = {
a:7;
get b(){}
set c(x){}
};

Getters and Setters can also be added to an object at any time using the Object.defineProperties method. 

Example :

var obj = { a : 7 };


Object.defineProperties(obj, {
    'b': { get: function() { return this.a + 1; } },
    'c': { set: function(x) { this.a = x / 2; } }
});

obj.c = 10;
console.log(obj.a); // 5
console.log(obj.b); // 6






Difference between object literal notation and JSON

The Object literal notation is not as same as JavaScript Object Notation(JSON).


  • JSON property is defined as "property" : "value". The property cannot be short handed and it must be double quoted.
  • In JSON the values can be only strings,numbers,array,true,false,null or another JSON object.
  • A function can not be assigned to a value in JSON.
  • Objects like date can be a string after JSON.parse().
  • JSON.parse() will not accept computed property names and error will be thrown. 

Object Initializer

JavaScript has number of predefined objects and can also create our own objects. object cane be created using object initializer.

Object Initializer :

Objects can be initialized using new Object(), Object.create() or using initializer notation. It is a comma delimited list of zero or more pairs of property names and associated values of an object, which are be defined in curly braces ({}).

syntax :

var data = {};

var data = {a:'hello',b:42,c:{}};

var a = 'hello', b = 42, c = {};
var data = {a:a,b:b,c:c};

var newData = {
         property: function ([parameters]) {},
         get property() {},
         set property(value) {}
};

where as In ECMAScript 2015, these notations are defined as :

var a = 'hello', b = 42, c = {};
var data = {a,b,c};

var a = {
      property([parameters]){}
};

var prop = 'zoo';

var a = {
     [prop]: 'hello',
     ['b' + 'ut']: 'here'
};

values of the object properties can contain primitive datatypes or other objects.

Creating objects :

An empty object with no properties can be created as :

var emptyObject = {};

The main advantage of this notation intializer is we can create objects quickly with its properties inside curly braces. You can simply notate a key : value pairs which are been separated by comma.

Example :

var details = {
name : 'ram',
age : 20,
college:'srichaitanya'
}

Accessing Properties :

Once the object is defined we might want to retrieve them or change them. Object properties can be accessed using dot notation or bracket notation.

details.name; //ram
details['age'] //20

details.name = 'tommy';

Duplicate property name :

when the same name is used for the property, then the second property is overwritten by the first value.

Example :

var z = {x:1,x:2};

console.log(z); //  x : 2

In ECMAScript 5, if duplicate elements are defined then it would be considered as syntax error.In ECMAScript 2015 has removed this restriction. By using strict mode, it would allow the duplicate property names.

Method Definitions :

A property of an object can refer to a function or getter or setter method.

var example = {
property : function([params]){}
get property() {},
set property(val) {}
};

Spread Properties :

It copies own enumerable properties from a provided object into a new object.

Example :

var obj1 = { foo: 'bar', x: 42 };

var obj = { ...obj1 };

console.log(obj);
// { foo: 'bar', x: 42 }

Overview of AngularJS

AngularJS is an open source web application framework. It is now maintained by Google . The most of the code can be eliminated by using th...