Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

String Concatenation in JavaScript Explained with Examples

String Concatenation is the process in which two or more Strings are joined to make a Single String. Different programming languages have different implementations for String Concatenation.
In this post we are going to see How to Implement String Concatenation in JavaScript using different methods like

  • String Concatenation in JavaScript with + operator
  • String Concatenation in JavaScript using for loop
  • String Concatenation in JavaScript with Variables

We are going to see String Concatenation in JavaScript with different examples for better understanding.

String Concatenation in JavaScript with + operator

In JavaScript easiest way to concatenate 2 strings is by using '+' Operator. This is the most used traditional method to concatenate 2 strings.

For Example
var str1 = "JavaScript";
var str2 = "foo";
var str3 = str1+str2;
console.log(str3); 
Output in Console :
"JavaScriptfoo"
Another way to append 2 String in Javascript using + operator is like below
var str1 = "JavaScript";
str1 += "Foo"
console.log(str1); 
Output in Console :
"JavaScriptFoo"

String Concatenation in Javascript using for loop

String Concatenation in JS can be achieved using loop controls.

When do we need to use loop to concatenate strings?
There could be many reasons based on our requirements to use the loops to concatenate different strings. So, one basic and frequently used reason for it is, suppose we have an array of strings and want to concatenate them to form a final Single String. As we don't know the length of the string array, we cannot use the + operator directly on array of strings and readability of the code decrease. The Simplest and Easiest way is to use 'for' loop on the array of strings and concatenate them using + operator. let us look at a simple example to concatenate a String Array in javascript .

var arr = ["Java","Script","Foo"];
var finalString = ""; 
for(var x=0; x<arr.length; x++)
{
    finalString += arr[x];
}
console.log(finalString) ;
Output in Console :
"JavaScriptFoo"

String Concatenation in JavaScript with Variables

Well, Concatenating 2 or more variables is same as "String Concatenation in JavaScript with + operator",  which we discussed already. Then why we need to understand it separately? There is a reason for it. Using + operator between two strings simply results a single final string. But what If we do operation on JavaScript variables?
As we all know Javascript variables can hold any type of data like String, Numbers, Boolean etc,we cannot easily determine which type of data a particular variable holding unless we do some checks on it like isNAN etc..
So If we do + operator on 2 different type of variables, actual results would be different than expected results

For Example

If one variable contains String and another Number, then output is String
var str1 = "JavaScript"; 
var str2 = 2;
var str3 = str1+str2;
console.log(str3); 
Output in Console :
"JavaScript2"
If both variables are Numbers, then output is a Number
var str1 = 3; 
var str2 = 2;
var str3 = str1+str2;
console.log(str3); 
Output in Console :
"5"
If both variables are Numbers, but used double-quote while assigning numbers, then output is a String
var str1 = "3"; 
var str2 = "2";
var str3 = str1+str2;
console.log(str3); 
Output in Console :
"32"

So, whenever we do String Concatenation with JavaScript variables, we should be careful about their data types. Otherwise we may get unexpected results.

Find More Details about String Concatenation In JavaScript here http://javascriptfoo.blogspot.in/search/label/Concatenation

How to check if a String Contains a Substring in Javascript

 In many Scenarios we may need to write the javascript code to check If a String Contains a give SubString.

Though there are many methods available to find a substring in JavaScript, Below are the 2 popular ways to check if a String contains SubString.
  • Regular expression
  • indexof

Regular expression

Using Regular Expressions to find a Substring is more appropriate way compared to indexof. because you can use specific pattern to search a string, which you cannot do using indexof.

Let us see some example on Regular Expression.
 Regular Expression Can be created using any of the follwing way

Using litteral Expression  var re = /ab+c/; 
or using RegExp Object     var re = new RegExp("ab+c");

Below is the Simple Example to check If a String Contains the another String


var str = "javascriptfoo";
var re = new RegExp("foo");
console.log(re.test(str));
Above code will return true.

Using indexof

indexof is built in JavaScript String function, which will return the index of a substring If it contains, If it does not contain it returns -1. It is the Simplest function to check If a String contains a Substing.

Example:-
var str="Javascriptfoo";
var str1 = "foo";
console.log( str.indexOf(str1));
Above code prints 10. So we can add check for "-1", if it is not -1 then String contains the substring and If it is "-1", then substring not present in the given string.

To find different ways of using Regular expression This Mozilla article is very good for reference purpose.

What is a CDN and How to load jQuery from CDN with Fallback?

What is a CDN ? 

CDN is an acronym for Content Delivery Network.
From wiki "A content delivery network or content distribution network (CDN) is a large distributed system of servers deployed in multiple data centers across the Internet. The goal of a CDN is to serve content to end-users with high availability and high performance."

As a developer  we mostly use CDNs for loading some JavaScript releated JS plugins and frame works like jQuery, Dojo, AngulaJS etc.. However CDN Not only used for downloading text/Script files but Its major use now a days is downloading objects like media files, software, documents etc.., applications like e-commerce, portals And also for live streaming media.

Which are the popular jQuery CDN ?

In this post we want to concentrate on jQuery related CDNs only so I ll be listing only jQuery related CDN sources mainly. You can use them in your application.

CDNs can offer a performance benefit by hosting jQuery on servers spread across the globe. This also offers an advantage that if the visitor to your webpage has already downloaded a copy of jQuery from the same CDN, it won't have to be re-downloaded.
Popular CDNs and their URLs

How to load jQuery locally when CDN fails?

There May be Situations where JavaScript file from CDN May not be loaded. There can be any reason for it as i mentioned it in my blog Here How to Check If JQuery Library Loaded?
WHat to do in this situation? Its simple just check If the jQuery library is loaded or not using This method and add the local JS file in Else condition as shown below.


That is it. Isn't it that simple???

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

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);