ES6 Array Methods

1. concat() :

concat() method joins two or more methods.

Syntax :

array.concat(val1,val2...valn);

It returns a new array.

Example :

var firstArray = [ 'aa','bb','cc'];
var secondArray = [ 1,2,3 ];
var thirdArray = firstArray.concat(secondArray);
console.log(thirdArray);
output:
['aa','bb','cc',1,2,3];

2.every() :

every() method tests whether all the elements in the array satisfies the condition which is been implemented by the function.

Syntax :

array.every(callback[,thisObject]);

It returns true if every element satisfies the condition.

Example :

function test(element){
return (element > 0 )
}

var check = [1,2,3,4,0].every(test);
console.log(check);

output :
false

3. filter() :

filter() method creates a new array with all the elements which will pass the test.

Syntax :

array.filter(callback[,thisObject]);

It returns the created array.

Example :

function test(element){
return (element > 0 )
}

var check = [1,2,3,4,0].filter(test);
console.log(check);

output :
[1,2,3,4]

4. forEach() :

forEach() method calls a function for each element in the array.

Syntax :

array.forEach(callback[,thisObject]);

It returns the created array.

Example :

var a= new Array(1,2,3,4)
a.forEach(function(val,index){
console.log(val)
})

output :
1
2
3
4

5. indexOf()

indexOf() method returns the first index of the element from the array if it is not present then it returns -1.

Syntax :

array.indexOf(searchelement[,fromIndex]);

Example :
var getIndex = [111, 222, 333, 444 ].indexOf(222);
console.log(getIndex );
output :
1

6. join()

join() method joins all the elements of an array into a string.

Syntax :

array.join(separator);

separator: It specifies a string to separate the each element of the array and if separator is not passed, then the array elements are separated by comma.

It returns the string after joining all the elements in the array.

Example :

var getIndex = [111, 222, 333, 444 ];

var newArr = getIndex.join();
console.log(newArr); 
output :
"111,222,333,444"

var newArr1 = getIndex.join(" - ");
console.log(newArr1); 
output :
"111 - 222 - 333 - 444"

7. lastIndexOf() :

lastIndexOf() method returns the last index of the given element from the array and if the element is not present then it returns -1.The array is searched from backwards.

Syntax :

array.lastIndexOf(searchIndex[,fromIndex]);

Example :

var getLastIndex = [12, 5, 8, 130, 44,45,8,65,99].lastIndexOf(8); 
console.log("index is : " + getLastIndex );   
output :
index is : 6

8. map() :

map() method creates a new array with the given result by calling the function for each and every element.

Syntax :

array.map(callback[,thisObject]);

Example :

var nos = [9,16,25,36,49];
var rootsOfNumbers = nos.map(Math.sqrt);
console.log(rootsOfNumbers );
output :
[3, 4, 5, 6, 7]

9. pop() :

pop() method removes the last element from the array and returns that element.

Syntax :

array.pop();

Example :

var nos = [9,16,25,36,49]; 
var removedElement = nos.pop();
console.log(removedElement );
output : 49
console.log(nos);
[9,16,25,36]

10. push() :

push() method adds the element at the end of the array.

Syntax :

array.push(ele1,ele2,...,elen);

Example :
var nos = [9,16,25,36,49]; 
nos.push(64);
console.log(nos);
output :
[9, 16, 25, 36, 49, 64]

11. reduce() :

reduce() method applies a callback function for the values of the array and reduces it to one from left to right.

Syntax :

array.reduce(callback[,initialValue);

Example :

var sub = [99, 20, 12, 5].reduce(function(a, b){ return a - b; }); 
console.log("number : " + sub );    
output : 
number : 62

12. reduceRight() :

reduceRight() method applies a callback function for the values of the array and reduces it to one from right to left.

Syntax :

array.reduceRight(callback[, initialValue]);    

Example :

var sub = [99, 20, 12, 5].reduceRight(function(a, b){ return a - b; }); 
console.log("number : " + sub );
output : 
number : -126

13. reverse() :

The reverse() method will reverse the element i.e, the last becomes first and first will be last.

Syntax :

array.reverse();

Example :

var a = ["name", "age" , "job" ].reverse();
console.log(a);
output :
["job", "age", "name"]

14. shift() :

shift() method removes the first element from the array.

Syntax :

array.shift();

Example :

var a = ["name", "age" , "job" ];
a.shift();
console.log(a);
output :
["age", "job"]

15. unshift() :

unshift() method adds the one or more elements at the beginning of the array.

Syntax :

array.unshift(ele1,...,eleN);

Example :

var arr = new Array("apple", "banana" , "kiwi");
arr.unshift("watermelon");
console.log(arr);
output:
["watermelon", "apple", "banana", "kiwi"]

16. slice() :

slice() method get the specific element from the array.

Syntax :

array.slice(begin[,end]);

Example :

var arr = new Array("apple", "banana" , "kiwi");
arr.slice(1,2);
output :
["banana"]







JavaScript Page Redirect

Page redirection is way to redirect from one webpage to another webpage. The redirected page can be on the same website or on a different website or web server.

window.location and window.location.href

In JavaScript, we can use many methods to redirect a webpage to another webpage. window.location is a object. It is used to get the current URL address and to redirect the browser to the new page. This property is of window object. The behaviour is same for both window.location and window.location.href.

Example : 

function redirectPage(){
       window.location = "http://www.google.com";
}
 redirectPage();

The page is redirected to google.

location.replace() :

The most frequently used is replace() method in window.location object, replace() method will replace the current document with new url and performs HTTP redirect.

Syntax :

window.location.replace("http://www.kfc.com");

location.assign() :

This method loads a new document in the browser window.

Syntax :

window.location.assign("http://www.kfc.com");

Difference between location.assign() and location.replace() :

location.replace() method deletes the current url from the document history. So, we cannot go back to the original document where as the location.replace() method loads a new document in the browser. To avoid this situation, we need to use location.assign() method.

location.reload() :

The location.reload() method reloads the current document in the browser.

Syntax :

window.location.reload("http://shruthikatkoori.blogspot.com");

window.navigate() :

This is almost similar to window.location.href property i.e, assigning a new value. This is only available in MS Internet Explorer so better to avoid this in cross-browser development.

Syntax :

window.navigate("http://www.abc.com");

Redirection and Search Engine Optimisation :

If you want to notify the url forwarding to the SEO then need to add rel = "canonical" meta tag to your website head part because the search engines don't identify the JavaScript redirection.



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.


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...