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

Advertisements

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 to get dropdown list or select list selected value and selected text in angularJS :: asp.net mvc


We can get dropdown list selected value or text using ng-model attribute as shown in the below example

How to get dropdown list or select list selected value and selected text in angularJS asp.net mvc

        public JsonResult GetColorsData()
        {
            List<Colors> colors = new List<Colors>()
            {
                new Colors() { Id=1,Name="Red"},
                new Colors() { Id=2,Name="White"},
                new Colors() { Id=3,Name="Blue"},
                new Colors() { Id=4,Name="Green"},
            };
            return Json(colors, JsonRequestBehavior.AllowGet);
        }

@{
    ViewBag.Title = "How to get dropdown list or select list selected value and selected text in angularJS :: asp.net mvc";
}

<h3>Colors</h3>
<script src="~/Scripts/angular.min.js"></script>

<div ng-app="ddlExample">
    <div ng-controller="ddlController">

        <select ng-model="selectedColor"
                ng-options="color.Name for color in colors track by color.Id">
        </select>

        <br/>
        Selected Color Name : {{selectedColor.Name}} <br/>
        Selected Color Id : {{selectedColor.Id}}
    </div>
</div>

<script>
    angular.module('ddlExample', [])
      .controller('ddlController', ['$scope', '$http', function ($scope, $http) {
          $http({
              method: 'Get',
              url: '/Home/GetColorsData'
          }).success(function (data, status, headers, config) {
              //adding colors to model
              $scope.colors = data;
              //set selected color
              $scope.selectedColor = $scope.colors[1];
          }).error(function (data, status, headers, config) {
              $scope.message = 'Error';
          });
      }]);
</script>

Output:

Dynamic data binding to dropdown list in angularjs mvc

Happy coding…

Dynamic Data Binding AngularJS SELECT Dropdown list in asp.net MVC


Binding dropdown list or select in web application development is very importent.

we can bind data to dropdown list in angularjs in two ways

1. using ng-options

ng-options is angularJS attribute can be used to dynamically generate a list of <option> elements for the <select> element using the array or object.

Advantages of ng-options

1. Reducing memory and increasing speed by not creating a new scope for each repeated instance.

2. providing more flexibility in how the <select>‘s model is assigned via the select as part of the comprehension expression

2. using ng-repeat

ng-repeat can be used on <option> element to generate list of options

this is not preferred way of binding dropdown list or select lsit

Example using ng-options
        public JsonResult GetColorsData()
        {
            List<Colors> colors = new List<Colors>()
            {
                new Colors() { Id=1,Name="Red"},
                new Colors() { Id=2,Name="White"},
                new Colors() { Id=3,Name="Blue"},
                new Colors() { Id=4,Name="Green"},
            };
            return Json(colors, JsonRequestBehavior.AllowGet);
        }

@{
    ViewBag.Title = "Dynamic data binding to dropdown list in angularjs mvc";
}

<h3>Colors</h3>
<script src="~/Scripts/angular.min.js"></script>

<div ng-app="ddlExample">
    <div ng-controller="ddlController">
        <select ng-model="selectedColor" ng-options="color.Name for color in colors track by color.Id"></select>
        <br/>
        Selected Color : {{selectedColor.Name}}
    </div>
</div>

<script>
    angular.module('ddlExample', [])
      .controller('ddlController', ['$scope', '$http', function ($scope, $http) {
          $http({
              method: 'Get',
              url: '/Home/GetColorsData'
          }).success(function (data, status, headers, config) {
              //adding colors to model
              $scope.colors = data;
              //set selected color
              $scope.selectedColor = $scope.colors[1];
          }).error(function (data, status, headers, config) {
              $scope.message = 'Error';
          });
      }]);
</script>

 

Output:

Dynamic data binding to dropdown list in angularjs mvc