JavaScript String slice, substring and substr Methods

JavaScript String holds the sequence of charters.
 var str = "This is Sample String"; 
To Extract portion of a String in javascript we have 3 methods avilable. They are
  • String.slice(start, end)
  • String.substring(start, end)
  • String.substr(start, length) 


String.slice()

This Method Extracts the part of a String and returns the extracted part as String.
It takes 2 arguments for start index and end index.
  • If we give negative arguments, String.slice method will extract the String from end position to start position
  • if we give single positive argument, then String.slice extracts the String from that position to the End of the String.
  • if we give single negative argument, then String.slice extracts the String from End of the String to those many characters specified in the argument.
  • If we Specify the out of index, It will return the empty String.

See below for Example of String.Slice behavior

 var str = "This is Sample String";
console.log("slice(8,14) : "+str.slice(8,14));
console.log("slice(-13,-7) : "+str.slice(-13,-7));
console.log("slice(8) : "+str.slice(8));
console.log("slice(-7) : "+str.slice(-7));
console.log("slice() : "+str.slice());
console.log("slice(50) : "+str.slice(50));


Output for Above :- 
 slice(8,14) : Sample
slice(-13,-7) : Sample
slice(8) : Sample String
slice(-7) :  String
slice() : This is Sample String
slice(50) :

String.substring()


JavaScript substring method is similar to slice, except behavior is different for negative argument.
Unlike Slice method which takes relative index from end of the String for negative arguments, substring method treats them from starting position of the String.
Say if i have a String str = "abc", and i am performaing str.substring(-3,-7), then Javascript will try to substring the str @ index between -13 and -7 and we don't have any characters at that indexes, it will return null.
However, If we use str.subgtring(-3), javaScript tries to return the SubString from -7 index to length of the String and we have String available from 0th Index, It will return the entire String.

 See below for Example of String.substring() behavior

var str = "This is Sample String";
console.log("substring(8,14) : "+str.substring(8,14));
console.log("substring(-13,-7) : "+str.substring(-13,-7));
console.log("substring(8) : "+str.substring(8));
console.log("substring(-7) : "+str.substring(-7));
console.log("substring() : "+str.substring());
console.log("substring(50) : "+str.substring(50));


 Output for Above :-
substring(8,14) : Sample
substring(-13,-7) :
substring(8) : Sample String
substring(-7) : This is Sample String
substring() : This is Sample String
substring(50) :


String.substr()


JavaScript substr method is similar to slice, except the second argument specifies the length of the string.
Also Behaviour of subStr() and Slice() methods changes based on the negative argument supplied.
If we pass only one argument and is negative to the subStr(), then it works similar like slice() method to from end of the String but it will return String with the length specified foe Ex:- str.subStr(-7) means it will return the String of 7 characters from End of the String str.
 If we pass 2 negative arguments to the substr() method, it will return the String from first argument position from end of the String to the lenght specified in second argument.

 See below for Example of String.substr() behavior for clear understanding.


var str = "This is Sample String";
console.log("substr(8,14) : "+str.substr(8,14));
console.log("substr(-11,7) : "+str.substr(-11,7));
console.log("substr(8) : "+str.substr(8));
console.log("substr(-7) : "+str.substr(-7));
console.log("substr() : "+str.substr());
console.log("substr(50) : "+str.substr(50));
 Output for Above :-
substr(8,14) : Sample String
substr(-11,7) : mple St
substr(8) : Sample String
substr(-7) :  String
substr() : This is Sample String
substr(50) :

From Above examples, we can conclude that If we want to perform operation based on indices, then we can go for slice() or subString() keeping in mind the behavior of the negative arguments. If we want to perform operation based on length then we go for substr().

For those who want to know the performance of these 3 methods here is a good jsperf comparison. http://jsperf.com/slice-vs-substr-vs-substring-methods-long-string/3

JavaScript Math object Examples and Reference

   Math is a built-in JavaScript object that has properties and methods to perform mathematical tasks. The Math object cannot be created using the new operator. It has no constructor defined. All the Properties and Methods of Math object are static. That means we no need to create object for it, we can directly access the properties and methods using Math.

JavaScript Math Properties or Constants


JavaScript Math Object has 8 Constants, They are

Math.E 

          Euler's constant and the base of natural logarithms, approximately 2.718.
Ex:-
var EulerVal = Math.E;
console.log("Euler's Value is : " + EulerVal); 
  
Output is:
  Euler's Value is : 2.718281828459045 

Math.LN2 

          This returns natural logarithm of 2
Ex:-
var Val = Math.LN2;
console.log("Val's Value is : " + Val); 
  
Output is:
  Val's Value is : 0.6931471805599453 

Math.LN10 

          This returns natural logarithm of 10
Ex:-
var Val = Math.LN10;
console.log("Val's Value is : " + Val); 
  
Output is:
  Val's Value is : 2.302585092994046 

Math.LOG2E 

          This returns base 2 logarithm of E
Ex:-
var Val = Math.LOG2E;
console.log("Val's Value is : " + Val); 
  
Output is:
  Val's Value is : 1.4426950408889634 

Math.LOG10E 

          This returns base 10 logarithm of E
Ex:-
var Val = Math.LOG10E;
console.log("Val's Value is : " + Val); 
  
Output is:
  Val's Value is : 0.4342944819032518 

Math.PI 

          This returns the ratio of the circumference of a circle to its diameter
Ex:-
var Val = Math.PI;
console.log("Val's Value is : " + Val); 
  
Output is:
  Val's Value is : 3.141592653589793 

Math.SQRT2 

          Square root of 2
Ex:-
var Val = Math.SQRT2;
console.log("Val's Value is : " + Val); 
  
Output is:
  Val's Value is : 1.4142135623730951 

Math.SQRT1_2 

          Square root of 1/2
Ex:-
var Val = Math.SQRT1_2;
console.log("Val's Value is : " + Val); 
  
Output is:
  Val's Value is : 0.7071067811865476 

JavaScript Math Object Methods


Below are the list of JavaScript Math Object methods their use and examples.

Math.abs(x) 

          This method returns the absolute value of a number(x)
Ex:-
var val = Math.abs(-1);
console.log("Value is : " + val); 

val = Math.abs(0);
console.log("Value is : " + val); 

val = Math.abs(2);
console.log("Value is : " + val); 
  
Output is:
Value is : 1
Value is : 0
Value is : 2

Math.acos(x) 

          This method returns returns the arccosine of x, in radians
Returns a numeric value between 0 and PI radians for x between -1 and 1. If the value of number is outside this range, it returns NaN. Ex:-
var val = Math.acos(-1);
console.log("Value is : " + val); 

val = Math.acos(0);
console.log("Value is : " + val); 

val = Math.acos(2);
console.log("Value is : " + val); 
  
Output is:
Value is : 3.141592653589793
Value is : 1.5707963267948966
Value is : NaN

Math.asin(x) 

          This method returns the arcsine of x, in radians
Returns a numeric value between -pi/2 and pi/2 radians for x between -1 and 1. If the value of number is outside this range, it returns NaN. Ex:-
var val = Math.asin(-1);
console.log("Value is : " + val); 

val = Math.asin(0);
console.log("Value is : " + val); 

val = Math.asin(2);
console.log("Value is : " + val); 
  
Output is:
Value is : -1.5707963267948966
Value is : 0
Value is : NaN

Math.atan(x) 

          This method returns the arctangent in radians of a number. The atan method returns a numeric value between -pi/2 and pi/2 radians
Ex:-
var val = Math.atan(-1);
console.log("Value is : " + val); 

val = Math.atan(0);
console.log("Value is : " + val); 

val = Math.atan(2);
console.log("Value is : " + val); 
  
Output is:
Value is : -0.7853981633974483
Value is : 0
Value is : 1.1071487177940904

Math.atan2(x,y) 

          This method returns the arctangent of the quotient of its arguments. The atan2 method returns a numeric value between -pi and pi
Ex:-
var val = Math.atan2(30,60);
console.log("Value is : " + val); 
  
Output is:
Value is : 0.4636476090008061

Math.ceil(x) 

          This method returns the smallest integer greater than or equal to a number
Ex:-
var val = Math.ceil(1.25);
console.log("Value is : " + val); 

var val = Math.ceil(1.55);
console.log("Value is : " + val); 
  
Output is:
Value is : 2
Value is : 2

Math.cos(x) 

          This method returns the cosine of a number. The cos method returns a numeric value between -1 and 1
Ex:-
var val = Math.cos(30);
console.log("Value is : " + val); 

var val = Math.cos(60);
console.log("Value is : " + val); 
  
Output is:
Value is : 0.15425144988758405
Value is : -0.9524129804151563

Math.exp(x) 

         This method returns Ex, where x is the argument, and E is Euler's constant, the base of the natural logarithms
Ex:-
var val = Math.exp(1);
console.log("Value is : " + val); 

var val = Math.exp(2);
console.log("Value is : " + val); 
  
Output is:
Value is : 2.718281828459045
Value is : 7.38905609893065

Math.floor(x) 

         This method returns the largest integer less than or equal to a number
Ex:-
var val = Math.floor(1.25);
console.log("Value is : " + val); 

var val = Math.floor(1.55);
console.log("Value is : " + val); 
  
Output is:
Value is : 1
Value is : 1

Math.log(x) 

         This method returns the natural logarithm (base E) of a number. If the value of number is negative, the return value is always NaN
Ex:-
var val = Math.log(1.25);
console.log("Value is : " + val); 

var val = Math.log(1.55);
console.log("Value is : " + val); 
  
Output is:
Value is : 0.22314355131420976
Value is : 0.4382549309311553

Math.max(val1, val2, ... valN) 

         This method returns the largest of zero or more numbers. If no arguments are given, the results is Infinity
Ex:-
var val = Math.max(1.25, 2.5);
console.log("Value is : " + val); 

var val = Math.max(1, 2, 5);
console.log("Value is : " + val); 

var val = Math.max();
console.log("Value is : " + val); 
Output is:
Value is : 2.5
Value is : 5
Value is : -Infinity

Math.min(val1, val2, ... valN) 

         This method returns the smallest of zero or more numbers. If no arguments are given, the results is Infinity
Ex:-
var val = Math.min(1.25, 2.5);
console.log("Value is : " + val); 

var val = Math.min(1, 2, 5);
console.log("Value is : " + val); 

var val = Math.min();
console.log("Value is : " + val); 
Output is:
Value is : 1.25
Value is : 1
Value is : Infinity

Math.pow(base, exponent ) 

         This method returns the base to the exponent power
Ex:-
var val = Math.pow(1.25, 2.5);
console.log("Value is : " + val); 

var val = Math.pow(1, 2);
console.log("Value is : " + val); 

var val = Math.pow();
console.log("Value is : " + val); 
Output is:
Value is : 1.7469281074217107
Value is : 1
Value is : NaN

Math.random() 

         This method returns a random number between 0 (inclusive) and 1 (exclusive)
Ex:-
var val = Math.random();
console.log("Value is : " + val); 
Output is:
Value is : 0.49192287446931005

Math.round(x) 

         This method returns the value of a number rounded to the nearest integer
Ex:-
var val = Math.round(1.25);
console.log("Value is : " + val); 

var val = Math.round(1.55);
console.log("Value is : " + val); 
Output is:
Value is : 1
Value is : 2

Math.sin(x) 

         This method returns the sine of a number. The sin method returns a numeric value between -1 and 1
Ex:-
var val = Math.sin(1);
console.log("Value is : " + val); 

var val = Math.sin(60);
console.log("Value is : " + val); 
Output is:
Value is : 0.8414709848078965
Value is : -0.3048106211022167

Math.sqrt(x) 

         This method returns the square root of a number. If the value of number is negative, sqrt returns NaN
Ex:-
var val = Math.sqrt(24);
console.log("Value is : " + val); 

var val = Math.sqrt(-24);
console.log("Value is : " + val); 
Output is:
Value is : 4.898979485566356
Value is : NaN

Math.tan(x) 

         This method returns the tangent of a number. The tan method returns a numeric value that represents the tangent of the angle
Ex:-
var val = Math.tan(30);
console.log("Value is : " + val); 

var val = Math.tan(90);
console.log("Value is : " + val); 
Output is:
Value is : -6.405331196646276
Value is : -1.995200412208242

Setup Node.js and Npm 'Proxy' config if you are behind a proxy


Are you getting below error while using the npm?

"Error: connect ECONNREFUSED" and "If you are behind a proxy, please make sure that the
'proxy' config is set properly.  See: 'npm help config'".  As shown in below image


Node.js proxy Error

If you get above error, then you are proxy might not set properly for npm.

To Set the proxy for the Node.js, use below syntax
npm config set proxy "http://<PROXY_SERVER>:<PORT>"

We can also Pass username and password, If Proxy needs it like below
npm config set proxy http://username:password@<PROXY_SERVER>:<PORT>

In some cases, we might be using special characters for our passwords(like @ in password), in this case above syntax wont work. So its better to use double quotes (") for username:password as shown below.
npm config set proxy http://"username:password"@<PROXY_SERVER>:<PORT>

We can also use below to set https_proxy
npm config set https-proxy http://<PROXY_SERVER>:<PORT>
 

Arrays in JavaScript with Examples


Arrays

 An Array is an Object which stores multiple elements in it. it can be same type or different types.

Creating Arrays in JavaScript

    In JavaScript we can create array in 2 ways
    1. Using Array Literal Notation
    2. Using Array() Constructor

Creating Arrays using Array Literal Notation

    In this method of creating Array we simply use Square brackets and then put all the elements inside this using comma separated.
    Ex:-
  var arrLit1 = [];    //This is Empty Array
  var arrLit2 = [1,2,3];   //Array with numbers and length 3
  var arrLit3 = ["Foo","Bar"];//Array with Strings and length 2
 

Creating Arrays using Array() Constructor

    In this method We need to explicitly define the Array() with javascript's "new" Keyword
For the Array() Constructor, If we pass don't pass any arguments, then Array will be created with Zero length. If we pass one argument(Number) to the Array(), Array will be created with the passed argument as length. If we specify multiple arguments inside the constructor, then array will be created with those arguments and number of arguments wil be the lenght of the array.
   
    Ex:-
  var arr1 = new Array();   //This is Empty Array
  var arr2 = new Array(10);   //Array with length 10
  var arr3 = new Array("foo");  //Here Array with foo element created which is of length 1
  var arr4 = new Array(1,4,3); //Array with specified elements and length 3
 
       
We can create An array with mixed data types as shown in below example

 var arr3 = new Array("ss",1);
   

Array Length

    "length" is the property of Array. It will return the number of elements it currently holding or the length defined using the Array() constructor while creating the array.

    Ex:-
  var arr = new Array("foo","bar");
  console.log(arr.length) ; // It will print 2 in the console.
  
  var arr = new Array(10);
  console.log(arr.length) ; // It will print 10 in the console.
 

How to Access Contents of an array?

    To access the contents of an array in JavaScript we need to use the index.
    INDEX specifies the position of the element in the Array. The first element has an index of 0.
   
    Ex:-
  var arr = new Array("foo","bar");
  console.log(arr[0]); //prints "foo"
  arr[0] = "newVal";  //0 th index element(1st element) value replaced with "newVal"
 

JavaScript Timers - setTimeout() and setInterval() functions



The setTimeout() and setInterval() methods allows to schedule timer-based callbacks in JavaScript

setTimeout() 

Executes a callback function after a specified number of milliseconds.

Javascript setTimeout takes 2 parameters, one is Callback function and then the delay in Milliseconds.
The syntax is:
var timerId = setTimeout(callback, delay)
setTimeout() Example:
function foo() {
   alert('Hi')
}
setTimeout(foo, 1000);

We can also Cancel the execution of the setTimeout in JavaScript.
To Cancel the Execution we need to store the value returned by setTimeout and then call clearTimeout().

Example below for Cancelling the Clear timeout.
    function foo() { 
      alert('Hi');
    }
    var timeID = setTimeout(foo, 1000);
    clearTimeout(timeID);

setInterval() 

Executes a callback function at specified time intervals.
The syntax is:
    var timerId = setInterval(callback, interval);
setInterval() Example:
    function foo() { 
      alert('Hi');
    }
    setInterval(foo, 1000);

For setTimeout() we have cancel function clearTimeout(). for setInterval() also we have Cancel function available clearInterval().
Same like setTimeout(), to Cancel the Execution of setInterval(), we need to store the value returned by setInterval and then call setInterval().

Example below for Cancelling the Clear timeout.

    function foo() { 
      alert('Hi');
    }
    var timeID = setInterval(foo, 1000);
    clearInterval(timeID);