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