FrontendDeveloper.in

JavaScript Interview Questions

  • Question 121

    How do you check whether a string contains a substring

    There are 3 possible ways to check whether a string contains a substring or not,

    1. Using includes: ES6 provided String.prototype.includes method to test a string contains a substring
    var mainString = "hello",
    subString = "hell";
    mainString.includes(subString);
    
    1. Using indexOf: In an ES5 or older environment, you can use String.prototype.indexOf which returns the index of a substring. If the index value is not equal to -1 then it means the substring exists in the main string.
    var mainString = "hello",
    subString = "hell";
    mainString.indexOf(subString) !== -1;
    
    1. Using RegEx: The advanced solution is using Regular expression's test method(RegExp.test), which allows for testing for against regular expressions
    var mainString = "hello",
    regex = /hell/;
    regex.test(mainString);
    
  • Question 122

    How do you validate an email in javascript

    You can validate an email in javascript using regular expressions. It is recommended to do validations on the server side instead of the client side. Because the javascript can be disabled on the client side.

    function validateEmail(email) {
    var re =
    /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(String(email).toLowerCase());
    }
    

    The above regular expression accepts unicode characters.

  • Question 123

    How do you get the current url with javascript

    You can use window.location.href expression to get the current url path and you can use the same expression for updating the URL too. You can also use document.URL for read-only purposes but this solution has issues in FF.

    console.log("location.href", window.location.href); // Returns full URL
    
  • Question 124

    What are the various url properties of location object

    The below Location object properties can be used to access URL components of the page,

    1. href - The entire URL
    2. protocol - The protocol of the URL
    3. host - The hostname and port of the URL
    4. hostname - The hostname of the URL
    5. port - The port number in the URL
    6. pathname - The path name of the URL
    7. search - The query portion of the URL
    8. hash - The anchor portion of the URL
  • Question 125

    How do you get query string values in javascript

    You can use URLSearchParams to get query string values in javascript. Let's see an example to get the client code value from URL query string,

    const urlParams = new URLSearchParams(window.location.search);
    const clientCode = urlParams.get("clientCode");
    
  • Question 126

    How do you check if a key exists in an object

    You can check whether a key exists in an object or not using three approaches,

    1. Using in operator: You can use the in operator whether a key exists in an object or not
    "key" in obj;
    

    and If you want to check if a key doesn't exist, remember to use parenthesis,

    !("key" in obj);
    
    1. Using hasOwnProperty method: You can use hasOwnProperty to particularly test for properties of the object instance (and not inherited properties)
    obj.hasOwnProperty("key"); // true
    
    1. Using undefined comparison: If you access a non-existing property from an object, the result is undefined. Let’s compare the properties against undefined to determine the existence of the property.
    const user = {
    name: "John",
    };
    
    console.log(user.name !== undefined); // true
    console.log(user.nickName !== undefined); // false
    
  • Question 127

    How do you loop through or enumerate javascript object

    You can use the for-in loop to loop through javascript object. You can also make sure that the key you get is an actual property of an object, and doesn't come from the prototype using hasOwnProperty method.

    var object = {
    k1: "value1",
    k2: "value2",
    k3: "value3",
    };
    
    for (var key in object) {
    if (object.hasOwnProperty(key)) {
    console.log(key + " -> " + object[key]); // k1 -> value1 ...
    }
    }
    
  • Question 128

    How do you test for an empty object

    There are different solutions based on ECMAScript versions

    1. Using Object entries(ECMA 7+): You can use object entries length along with constructor type.
    Object.entries(obj).length === 0 && obj.constructor === Object; // Since date object length is 0, you need to check constructor check as well
    
    1. Using Object keys(ECMA 5+): You can use object keys length along with constructor type.
    Object.keys(obj).length === 0 && obj.constructor === Object; // Since date object length is 0, you need to check constructor check as well
    
    1. Using for-in with hasOwnProperty(Pre-ECMA 5): You can use a for-in loop along with hasOwnProperty.
    function isEmpty(obj) {
    for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
    return false;
    }
    }
    
    return JSON.stringify(obj) === JSON.stringify({});
    }
    
  • Question 129

    What is an arguments object

    The arguments object is an Array-like object accessible inside functions that contains the values of the arguments passed to that function. For example, let's see how to use arguments object inside sum function,

    function sum() {
    var total = 0;
    for (var i = 0, len = arguments.length; i < len; ++i) {
    total += arguments[i];
    }
    return total;
    }
    
    sum(1, 2, 3); // returns 6
    

    Note: You can't apply array methods on arguments object. But you can convert into a regular array as below.

    var argsArray = Array.prototype.slice.call(arguments);
    
  • Question 130

    How do you make first letter of the string in an uppercase

    You can create a function which uses a chain of string methods such as charAt, toUpperCase and slice methods to generate a string with the first letter in uppercase.

    function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
    }
    
  • Question 131

    What are the pros and cons of for loops

    The for-loop is a commonly used iteration syntax in javascript. It has both pros and cons

    Pros

    1. Works on every environment
    2. You can use break and continue flow control statements

    Cons

    1. Too verbose
    2. Imperative
    3. You might face off-by-one errors.
  • Question 132

    How do you display the current date in javascript

    You can use new Date() to generate a new Date object containing the current date and time. For example, let's display the current date in mm/dd/yyyy

    var today = new Date();
    var dd = String(today.getDate()).padStart(2, "0");
    var mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0!
    var yyyy = today.getFullYear();
    
    today = mm + "/" + dd + "/" + yyyy;
    document.write(today);
    
  • Question 133

    How do you compare two date objects

    You need to use date.getTime() method in order to compare unix timestamp values

    var d1 = new Date();
    var d2 = new Date(d1);
    console.log(d1.getTime() === d2.getTime()); //True
    console.log(d1 === d2); // False
    
  • Question 134

    How do you check if a string starts with another string

    You can use ECMAScript 6's String.prototype.startsWith() method to check if a string starts with another string or not. But it is not yet supported in all browsers. Let's see an example to see this usage,

    "Good morning".startsWith("Good"); // true
    "Good morning".startsWith("morning"); // false
    
  • Question 135

    How do you trim a string in javascript

    JavaScript provided a trim method on string types to trim any whitespaces present at the beginning or ending of the string.

    "  Hello World   ".trim(); //Hello World
    

    If your browser(<IE9) doesn't support this method then you can use below polyfill.

    if (!String.prototype.trim) {
    (function () {
    // Make sure we trim BOM and NBSP
    var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
    String.prototype.trim = function () {
    return this.replace(rtrim, "");
    };
    })();
    }
    
Get LinkedIn Premium at Rs 399