Functions

Functions are set of statements that perform a task. The Function keyword can be used to define a function inside the expression. These can be defined in two ways i.e. function constructor or function expression.

Function Expression :

Functions can be created by function expression. These functions are known as anonymous function i.e. it doesn't have any change.

Syntax :

var myFunc = function [name]([param1[,param2[,...,paramN]]]){
//statements
}

Parameters :

name : name is the function name and this is not mandatory. So, it can be omitted, in this case it will be an anonymous function.

params : params are the name of the argument which are been passed to the function.

statements : The statements will be body of the function.

Examples :

var a = function(a) {
        console.log(a);
}
a(1);

output :

1

Function Expression are convenient when passing a function as an argument to another function.

Example :

function firstFunc(anotherfunc){
anotherfunc();
}
function secondFunc(){
console.log("secondFunc() is passed as an argument to the firstFunc()");
}
firstFunc(secondFunc);

output :

secondFunc() is passed as an argument to the firstFunc()

Function Declaration :

Function declaration is also known as function definition or function statement.
A Function which is been created with a function declaration will be a function object and it has all the properties, methods, behavior of function objects. By default the return type of function is undefined and to return any value the function must have a return statement that will specify the value to be returned.

It consists of :
  • name of the function.
  • list of parameters that is been passed inside the parenthesis separated by comma.
  • body which is been enclosed in the curly braces {}.
Example :

function a(){
console.log("hi");
}
a();
output :
hi

If the object is passed as a parameter and the function changes it's object properties then change is effected even outside the function.

Example :

function first(a){
          a.name = "john";
}
var details = { name:'joy', gender:'female' };
var x,y;
console.log(details.name);
first(details);
console.log(details.name);

output :

joy
john

The main difference between function expression and function statement :
  • function statement is the function name which can be omitted in the function expression which will be defined as anonymous function.
  • This function Expression can be used as Immediately Invoked Function Expression. As, it can run as soon as it is been defined.
  • Function Expression are not hoisted as Function declaration.
Example :
 
b(1);
var b = function(a) {
        console.log(a);
}

It throws an error by saying that prototype of undefined.

Named Function Expression :

To refer a current function inside the function we create a named function expression. This name is accessible only to the function body scope and this also avoids non-standard property.

Anonymous function Example :

var a = function(b){
console.log(b + b);
a(5);
output :
10

Naming Conflict :

When two variables or arguments have the same name then it would be a name conflict. Inner scope will have the highest precedence and the outer scope will have the least precedence. This is scope chain.

Example :

function outer(){
    var x = 10;
    function inner(x){
          return x * 10;
     }
     return inner;
}
outer()(20);

output :

200

Here, the name conflict is the variable x. So, the inner x will take the scope the outer x and the output will be 200 instead of 100.
 

HTML BLOCK AND INLINE ELEMENTS

Block-level Elements :

A Block level Element always starts with a new line and it takes up the full width.

Block level Elements in HTML are :

address :

This tag defines the contact information for the owner/author of a document or an article. If this tag is defined inside the body element then the contact information is for  the document. If this tag is defined inside the article element then the contact information will be for the article . The text is rendered in italic for the address element.

article :

This tag specifies independent, self-contained elements. An article should make sense on its own and it has to be relevant with the data.

Example :

Facebook :
       Facebook is an American online social media and social networking service company based                 in Menlo Park, California. The Facebook website was launched on February 4, 2004, by Mark               Zuckerberg.

div :

This tag defines a division or a section in a HTML document. It is used to group elements to format them with CSS.
<div style="color:red">
  <h3>This is a heading</h3>
  <p>This is a paragraph.</p>
</div>

dd,dt,dl:

dd is used to describe the term/name in a description list.
dt is used to define the term/name in a description list.
dl will define the description list.

Example :

Fruits

Apple 
Banana
Mango

footer :

This tag defines a footer for the document or for a section and the information must be related to it's contact information.

The footer element may contain information about :

1. author information.
2. contact information.
3. related documents
4. to revert to top of the page and so on.

form :

This tag is used to create HTML form to accept user inputs. The form tag contains following elements. They are :

input: This allows user to enter the data and it can be in many ways. It depends on the type attribute.

textarea :  This tag defines a multi-line text holder. This can hold unlimited number of character. This textarea can be specified by the cols and rows attribute.



label : This tag defines a label for a input element

button : This defines a clickable button and the button element can also contain content like text or images.

select: The selection element is used to create a drop down list.

option : The option element is defined inside the selected element to show the available options list.

fieldset : To group a related elements in a group we use fieldset element and this tag draws a box around the related elements.

optgroup : This element is used to group the related options in the drop down list.

h1 to h6 : These tags are used for HTML Headings. h1 is the most important heading and h6 will be least important heading.

Heading1

Heading2

Heading3

Heading4

Heading5
Heading6
header : This tag is used to introduce the content and this may contain any of these heading elements i.e, h1 to h6 and may contain any icon or logo.

ol :This tag defines an ordered list and this can be numerical or alphabetical.
li : li is the list item. It is uses in ol and ul i.e. ordered list and unordered list.
nav : This tag is used to navigate the links.

noscript:  This tag is used to disable scripts in your browser. This tag can be used with in the body and head element. sometimes content will be displayed is it is not supported.

p : This defines paragraph. And the browser will automatically adds some space before and after the p tag and margins can be modified with styles.

section : The section tag defines a section in a document. such as headers,footers,chapters or it can be any other sections.

video : This tag defines a video or a video stream or it can be movie clip.

The mime types which are been supported are :

video/mp4
video/webm
video/ogg

main : This tag specifies the main content in the document. The content inside the main element must be unique such as navigation links, logos etc.

INLINE ELEMENTS :

Inline Elements doesn't start on a newline and it takes only as much as width it needed.

The Inline Elements are :

span : This tag is used as a container for some text and it is used group inline elements in a document.

a : This tag is for hyperlink, used to link from one page to another and most important attribute is href i.e. to indicate it's destination.

Google

b : This tag specifies bold text.
bold text

br : This is break tag which will insert a single break line and it doesn't have any closing tag.
Hello,
this is my blog

i : This tag will display the text in italic.
italic

script : script element is used to define client-side scripting. It may contain scripting statements or external source files through the source attribute.

strong : This tag defines an important .

Important

sub : subscript text.

Hello blog

sup : superscript text.

24

img : Image tag define an image in the HTML page. This has two attributes i.e. src and alt.
src is the image path to retrieve and set it on the HTML page and text is been given in alt parameter when the image is not able to loaded then this particular text will be displayed.


ES2015 OR ES6 Sets

Set Objects are collection of values where the values can be iterated through insertion order and it doesn't accept duplicate values i.e. it contains only unique values of any type i.e. primitive type or object references.

Syntax :

new Set([iterable]);

iterable parameter will add all the elements into the new Set. If the parameter is not set or the value is null then it returns a new empty Set.

NaN and undefined can also be stored in the set.

Properties :

Set.length  : By default the length is 0 and it returns the length of the set object.

Set.prototype : It allows the addition of properties to all the Set Objects and it represents the prototype of the set constructor.

Set instances :

All the Set instances are been inherited from Set.prototype.

Properties :

Set.prototype.size : 

It returns the length of the Set Object.

Set.prototype.constructor : 

It returns a function that is been created as the instance prototype and  this will be Set function by default.

Methods :

Set.prototype.add(val) : 

It will append the new element to the Set Object and then returns the Set Object.

Set.prototype.clear() : 

It removes all the elements from the Set Object.

Set.prototype.delete(val) : 

It removes the specific element from the Set Object and through has() method we can check whether the element exits or not it returns in boolean format i.e. true if the element exits else it returns false.

Set.prototype.has(value) : 

It returns boolean value i.e. if the element is present in the given set object then it returns true else it returns false.

Set.prototype.entries() : 

It returns a new Iterator object that returns an array [value,value] for each element in the set object in the insertion order.

Set.prototype.forEach(callbackfunction[,thisArg]) :  

The callback function will call for each and every value present in the Set Object in the insertion order and thisArg is been passed to the forEach, it is used as a this value for every calback.

Set.prototype.keys() :

It is same as values() method. It returns a new Iterator object that has values of each element in the Set Object in the insertion order.

Set.prototype.values() :

It returns a new Iterator object that has values of each element in the Set Object in the insertion order.

Example for the above methods :

var myNewSet = new Set();
myNewSet.add(1); // [1]
myNewSet.add(2);  // [1,2]
myNewSet.add(2); // [1,2]
myNewSet.add('text'); // [1,2,text]

myNewSet.size; //3

myNewSet.has(Math.sqrt(1)); //true

myNewSet.add(10); // [1,2,text,10]

myNewSet.has(Math.sqrt(100)); //true

var emp = { name : "sita",age : "20" };

myNewSet.add(emp);

myNewSet.has(1); // true

myNewSet.has('text'); //true

myNewSet.delete(2); // removes 2 from the set

myNewSet.has(2); //false

myNewSet.size; // 4

Iterating Sets :

for(let item of myNewSet) { console.log(item) } 

output :

1
text
10
{name: "sita", age: "20"}

for(let item of myNewSet.keys()) { console.log(item) } 

1
text
10
{name: "sita", age: "20"}

for(let item of myNewSet.values()) { console.log(item) } 
1
text
10
{name: "sita", age: "20"}

for(let item of myNewSet.entries()) { console.log(item) } 
[1, 1]
["text", "text"]
[10, 10]
[{name:"sita",age:"20"}]

var myArr = Array.from(myNewSet);
console.log(myArr);
output :

[1,"text",10, { name:"sita",age : "20" } ]

myNewSet.forEach(function(value) {
  console.log(value);
});

output :

1
text
10
{name:"sita",age:"20"}

Basic set operations :

1. union :

Set.prototype.union = function(setB) {
    var union = new Set(this);
    for (var elem of setB) {
        union.add(elem);
    }
    return union;
}

var setA = new Set([1,2,3,4]);
var setB = new Set([1,2,5,6]);
setA.union(setB); // [1,2,3,4,5,6]

2. Intersection :

Set.prototype.intersection = function(setB) {
    var intersection = new Set();
    for (var elem of setB) {
        if (this.has(elem)) {
            intersection.add(elem);
        }
    }
    return intersection;
}
var setA = new Set([1,2,3,4]);
var setB = new Set([1,2,5,6]);
setA.intersection(setB); // [1,2]

3. difference :
 Set.prototype.difference = function(setB) {
    var difference = new Set(this);
    for (var elem of setB) {
        difference.delete(elem);
    }
    return difference;
}

var setA = new Set([1,2,3,4]);
var setB = new Set([1,2,5,6]);

setA.difference(setB); // [3,4]

setB.difference(setA); [5,6]

Relation with Strings :

var text = "Blogger";

var myNewSet = new Set(text);

console.log(myNewSet);

["B","l","o","g","g","e","r"]

myNewSet .size; //6

Relation with Arrays :

var myArr = ['val1','val2','val3'];

var myNewSet = new Set(myArr);

myNewSet .has('val1'); //true

To transform a set into an Array we use spread operator.

console.log([...myNewSet]); //["val1", "val2", "val3"]

ES2015 or ES6 Collections Maps and Sets

The two new Data Structures are been implemented in ES2015. They are :

1. Maps

2. Sets

Maps :

This will map a key to a value. The key and value accept both primitive and object types.
Maps are ordered and it elements are been traversed based on the order of the insertion.

Syntax :

new Map([iterable])

Operations of Map :

1. set()
2. get()
3. has()

set() :

This function will set the value for the respective key in the map object. It accept two parameters i.e. the key and the value. This don't accept duplicates i.e. it contains only unique values. This is similar to the arrays.

Example :

var setId = new Map(); //creating a map object
setId.set('id','1234');
Here, the id key is mapped to the number 1234.

The set() will also support the chaining concept. i.e. we can set more than one key value pair to a single map object.

Example :

var fruits = new Map();
fruits.set('1','apple')
.set('2','banana')
.set('3','grapes');
console.log(fruits.get('2')); //banana

get() :

This function is used to retrieve the values from it's related key.

Example :

setId.get('id'); // "1234"

has() :

This function will verify whether the key is been found in the map object or not and it returns a Boolean result. If element is found it returns true else the result will be false.

Example :

setId.has('id'); //true

The Map constructor can also be defined in the form of an array.

Example :

var fruits = new Map([
['1','apple'],
['2','banana'],
['3','orange'],
]) ;
console.log(fruits.get('3'));
output :
orange

The values of the set can also be replaced i.e. fruits.set('2','watermelon');

console.log(fruits.get('2')); //watermelon

Methods :

There are six map methods. They are :

1.Map.prototype.clear()
2.Map.prototype.delete(key)
3.Map.prototype.entries()
4.Map.prototype.keys()
5.Map.prototype.values()
6.Map.prototype.forEach(callBackFunction,arg)

 Map.prototype.clear() :

The clear() method removes all the key/value pairs from the Map object.

Example :

var names= new Map();
names.set('name','sita');
console.log(names.size); //1
names.clear();
console.log(names.size); //0

Map.prototype.delete(key) :

It deletes the value which is been associated to the key. It returns true if the element exists and deleted else it returns false and a parameter key need to passed to identify the value.

Example :

var data = new Map();
data.set('name','shruthi');
console.log(data.has('name'));
output :
true
data.delete("name");
console.log(data.has('name'));
output :
true
false

Map.prototype.keys() :

It refers to the keys in the Map and then returns a new iterator object.

Syntax :

data.keys()

Example :

var data = new Map();
data.set('name','shruthi');
data.set('gender','female');
var itrtr = data.keys();
console.log(itrtr.next().value);
console.log(itrtr.next().value);

output :
name
gender

Map.prototype.values() :

It refers to the keys in the Map and then returns a new iterator object.

Syntax :

data.values()

Example :

var data = new Map();
data.set('name','shruthi');
data.set('gender','female');
var itrtr = data.values();
console.log(itrtr.next().value);
console.log(itrtr.next().value);

output :

shruthi
female

Map.prototype.entries() :

It returns an array of [key,value] pairs in the new iterator object for each element in the map.

Syntax :

data.entries()

Example :

var data = new Map();
data.set('name','shruthi');
data.set('gender','female');
var itrtr = data.entries();
console.log(itrtr.next().value);
console.log(itrtr.next().value);

output :
name,shruthi
gender,female

Map.prototype.forEach(callBackFunction,arg) :

The forEach() function executes the specified function for each and every entry.

Example :

var data = new Map();
data.set('name','shruthi');
data.set('gender','female');
data.forEach(showDetails);
function showDetails(key,value){
console.log(key + " "+ value);
}
output :

shruthi name
female gender

Comparison between Maps and Objects :

The main differences are :

1. The keys for the Object has to be only strings or symbol but for the Maps it can be any value i.e. it may be a function,objects or any primitive.
2. To know the size of a object when need to check manually but for the map we can easily know with the size property.
3. Map has better scenarios for adding and removing the key/value pairs.
4. To iterate an object we need to obtain the key and then do the iteration but Map can be directly iterated.

If NaN is used as Map keys :

Even though NaN is not equal to itself i.e. NaN == NaN (false) , the NaN can be used as a key in a Map.
Example :

var data = new Map();
data.set(NaN,"not a number");
data.get(NaN);
output : 
"not a number"
var data1 = Number("abcd");
data.get(data1);
output :
"not a number"

Iterate Map using for...of loop :

Map can be created using for..of loop. Example :

var myMap = new Map();
myMap.set(1,'apple');
myMap.set(2,'banana');

for(var [key,value] of myMap)
{
      console.log(key + '=' + value);
}

output :

1=apple
2=banana

for(var key of myMap.keys())
{
      console.log(key);
}

output :

1
2

for(var value of myMap.values())
{
       console.log(value);
}

output :

apple
banana

for(var [key,value] of myMap.entries())
{
     console.log(key + '=' + value);
}

output :

1=apple
2=banana

Relation with the Array Objects :

var array1 = [["name","ram"],["gender","male"]];
var myMap = new Map(array1);
myMap.get('name');

output :
"ram"

Array.from(myMap) :
It retrieves all the array elements key/value pairs.

output:
["name","ram"]
["gender","male"]

Array.from(myMap.keys()) :
It retrieves only keys from the array.

output :
["name","gender"]

Array.from(myMap.values()) :
It retrieves only valuesfrom the array.

output :
["ram","male"]
 

ES6 New String Methods

New String Methods :

1. String.prototype.startsWith(searchString,position)

This method will check if the string starts with the specified character. And returns true if the start character is same as the search string.

Parameters :

searchString : The specified character to be searched from starting of a string.

position : It is the index position, which has to begin it's search for the search string and default value is 0.

It returns true if the start string matches else it returns false.

Example :

var str = "Hi, Good Morning!"
console.log(str.startsWith('Hi'));

output :
true

console.log(str.startsWith('Hi',0)); //true

console.log(str.startsWith('Hi',6)); //false

2. String.prototype.endsWith(searchString,endPosition = endPosition.length) :

This method validates whether the string ends with the character of another string.

Parameters :

searchString : The characters that the string must end and it is case-sensitive.

endPosition : The position is to the match the string and this is optional.

returns true if the character ends with the match string else it returns false.

Example :

var str = 'Hi, Good AfterNoon !!! ';

console.log(str.endsWith('Hi')); //false
console.log(str.endsWith('Hi',2)); // true

3. String.prototype.includes(searchString,position)

This string determines whether the string is a substring of a given string.

Parameters :

searchString : substring to search for

position : position is the index to start search from that specified index and default value is 0.

returns true if the string has the substring else it returns false.

Example :

var str = 'Hi, Good Morning!';

console.log(str.includes('hi')); // false   
console.log(str.includes('Hi'));  // true

console.log(str.includes('Morning'));   // true
console.log(str.includes('Good',4)); // true

4. String.prototype.repeat(count) :

This method repeats the string for the specified number of times.

Syntax :

str.repeat(count);

Parameter :

count : number of times the string need to be repeated.

returns a new string

Example :

var myString = new String("JavaScript");
console.log(myString.repeat(3));

output:

JavaScriptJavaScriptJavaScript

Template Literals :

Template Literals are string literals which can allow the embedded expressions and the template strings use back ticks (` `) instead of single quotes and double quotes.

Template String Example :

var foo = `Hello World!`;

String Interpolation :

The placeholders for string substitution can be used by the following syntax :
${ }

Example :

var name = "blog";
console.log('Hi, ${name}');

output :

Hi, blog

String Methods :

1. charAt() :

This method returns the character from the specified index. The characters in the string are been indexed from left to right. The index will start from 0 and end up to the string length - 1.

Example :

var string = "Ambition";
console.log(string.charAt(3));

output : i

2. charCodeAt() :

This method returns the number for the given index in the form of  Unicode value.

These Unicode values range from 0 to 1,114,111. The first 128 Unicode's are of ASCII values and the charCodeAt() returns a value which is less than 65,536.

It returns NaN if the given index i.e, number is not between 0 and length of the string - 1.

Example :

var string = "Ambition";
console.log(string.charCodeAt(3));

output : 105

3. indexOf() :

This method returns the index of the first occurrence of the string object. It starts searching from fromIndex or it can be -1 if the value is not found.

Example :

var string = "Ambition";
console.log(string.indexOf("b"));

output : 2

4. concat() :

concat() method is used to add two or more strings and returns a new string.

Example :

var string1 = "TRY AGAIN FAIL AGAIN ";
var string2 = "FAIL BETTER";
console.log(string1.concat(string2));

output : TRY AGAIN FAIL AGAIN FAIL BETTER

5. lastIndexOf() :

This method returns the index of the string i.e, the last occurrence of the specified value. It starts searching at fromIndex and -1 if the value is not found.

Example :

var string1 = "TRY AGAIN FAIL AGAIN ";
console.log(string1.lastIndexOf("AGAIN"));

output : 15

6. localeCompare() :

This method returns a number and indicates whether the string comes before or after or the same as the string.

It returns 0 if the string is same, returns 1 if there is no match and also if the parameter value contains in the string, returns -1 if there is no match and if the parameter value doesn't contains in the string.

Example :

var string = "This is a string";
console.log(string.localeCompare("xyz")); //-1
console.log(string.localeCompare("n")); //1
console.log(string.localeCompare("This is a string")); // 0

7. slice() :

It extracts a specific string and returns a new string.

If the result is successful then it returns the string of the specified index else it returns -1.

Example :

var string = "This is a string";
console.log(string.slice(2,7)); // is is
console.log(string.slice(3,-4)); // s is a st

negative value determines that from the end of the string it removes that amount of values from the string.

8. split() :

This method splits a string into a array of strings by separating it into the substrings.

Example :

var string = "This-is-a-string";
console.log(string.split("-"));
output : ["This", "is", "a", "string"]

9. substr() :

This method returns the characters in the string from the beginning of the specified string to the specified number of characters.

The substr() method returns the new substring based on the given parameters.

Example :

var str = "This is a string";
console.log(str.substr(1,2)); //hi
console.log(str.substr(-2,2)); // hg
console.log(str.substr(1)); // his is a string

10. substring() :

This method returns the subset the of a string.

It returns the new sub-string based on the given parameters.

Example :

var str = "This is a string";
console.log(str.substring(1,2)); //h
console.log(str.substring(-2,2)); //Th
console.log(str.substring(1)); // his is a string

11. toLowerCase() :

It converts the string into lowercase.

Example :

var string = "TRY AGAIN FAIL AGAIN FAIL BETTER";
console.log(string.toLowerCase());

output : try again fail again fail better

12. toUpperCase() :

This method converts the string into upper case.

var string = "try again fail again fail better";
console.log(string.toUpperCase());

output : TRY AGAIN FAIL AGAIN FAIL BETTER

13. toString() :

This returns a string with the specified object.

Example :

var string = "This is a string";
var numbers = "1234";

console.log(string.toString());
console.log(numbers.toString());

output :
This is a string
1234

14. valueOf() :

This method returns the string object of the primitive value.

Example :

var str = "This is a string";
console.log(str.valueOf());
output :
This is a string

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.



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