how to check an array is empty or not in javascript


To check the array is empty or not, we need to follow these steps

  1. Check whether the array is undefined or not.

    • first we need to check for the array is defined or not i.e initialized or not as follows
    •  
      var arr = [];
      if(arr != undefined)

  2. Check whether the array is null or not.

    • if we are getting data from remote source we need to check for null as follows

    • var arr = [];
      if(arr != undefined && arr != null)

  3. Check whether the type is object or not.

    • to avoid type related problems we need to check for the type as follows

    • var arr = [];
      if(arr != undefined && arr != null && typeof(arr) == typeof([]))

  4. Check whether the length of the array using length property.

    • If we want to check whether the array is having data or not we can use length property on array

    • var arr = [];
      if (arr != undefined && arr != null && typeof (arr) == typeof ([]) && arr.length > 0)

Full Example

var arr = [];
if (arr != undefined && arr != null && typeof (arr) == typeof ([]) && arr.length > 0) {
    //TODO: if the array has something in it
}
else {
    //TOTO: if the array is empty or null or undefined
}

 

Happy coding..!!

How/Best way to check the string is Palindrome or not in Javascript


What is palindrome

Palindrome is a word, phrase, or sequence that reads the same backwards as forwards as shown in the below example.

palindrome example

Example 1 palindrome using reverse function

var profile = 'madam';
if (profile == profile.split('').reverse().join(''))
    console.log(profile + " is a palindrome");
else
    console.log(profile + " is not a palindrome");

Using reverse is overkill because you don’t need to generate an extra string, you just need to query the existing one. The following example checks the first and last characters are the same, and then walks further inside the string checking the results each time. It returns as soon as s is not a palindrome.

The problem with the reverse approach is that it does all the work up front. It performs an expensive action on a string, then checks character by character until the strings are not equal and only then returns false if it is not a palindrome. If you are just comparing small strings all the time then this is fine, but if you want to defend yourself against bigger input then you should consider this algorithm.

Example 2 palindrome without using reverse

var profile = 'madam';

function isPalindrome(profile) {
    var n = profile.length;
    for (var i = 0; i < (n / 2) ; ++i) {
        if (profile.charAt(i) != profile.charAt(n – i – 1))
            return false;
    }
    return true;
}

var isit = isPalindrome(profile);
if(isit)
    console.log(profile + " is a palindrome");
else
    console.log(profile + " is not a palindrome");

Happy coding

How can we force clients to refresh JavaScript files?


Q: How can we force web clients to refresh or load latest version javascript files from the web server.

This is the problem most of the web developers facing after deploying their newer versions of javascript files.

We normally ask the customer to hit Ctrl + F5 to ensure that all the latest javascript files loaded from server not from the cache.

But we can solve this in different ways as follows

Solution 1: If you are maintaining javascript versioning

If you are using javascript versions, it’s easy to solve the issue. i.e we just need to add the version to javascript file path as follows

<script src="~/scripts/demojs.js?100"></script>
<script src="~/scripts/demojs.js?version=100"></script>

so If the version of the file changed then the url also change. so if the url is different than the file which is already in cache, the browser (client) will request to get latest file from the server.

So these file will render to clients as follows

Loading from cache

image

Loading from server

image

Solution 2: If you are not using versioning use Asp.Net MVC datetime object ticks

In this case we just use ticks from C# datetime object as follows

<script src="~/scripts/demojs.js?@DateTime.Now.Ticks"></script>
<script src="~/scripts/demojs.js?currentTime=@DateTime.Now.Ticks"></script>

image

Solution 3: Restart application and Recycle Application pool in IIS

Please do following steps after completion of your deployment in IIS

  1. Restart your website

image

2. Then find the applicationpool of your website and recycle it.

image

In case of Microsoft Azure websites

Screenshot_10

Thanks

Happy coding ComputerSmile

$watch and $watchCollection is not firing/working on data change in angularJS


if $watch and $watchCollection is not firing on data change we need to use 3rd parameter i.e objectEquality parameter (type of boolean)

$watch(watchExpression, listener, [objectEquality])

above statement is the $watch signature with three parameters

in these three parameters third one (objectEquality) is optional and of type boolean

Example 1:

$scope.$watch(‘userProfile.userName’,
function (newValue, oldValue) {
$scope.userName = newValue;
}, true);

Example 2:

$scope.$watch(function () {
return authenticationService.userProfile;
},
function (newValue, oldValue) {
$scope.userProfile = newValue;
}, true);

Happy CodingComputerSmile

How can I get query string values in JavaScript?


We have may plug-ins to read Query string values in JavaScript. But we don’t know what is happening inside plug-in.

let’s learn how to read Query String values with plain JavaScript.

Example URL:

Script to read Query String Value.

<script type="text/javascript">
    function getParameterByName(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }
</script>

Method Call:

  1. var postNo = getParameterByName("PostNo");//OutPut:100

How to handle Double click event of asp.net button using JQuery


Subject: Here we can Learn how to Handle Double click event of Asp.Net controls using Jquery, here i will explain with asp.net button control

If you are New to Jquery Start from here.

first take new asp.net empty website and add jquery library to website and add one asp.net webform and write following code

JQuery Script:

<script type="text/javascript">
        $(function () {
            $("input[id$=Button1]").bind({
                click: function (e) {
                    e.preventDefault();
                },
                dblclick: function () {
                    alert("DoubleClick Happed to Button");
                }
            });
        });
    </script>

CompleteCode:

<%@ Page Title="Handling DoubleClick of Asp.Net Button" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="HandlingDoubleClick.aspx.cs" Inherits="HandlingDoubleClick" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    <script src="Scripts/jquery-1.7.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("input[id$=Button1]").bind({
                click: function (e) {
                    e.preventDefault();
                },
                dblclick: function () {
                    alert("DoubleClick Happed to Button");
                    //write ur code here
                }
            });
        });
    </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:Button ID="Button1" runat="server" Text="Double click on me" />
</asp:Content>

Explanation:

Here i am explaining Example with Master pages, the reason is, when the asp.net webform renders as html in browser it will assign dynamic ids for asp.net controls while merging master page and content page. Here why asp.net assigning dynamic ids, because to avoid naming collision

so here we have to use

$("input[id$=Button1]")

this statement to get asp.net control with dynamic id

and Bind method will bind events to control, here we are binding click and double click events

Click Event:

click: function (e) {
                    e.preventDefault();
                },

in this click event we are preventing default behavior of asp.net button control, i.e preventing post back

Double click Event:

dblclick: function () {
                    alert("DoubleClick Happed to Button");
                    //write ur code here
                }

in this double click event write your code…

 

Happy Coding….

If u have any drought feel free to contact from AboutMe page