jQuery

jQueryBasics :

The jQuerylibrary defines a single global function i.e. jQuery(). As this function is been used most frequently so a shortcut is been defined for it i.e. $. The value which is been returned by this function represents a set of zero or more DOM elements and is known as a jQuery object. The jQuery() is a factory function rather than a constructor: it returns a newly created object but is not used with the new keyword and the jQuery objects define many methods for operating on the sets of elements they represent.

Example :

$("p.newContent").css("background-color", "yellow").show("fast");

Explanation :

In the above example, css() method will be operated on the jQuery object returned by $(), and it will return the same object, so that the show() method can be invoked next in a compact “method chain.”
This method chaining idiom is common in jQuery programming.

How to obtain jQuery :

The jQuery library is a free software. we can download it from the http://jquery.com. Once the downloading is done we can include the src it in the script tag as :
< script >
src="jquery-1.4.2.min.js"
</ script >

The min in the file name is the minimised version of the library i.e. the unnecessary comments, whitespaces are been removed and the internal identifiers are been replaced with shorter one's.

And Here goes the another way to use jQuery in your web applications i.e. is to allow a content distribution network to serve it using a URL like (any URL can be used from the below mentioned one's):
            http://code.jquery.com/jquery-1.4.2.min.js
            http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js
            http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js

But most recommended is to use the downloaded file. where our data will be loaded faster and if the URL is been used sometimes the data may be received late because of network issues.

The jQuery() function :

The jQuery() function is the most important one in jQuery library.  The function can be invoked in four different ways i.e.

         The first way is to invoke $() to pass a CSS selector to it. When it is been called this way, it returns the set of elements from the current document that matches the selector. jQuery supports most of the CSS3 selector syntax, and also some extensions of its own. An element or a jQuery object can be passed as the second argument to $(), it will return only the matching descendants of the specified element or elements. A starting point is been defined for the jQuery by the optional second argument and is often called the context.

The second way is to invoke $() i.e. to pass it to a window or element or document object. It will simply bind the element, document or window in a jQuery object and it will return that specified object. By this it allows us to use jQuery methods to manipulate the element rather than using it as  raw DOM methods. The jQuery programs call $(document) or $(this). 

Example :

jQuery objects can be able to represent more than one element in a document, and you can also pass an array of elements to $(). So, the returned jQuery object represents the set of elements in an array.

         Now third way is to invoke $() i.e. to pass it a string of HTML text. Then the jQuery will create the HTML element or elements described by that text and then it returns a jQuery object representing those elements. If we are passing a plain text when you invoke $() in this way, or jQuery then it will think you are passing a CSS selector. For this format, the string which is been passed to $() must include at least one HTML tag with angle brackets.


       When invoked in this third way, $() will accept an optional second argument. A  Document object can be passed to specify the document with which the elements are to be associated or normally an object can be passed as a second argument. If you do this, the object properties are assumed to specify the names and values of HTML attributes to be set on the object. But if the object is been included with the properties containing any of the following names “css”, “html”, “text”, “width”, “height”, “offset”, “val”, or “data”, or properties that contains the same name as any of the jQuery event handler registration methods, then the  jQuery will invoke the method of the same name on the newly created element and pass the property value to it.

Now, the fourth way to invoke $() is to pass a function to it. The function which is been passed by us 
will be invoked when the document has been loaded and the DOM is ready to be manipulated. This is the jQuery version of the onLoad() function.

jQuery(function() { // Invoked when the document has loaded
// All jQuery code goes here
});

This will be invoked when the document is ready and DOM is ready.

The function which is been passed to jQuery() will be invoked with the document object as its
this value and with the jQuery function as its single argument. This means that we can undefine the global $ function and still use that convenient alias locally with  noconflict() :

jQuery.noConflict(); 
jQuery(function($) { 
});

Difference between $() and querySelectorAll() :

The $() function is similar to the Document method querySelectorAll() that was described both take a CSS selector as their argument and return an array-like object that holds the elements that match the selector. The jQuery implementation uses querySelectorAll() in browsers that support it, but there are good reasons to use $() instead of querySelectorAll() in your own code:
• querySelectorAll() has only recently been implemented by browser vendors but the $() works in older browsers as well as new ones.
• Because jQuery can perform selections “by hand,” the CSS3 selectors supported by $() work in all browsers, not just those browsers that support CSS3.
• The array-like object returned by $() (a jQuery object) is much more useful than the array-like object (a NodeList) returned by querySelectorAll().

each() :

  • looping over all elements in a jQuery object. we can call the each() method instead of writing a for loop. The each() method is like a ECMAScript 5 forEach() array method. 
  • It expects a callback function as its sole argument, and it invokes that callback function once for each element in the jQuery object . 
  • The callback is invoked as a method of the matched element, so within the callback the this keyword refers to an Element object. 
  • each() also passes the index and the element as the first and second arguments to the callback. 
  • The second argument are raw document elements, not jQuery objects. 
  • If we want to use a jQuery method to manipulate the element, we need to pass it to the $() first.
  • jQuery’s each() method has one feature that is quite different than forEach().
  • If the callback returns false for any element, iteration will be terminated after that element.
  • each() returns the jQuery object on which it is called, so that it can be used in method chains.
jQuery has released in January 2006 by John Resig at BarCamp NewYork. It is currently headed by Timmy Wilson and it is been maintained by the team of developers. Nowadays, the jQuery is been used by so many websites.

jQuery Release Dates :

Version No                                                   Release Date
   
    1.0                                                               26-Aug-2006
   
    1.1                                                               14-Jan-2007

    1.2                                                               10-Sep-2007

    1.3                                                               14-Jan-2009

    1.4                                                               14-Jan-2010

    1.5                                                               31-Jan-2011

    1.6                                                               3-May-2011

    1.7                                                               3-Nov-2011

    1.8                                                               9-Aug-2012

    1.9                                                               15-Jan-2013

    1.10                                                             24-May-2013

    1.11                                                             24-Jan-2014

    2.0                                                               18-Apr-2013

    2.1                                                               24-Jan-2014

JavaScript Tricky Questions

1. return statement :

function first(){
      return {
       name : "sita"
      };
}
function second(){
      return
      {
         name : "ram"
       };
}

call both the functions

first();
second();

The first() will return the Object =>  { name : "sita"} and the function second() will return undefined both doesn't give the same result because here it adds semicolon for the return statement. It will be inserted immediately at the end of the return statement and the block of the code will never get executed but it doesn't throw any error because the  remainder of the code is valid.

2. Equality :

console.log(0.1 + 0.2 );
console.log(0.1 + 0.2 == 0.3);

Here, our guess goes to true for the second log but it log false. The numbers in JavaScript are treated as floating point. So, unexpectedly the output will be :

0.30000000000000004
false

3. NaN :

NaN means "not a number".
NaN compared to anything or itself returns false.
console.log(NaN == NaN )
output : false
the typeof NaN is number
console.log(typeof NaN == "number")
output :   true

4. If we add strings with numbers : 

console.log(1 +  "2" + "5");
output :
125 // If a string is added after the number then the numbers will be concatenated but not added.

console.log(1 +  +"2" + "5");
output : formula : (  + * + = +)
35 // It string is followed two plus symbols then the first and second numbers are added and the third one is concatenated.

console.log(1 +  -"1" + "5");
output :
35
As formula says ( + * - = -)  here the numbers are subtracted  and the third number is concatenated.

console.log(+"1" +  "5" + "7");
output :
157
Because all are strings.

console.log( "A" - "B" + "5");
output :
NaN5
As, "A"-"B" is not valid so, it returns NaN and the other string 5 is valid it concatenates 5 to NaN.

console.log( "A" - "B" + 5);
output :
NaN
Here, 5 is a number and adding all those is not valid. So, NaN is returned.

5. Boolean false Equality :
console.log(false == '0'); // true
console.log(false === '0'); //false

In JavaScript, we have two equality operators i.e. triple equal and double equal operator. Triple equal will returns true if the two expressions on either side has same type and same value whereas double equal just compares the value.

6.  var y = 10;
var foo =  function() {
console.log(y);
var y = 15;
};
foo();

output :
undefined

The output is not 10 or 15. Then we just get a doubt that if it is not taking a local variable why can't it take global variable the answer is : when the function is getting executed it checks that the local variable y is present but it isn't declared yet so it will not look for the global variable.

7. typeof
 typeof undefined == typeof NULL

output :

true

Because NULL is treated as any other undefined value.

8. console.log(typeof typeof 10);

what would this returns?

output :
string
Because the typeof 10 will result "number" and the typeof "number" will result in string.

9. Delete operator : 
var output = (function(y){
    delete y;
    return y;
  })(0);
 
  console.log(output);

output :
0

Because here delete operator is used delete properties from an object. As y is a local variable, it is not an object. So, no changes will be done.

10. Deleting an array element :
var sample = ["apple","banana","grapes","kiwi","orange"];
delete sample[3];
console.log(sample.length);

output :
5

After deleting the sample[3] it creates an empty space but doesn't get effected to the length of the array. Only the value gets removed and undefined will be placed at that index.

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

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