Monday, April 30, 2018

setInterval

It runs the function regularly after the given interval of time. Suppose, If you want to stop the actions you should call clearInterval(timerId).

The setInterval method syntax is same as setTimeout.

Syntax:


let timerId = setInterval(func|code, delay[, arg1, arg2...])

Example:



let timerId = setInterval(() => alert('I will run every 3 seconds continuously'), 3000);

The above alert will show up every 3 seconds once.

setInterval with clearInterval

Example:

1
2
3
4
let timerId = setInterval(() => alert('Test'), 2000);

// after 5 seconds stop the interval
setTimeout(() => { clearInterval(timerId); alert('stop'); }, 5000);

Explanation:
       
                1. Line number 1 will be run continuously for every 2 seconds.

                2. But line number 5 will clear the interval time after 5 seconds. So after 5 seconds alert 
                    "Test" will not shown.





setTimeout with clearTimeout

We can use “timer identifier” which will be returned by setTimeout and the same we can use to cancel the execution.

Syntax:



let timerId = setTimeout(...);
clearTimeout(timerId);

Example:



1
2
3
let myVar = setTimeout(function(){ alert("Hello"); }, 3000);

let xxx = clearTimeout(myVar);

Explanation:

1. Line number 1 will be executed initially

2. To display the alert Hello message 3 seconds need to be waited.

3. But line number 3 will be executed before three seconds. So alert message will not be displayed here.

setTimeout


For executing some methods based on some times, then we should go ahead with setTimeout and  setInterval.

setTimeout allows to run a function once after the interval of time.


The syntax:



let timerId = setTimeout(func|code, delay[, arg1, arg2...])


func|code -  Function or a string of code to execute. Mostly, this will be a function. But some peoples may pass a string of code and its not recommended. The reason I have mentioned in Javascript interview section.

delay -  The delay before run, should be mentioned in milliseconds (1000 ms = 1 second).

arg1, arg2…  - arguments.

Simple Example:



1
2
3
4
5
function sayHi(welcomeMsg, user) {
  alert( welcomeMsg + ', ' + user );
}

setTimeout(sayHi, 5000, "Hello", "Raj"); // Hello, Raj

Explanation:

The sayHi method will be called after 5 seconds. Just compare this example with syntax. Hope you got it.

Note:

Do not pass like sayHi(). You should pass always method name only like sayHi without brackets.





Friday, April 27, 2018

Named Function Expression - NFE

Named Function Expression (NFE)  - We are giving a name to Function Expressions.

Before going into NFE, we should understand what is Ordinary Function Expression. Below is example,


let sayTest = function(one) {
  alert(one);
};

Now just add a name to that, (NFE).


let sayTest = function yourName(one) {
  alert(one);
};

It looks like very simple. But everything is designed for some reason. Let check why we are giving name like this?


1. It allows the function to reference itself internally.

2. It will not be visible to outside of the function.


let sayTest = function yourName(one) {
  if (one) {
    alert(one);
  } else {
    yourName("Guest"); // use yourName to re-call itself
  }
};

sayTest(); // Guest

// Error here
yourName(); // Error Here - not visible outside of the function


Come to our final main concept. Why we want this NFE. See below example,


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let sayHi = function yourName(one) {
  if (one) {
    alert(`Hello, ${one}`);
  } else {
    yourName("Guest");  // Because of this line, this code working
    //sayHi ("Guest"); // This will not work.
  }
};

let welcome = sayHi;
sayHi = null;

welcome(); // nested call works here perfectly

Explanation :

1. Here line number 1, yourName is your NFE. 

2. You have used this name inside line number 5.

3. Suppose if you change the line number 5 to like sayHi("Guest"), will throw an error. Why ?

4. Because line number 10, sayHi was assigned to null. So this will be reflected to line number 9 too. So error will be thrown. (There is no sayHi function).

5. To solve that, we should add NFE , Because internal call possible in NFE.





Function Object with Custom Properties

We can add our own custom properties with function object.

Below example will explain you How do we use custom property with function object.


function countTest() {
  alert("Hi");

  countTest.counter++;
}
countTest.counter = 0; // initial value

countTest(); // Hi
countTest(); // Hi

alert( `Called ${countTest.counter} times` ); // Called 2 times

Explanation :

We are calling countTest function at two times. So while calling at every time counter (custom property) will be executed and returning 2 in alert.


Function object - length property

Using length property with function object, will return how many parameters the function using.

Example:


function first(a) {}
function second(a, b) {}
function multiple(a, b, ...more) {}

alert(first.length); // 1
alert(second.length); // 2
alert(multiple.length); // 2

Note: The last one, multiple function showing parameter length as 2. Because rest parameters(...) will not be calculated.


Thursday, April 26, 2018

Function Object - name property


Function objects contain some properties.

1. name property

We can access a function’s name with the help of the “name” property.


function testFunctionName() {
  alert("Hi");
}

alert(testFunctionName.name); //testFunctionName


let sayHi = function() {
  alert("Hi");
}

alert(sayHi.name); // sayHi

Above code, you can see we are getting the function name with the help of name property.


It will work with function which is placed inside object too. See below to understand further,


let user = {

  sayHi() {
    // ...
  },

  sayWelcome: function() {
    // ...
  }

}

alert(user.sayHi.name); // sayHi
alert(user.sayWelcome.name); // sayWelcome


Note: Suppose if there is no name for function then empty string will be returned.






Global Object (Window)

Global object is nothing but referring "window" only. The same will be called in node js as "global". For other frameworks it may have different name.

What it will do ?

It will provides you to access the built-in functions and values and provides access to the global Function Declarations and var variables.

Note: let and const is different from this. Declaring with var only we can consider as global.



var phrase = "Hello Test";

function sayHi() {
  alert(phrase);
}

// can read from window
alert( window.phrase ); // Hello Test
alert( window.sayHi ); // function sayHi() { alert(phrase); }


Wednesday, April 18, 2018

IIFE explanation with closure

Simple example for IIFE with closure explanation:


var MyClosureTest = (function (){
  var WelcomeMessage = 'Welcome to IIFE with Closure example';
  return {
    getWelcomeMessage: function () { return WelcomeMessage;},
    setWelcomeMessage: function (message) { WelcomeMessage = message}
  }
}());


Explanation:

Here,  We are not assigning a function to MyClosureTest. We want the result of invoking that function to MyClosureTest.

Important is, see at end - we added () in the last line.(IIFE).

If I want to get the WelcomeMessage then I can use getWelcomeMessage and it will work.  The below line will print our message.


console.log(MyClosureTest.getWelcomeMessage()); //Welcome to IIFE with Closure example

But following way would not work:


console.log(MyClosureTest.WelcomeMessage); 
// undefined

But you can set an get the expected message result:


MyClosureTest.setWelcomeMessage('I understood IIFE and closure');
console.log(MyClosureTest.getWelcomeMessage()); 
//I understood IIFE and closure






Self Invoking function | Immediately Invoked Function Expressions

Remember the below , this is the simple and best example for IIFE (Immediately Invoked Function Expressions).


(function () {
  // body of the function
}());

An another way for IIFE


(function () {
  // body
})();


It will be invoked automatically without being called. You must add parentheses(based on above two - I prefer second one ) in starting of the function and end of the function to express that it is a function expression.

How it is work ?

At the end we have added (), this is the reason its calling automatically. So remember adding () this at end is must. So that IIFE will work for you.

Why do we want to use this?

Most of the time for the below two reasons, we are using IIFE.

1. For Better namespace management

2. Closures

Next chapter we can see a good example about closures with IIFE. 





Tuesday, April 17, 2018

Spread operator

Spread operator to the opposite job of Rest parameter.

Below all examples combined together, please check one by one. So that you can understand it easily.


// Normal way - will not work
let arr = [7, 5, 4];
alert( Math.max(arr) ); // NaN


//Could work with spread operator
let arr = [7, 5, 4];
alert( Math.max(...arr) ); // 7 (spread turns array into a list of arguments)


//Multiple iterables array
let arr1 = [1, -2, 6, 5];
let arr2 = [8, 9, -8, 7];

alert( Math.max(...arr1, ...arr2) ); // 9



//Combined
let arr1 = [1, -2, 6, 5];
let arr2 = [8, 9, -8, 7];

alert( Math.max(3, ...arr1, 2, ...arr2, 52, 56) ); // 56



//Merging array is easy
let arr = [3, 5, 1, 4, 6, 8];
let arr2 = [8, 9, 15, 2, 1, 7, 3];

let merged = [0, ...arr, 2, ...arr2];

alert(merged); // 0,3,5,1,4,6,8,2,8,9,15,2,1,7,3


// String into array of characters
let str = "Hello";

alert( [...str] ); // H,e,l,l,o








Monday, April 16, 2018

The “arguments” variable

Actually rest parameters are available from ES6 on wards only. So if you you want the same behavior of Rest parameters in older than ES6, you should use "arguments".

Below example may tell you more clearly.


function showName() {
  alert( arguments.length );
  alert( arguments[0] );
  alert( arguments[1] );

  // Iteration also possible here
  // for(let arg of arguments) alert(arg);
}

// 2, Test1, Test2
showName("Test1", "Test2");

// 1, Ilakiya, undefined (Because no second argument)
showName("Ilakiya");

From the above code, we are calling showName method twice. While calling at first time we are passing two parameters.  So length is 2 and alert showing two parameters.

But while calling second showName function, we are passing only one parameter. So that , alert showing length as 1 and second parameter as undefined. Hope you got it.

Things to Remember:
              1. arguments is like an array , but it will not support array method . So you cannot use arguments.map() with this.

              2. Arrow functions do not have "arguments".





Rest parameters ...


A function can be called with any number of arguments. What is this means? Assume that you one simple sum function which accept two parameters. So you can pass those two parameters easily. But Suppose if it is more than 5 parameters or more than 10 parameters. You will get lazy to pass manually, right ? To avoid that use rest parameter.

Simple Example I:
function sumAll(...args) { // args is the name for the array
  let sum = 0;

  for (let arg of args) sum += arg;

  return sum;
}

alert( sumAll(1) ); // 1
alert( sumAll(1, 2) ); // 3
alert( sumAll(1, 2, 3) ); // 6

The rest parameters should be mentioned as three dots .... Here ...args is array which have all of your arguments.

Suppose if you dont want all n parameters as ...args, you can give first two as manual and remainig all as ...args.

Simple Example II:

function showName(firstName, lastName, ...titles) {
  alert( firstName + ' ' + lastName ); // TestFirstName TestLastName

  // the rest go into titles array
  // i.e. titles = ["ArrayFirst", "ArraySecond"]
  alert( titles[0] ); // ArrayFirst
  alert( titles[1] ); // ArraySecond
  alert( titles.length ); // 2
}

showName("TestFirstName", "TestLastName", "ArrayFirst", "ArraySecond");


Note: Remember, the ...rest must always be last.






JSON.parse


Whenever you are receiving data from a server, the data is may be a string. So to make the data as JS object we should use JSON.parse().


var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
console.log(obj); // Output will be in object format

var text = '{ "name":"John", "birth":"1986-12-10", "city":"New York"}';
var obj = JSON.parse(text);
obj.birth = new Date(obj.birth);

console.log(obj);

Explanation:
     Initially we have passed a string value into the parse method. So that now it will become an object.

In the third line, same concept we have used like line number 1 and 2. But after parse, we have modified birth date property. So now the Date will be added like correct date format.


JSON Reviver function:

The Reviver parameter is a function which will check each property, before returning the value.


var text = '{ "name":"John", "birthDate":"1986-12-10", "city":"New York"}';
var obj = JSON.parse(text, function (key, value) {
    if (key == "birthDate") {
        return new Date(value);
    } else {
        return value;
    }});


We are checking here for date, because we need to convert as a proper date format, not in string format. If you are not using parse reviver function, still you will use date as string only.
Hope you got it.





Custom - toJSON

Example I:


See the below example to understand custom toJson concepts. (Built in toJSON)

let Test = {
  number: 23
};

let TestingDate = {
  title: "DateTest",
  date: new Date(Date.UTC(2018, 0, 1)),
  Test
};

alert( JSON.stringify(TestingDate) );
/*
  {
    "title":"DateTest",
    "date":"2018-01-01T00:00:00.000Z",  // (1)
    "Test": {"number":23}               // (2)
  }
*/

Explanation:

        Here Date is showing perfectly after json convert. Because all dates have a built-in toJSON method which returns the correct string.

Example II: (custom toJSON)




let CustomCheck = {
  number: 23,
  toJSON() {
    return this.number;
  }
};

let CustomCheckTest = {
  title: "Something",
  CustomCheck
};

alert( JSON.stringify(CustomCheck) ); // 23

alert( JSON.stringify(CustomCheckTest) );
/*
  {
    "title":"Something",
    "CustomCheck": 23
  }
*/

Explanation:

This example is different, as we have mentioned toJSON separately. Means, we are not using in built toJSON.

In the initial customCheck object we have returned the number 23. So whenever you are using CustomCheck object , it will provide you 23.






What are the specific properties skipped by stringify

Some of JavaScript-specific object properties are skipped by JSON.stringify.

What are those ?

1. Function properties - means methods
2. Symbolic properties.
3. Properties that store undefined.


let user = {
  sayHi() { // ignored
    alert("Hello World");
  },
  [Symbol("id")]: 123, // ignored
  something: undefined // ignored
};

alert( JSON.stringify(user) ); // {} (empty object)



However, another good here is, nested objects are supported and converted automatically.


let testNestedObjects = {
  title: "NestedCheck",
  test1: {
    number: 123,
    participants: ["test25", "test26"]
  }
};

alert( JSON.stringify(testNestedObjects) );

Output:

{
  "title":"NestedCheck",
  "test1":{"number":123,"participants":["test25","test26"]},
}








JSON methods

Generally we will use JSON for sending data over the network like Rest web service call etc.,

We can see some important methods here.

1. JSON.stringify -  to convert objects into JSON.

2. JSON.parse      -  to convert JSON back into an object.



let student = {
  name: 'Rajini',
  age: 30,
  isAdmin: false,
  courses: ['css', 'js']
};

let json = JSON.stringify(student);

alert(typeof json); // Its String now.

alert(json);
/* JSON-encoded object:
{
  "name": "Rajini",
  "age": 30,
  "isAdmin": false,
  "courses": ["css", "js"]
}
*/


Things to Remember Here:

1. Strings use double quotes. No single quotes or backticks in JSON. So 'Rajini' becomes "Rajini".

2. Object property names are double-quoted also. That’s obligatory. So age:30 becomes "age":30.

3. JSON.stringify can be applied to primitives also.


JSON supported types are:

Objects { ... }
Arrays [ ... ]
Primitives:
strings,
numbers,
boolean values true/false,
null.







Object destructuring

We can use destructuring assignment for objects also.

Syntax:
let {var1, var2} = {var1:…, var2:…}

Right side is an existing object which that we want to split into variables. Left side is our pattern to split variables.

Basic Example I:



let options = {
  title: "MasterPage",
  width: 100,
  height: 200
};

let {title, width, height} = options;

alert(title);  // MasterPage
alert(width);  // 100
alert(height); // 200

Internally its uses like , options.title, options.width and options.height. Hope you got it.
and order does not matter here. Anywhere it will work.

Example II:



let options = {
  title: "MasterPage",
  height: 200,
  width: 100
};

let {title, width, height} = options;

alert(title);  // MasterPage
alert(width);  // 100
alert(height); // 200

Above order was changed, still its working perfectly.

Rest Operator:

Below we have used Rest operator with object. So other than title, remaining will come under rest. See below code.


let options = {
  title: "MasterPage",
  height: 200,
  width: 100
};

let {title, ...rest} = options;

// now title="MasterPage", rest={height: 200, width: 100}
alert(rest.height);  // 200
alert(rest.width);   // 100







Destructuring assignment

We all know, most used data structures in JavaScript are Object and Array.

Destructuring asis a special syntax that allows us to “unpack” arrays or objects into a bunch of variables.

Why its allowing? Since they are more convenient. Most of the time we want to work with complex functions that have a lot of parameters, default values etc.,

Array destructuring:



let arr = ["Ilakiya", "Kannika"]

// destructuring assignment
let [firstName, surname] = arr;

alert(firstName); // Ilakiya
alert(surname);  // Kannika

See, Its very compatible. Its coming with ES6.

Here is another trick for ignoring first elements. See below...


let [, , title] = ["Test1", "Test2", "Test3", "Test4"];

alert( title ); // Test3

As you have put comma for two times, first two elements not considered here.

You can more play with this.. See below.


let user = {};
[user.name, user.surname] = "Ilyakiya My Love".split(' ');

alert(user.name); // Ilyakiya


Rest ...

You can mention multiple at a time , then go with “the rest” using three dots "..."


let [name1, name2, ...rest] = ["Test1", "Test2", "Test10", "Test11"];

alert(name1); // Test1
alert(name2); // Test2

alert(rest[0]); // Test10
alert(rest[1]); // Test11
alert(rest.length); // 2


WeakMap and WeakSet

WeakMap and WeakSet is little different because it does not prevent from memory. You may understand it after seeing the example.

We can not use keys as primitives in weakmap.


let weakMap = new WeakMap();

let obj = {};

weakMap.set(obj, "ok"); // works fine (object key)

weakMap.set("test", "Whoops"); // Error, because "test" is a primitive

If you are trying to use primitives in weakmap, simply it will through an error. (above example).

Example II:


let john = { name: "John" };

let weakMap = new WeakMap();
weakMap.set(john, "...");

john = null; // overwrite the reference

// john is removed from memory!

alert(john); //null

Below is the main part of weakmap. Furthermore , you can not access john after set it to null.

Weak map have some limitation in methods, because of some technical reason. Because, we should allow javascript engine to do the clean work. Means, clean should do immediately or later or parallel.

1. weakMap.get(key)

2. weakMap.set(key, value)

3. weakMap.delete(key, value)

4. weakMap.has(key)

WeakSet also same like weak map.

JavaScript Set

A Set is a collection of values, where each value may occur only once.

Its main methods are:

new Set(iterable)  –  creates the set, optionally from an array of values.
set.add(value)       –  adds a value, returns the set itself.
set.delete(value)  –  removes the value, returns true if value existed at the moment of the call, else false.
set.has(value)       –   returns true if the value exists in the set, else false.
set.clear()             –   clear everything from the set.
set.size                 –   the elements count.

Example I:


let set = new Set();

let test1 = { name: "test1" };
let test2 = { name: "test2" };
let test3 = { name: "test3" };

set.add(test1);
set.add(test2);
set.add(test3);
set.add(test1);
set.add(test3);

// Unique only allowed
alert( set.size ); // 3

for (let user of set) {
  alert(user.name); // test1 (then test2 and test3)
}

For uniqueness, you can go ahead with set.

Set Iteration :

Below are supported methods with set iterator.

set.keys() – returns an iterable object for values.
set.values() – same as set.keys, for compatibility with Map.
set.entries() – returns an iterable object for entries [value, value], exists for compatibility with Map.

Note: Map also have the same above.



let setExample = new Set(["oranges", "apples", "Mango"]);

for (let value of setExample) alert(value);

// the same with ES6 for each
setExample.forEach((value, valueAgain, set) => {
  alert(value);
});






Iteration Map

Consider I am passing an array to the map like below,


// array of [key, value] pairs
let map = new Map([
  ['1',  'stringOne'],
  [1,    'number1'],
  [true, 'booleanTrue']
]);

Object.entries(obj) is an inbuilt method  which returns an array of key/value pairs for an object with same format.

We can an initialize a map from an object like below,


let map = new Map(Object.entries({
  name: "Tester",
  age: 30
}));

Here, Object.entries returns the array of key-value pairs.

Output:
 [ ["name","Tester"], ["age", 30] ].

Iterate on Map:

There are 3 methods, we can use..

map.keys() – returns an iterable for keys,
map.values() – returns an iterable for values,
map.entries() – returns an iterable for entries [key, value] and it is used by default in for..of.

Example I :



let sportsMap = new Map([
  ['Cricket', 500],
  ['Football', 350],
  ['WWE',    50]
]);

// iterate over keys (vegetables)
for (let sport of sportsMap.keys()) {
  alert(sport); // cricket, Football, WWE
}

// iterate over values (amounts)
for (let fee of sportsMap.values()) {
  alert(fee); // 500, 350, 50
}

// iterate over [key, value] entries
for (let entry of sportsMap) { // the same as of recipeMap.entries()
  alert(entry); // cricket,500 (and so on)
}

Note: Map preserves this insertion order


ForEach with ES6 :

Map has a built-in forEach method, similar to Array...

Example II


sportsMap.forEach( (value, key, map) => {
  alert(`${key}: ${value}`); // cricket: 500 etc
});







Thursday, April 12, 2018

How to use object as Keys in Map

We can also use object as key in map.

Note: ES6 map is different. Do not make confuse yourself.

Example I:


let testObject = { name: "TestObject With Map" };

let testMap = new Map();

testMap.set(testObject, 123);

alert( testMap.get(testObject) ); // 123

Here testObject is the simple normal object which I used as key in map.

How Map comparing keys ?

Map uses the algorithm SameValueZero (same as strict equality === ).

We can also do the chaining operation with map. See below example,



testMap.set('1', 'stringOne')
       .set(1, 'number1')
       .set(true, 'booleanTrue');


Like this you can add n number of times.







Important methods in Map with example

Map is like key value pair concept (like an Object). But Map allows keys as any type. Remember object allows only string key.

Note: ES6 map is different. Do not make confuse yourself.

Main methods are below,

      new Map() – creates the map.

     map.set(key, value) – stores key and value.

     map.get(key) – returns the value by the key. Suppose If key doesn’t exist undefined will be  returned.

     map.has(key) – returns true if the key exists, else false will be returned.

     map.delete(key) – removes the value by the key.

     map.clear() – clears the map.

     map.size – returns the current element count.

Simple Example I:



let map = new Map();

map.set('1', 'stringOne');   // a string key
map.set(1, 'number1');     // a numeric key
map.set(true, 'booleanValueTrue'); // a boolean key

alert( map.get(1)   ); // 'number1'
alert( map.get('1') ); // 'stringOne'
alert( map.get(true) ); // 'booleanValueTrue
alert( map.size ); // 3


Note: See the above example, Keys are not converted to string.





Array - Split and join

A delimiter should be used with split method and its an optional parameter.

Syntax: 
string.split(separator, limit)


separator - Optional. Specifies the character, or the regular expression, to use for splitting the string.

limit - Optional. An integer that specifies the number of splits. No item will be take care after specified limit.

Example I:



let names = 'Test, Test1, Test3';

let arr = names.split(', ');

for (let name of arr) {
  alert( name ); // Test Test1 Test3
}

Example II:


var strTest = "How are you Baby?";
 var resTest = str.split(" ", 3);
 alert(resTest); // How,are,you

Example III:

Nothing specified then , below result you will get.

let str = "test";

alert( str.split('') ); // t,e,s,t


Join Method:

The reverse of split is called join method. Means, opposite to reverse.


let arr = ['Test1', 'Test2', 'Test3'];

let str = arr.join(';');

alert( str ); //Test1;Test2;Test3







Array Sort - Reverse

To sort an array in reverse, we can use reverse method directly. See below example,

1. Reverse an Integer array


let arr = [1, 2, 3, 4, 5];
arr.reverse();

alert( arr ); // 5,4,3,2,1

2. Reverse an string array


var fruitsTest = ["Banana", "Orange", "Apple", "Mango"];
fruitsTest.reverse();

Note: Reverse means , just reverse( End to start) the output. not any order.

Wednesday, April 11, 2018

Array ReOrdering - Sort


        In Javascript , the items are sorted as strings by default. So if you try to sort an array with have integer value, it will return incorrect result. See below example,


let arr = [ 1, 2, 7,15, 18 ];

arr.sort();

alert( arr );  // 1,15,18,2,7(Wrong Result)

The above example returns a wrong result. Because as I said earlier, sorted by string is default.

Remember, internally it will convert as string.

1. Classical Trick


function compareNumeric(a, b) {
  if (a > b) return 1;
  if (a == b) return 0;
  if (a < b) return -1;
}

let arr = [ 1, 2, 15, 7, 19, 54, 87, 43 ];
arr.sort(compareNumeric);
alert(arr);  // 1,2,7,15,19,43,54,87

2. With simple comparison




let arrSort = [ 1, 2, 15, 76, 76, 34, 89, 12 ];

arrSort.sort(function(a, b) { return a - b; }); // Ascending

alert(arrSort);

Note: For descending use b-a.


3. Same with Arrow function




let arrSort = [ 1, 2, 15, 76, 76, 34, 89, 12 ];

arrSort.sort( (a, b) => a - b );

alert(arrSort);


Conclusion:

Here all the example is only for integer array. Suppose If you want to sort an string array, no need to worry about above logic. Simply you can call sort method directly.







Thursday, April 5, 2018

Array Reordering - map


                      This method is really very useful and often time we will use in our project.

It calls the function for each element of the array and returns the array of results. It does not change the original array.

Syntax:

let result = arr.map(function(item, index, array) {
  // returns the new value instead of item

})

item      -   The value of the current element and its mandatory.
index    -   The array index of the current element and its an optional parameter.

array    -   The array object the current element belongs to the array and its an optional.


let lengths = ["One", "Two", "Three"];
var lengthTest = lengths.map(item => item.length)
alert(lengthTest); // 3,3,5






Wednesday, April 4, 2018

Array search - Filter

We know find method looks for a single (first) element. But filter will check all passed data and return an array.

The syntax is same as find method,

let results = arr.filter(function(item, index, array) {
  ..................
});

Example:


let usersArrOfObject = [
  {id: 1, name: "John"},
  {id: 2, name: "Pete"},
  {id: 3, name: "Mary"},
  {id: 4, name: "Maths"},
  {id: 5, name: "Mercy"}
];

let outputUsers = usersArrOfObject.filter(item => item.id < 3);

alert(outputUsers.length); // 2
console.log(outputUsers);

From the above we are passing an item and checking the condition which specifies id is less than 3. So passed data as returned as array.







Array search - find and find Index for an object

Just think, You have an array of objects. How do you find an object with the specific condition in that array?

Here, the arr.find method will do the job for you!

Syntax:

let result = arr.find(function(item, index, array) {
  ..........................
});

item - It is the element.
index  - It is its index.
array  It is the array itself.


Example :


let arr = [

    { name:"string 1", value:"this", other: "that" },

    { name:"string 2", value:"this", other: "that" }

];

let obj = arr.find(o => o.name === 'string 1');

console.log(obj);

Output:
{
  "name": "string 1",
  "value": "this",
  "other": "that"
}

If found happen , returns true and the search will be stopped, the item is returned. If nothing found, undefined is returned.

From the above I have used ES6 arrow function, arr having array of objects. Here o is the parameter (current item) and its getting name from the current and checking with our condition. If its will get match, returns true and further search will be stopped.

If nothing matching undefined will be returned.

Note:
We did not use any other parameter except item , mentioned in the syntax.


arr.findIndex 

               The arr.findIndex method is also same, but it will returns the index where the element was found instead of the element.










Array search elements

Actually lot of methods there for searching in an array.we can see those all later on next chapter.

Here we are going to see the below three methods.

      1. indexOf

      2. lastIndexOf 

      3. includes

Generally indexOf function means, you would have thought its working based on characters. But java script, here not the case. Its an item in java script.

A short intro about these all function. Let see...

Syntax:
arr.indexOf(item , from)

It returns the position of the first occurrence of a specified value in a string. If unable to find will return -1.

item - Its specifies what you are searching...
from - Its Optional. Default 0. At which position to start the search(item).


Syntax:
arr.lastIndexOf(item, from)

It looks from right to left. Means, returns the position of the last occurrence of a specified value in a string. If unable to find will return -1.

item - The string(item) what you are going to search.
from - Its Optional. The position where to start the search.

Syntax:
arr.includes(item, from)

It checks whether a string contains the characters of a specified string. This method returns true if the string contains the characters, and false if not able to find.

item - The string, what you are going to search.
from - Its an optional. Default is 0. At which position to start the search(item)

Example for indexOf:
Q: Find the first occurrence e here.


var str = "Hello world, welcome to JS";
var n = str.indexOf("e");

alert(n); // 1


Q: Search e which should start position from 5.

var str = "Hello world, welcome to javascript";
var n = str.indexOf("e", 5);

alert(n); // 14


Example for lastIndexOf:


Q: Search last occurrence  "love" from the given string.


var str = "Hello I love JS much.";
var n = str.lastIndexOf("love");
alert(n) // 8

Q: Search item "love" which should start position at 30.


var str = "Hello I love JS very much very much very much";
var find = str.lastIndexOf("very", 30);
alert(find) // 26

Example for includes:


Q: Find 'world' from below given string.


var str = "Hello world, welcome JS.";
var n1 = str.includes("world");

alert(n1); // True

Q: Find 'world' from below given string.


var str = "Hello world, welcome JS.";
var n2 = str.includes("world", 12);

alert(n2); // false