FrontendDeveloper.in

JavaScript Interview Questions

  • Question 286

    How do you check whether or not an array includes a particular value

    The Array#includes() method is used to determine whether an array includes a particular value among its entries by returning either true or false. Let's see an example to find an element(numeric and string) within an array.

    var numericArray = [1, 2, 3, 4];
    console.log(numericArray.includes(3)); // true
    
    var stringArray = ["green", "yellow", "blue"];
    console.log(stringArray.includes("blue")); //true
    
  • Question 287

    How do you compare scalar arrays

    You can use length and every method of arrays to compare two scalars (compared directly using ===) arrays. The combination of these expressions can give the expected result,

    const arrayFirst = [1, 2, 3, 4, 5];
    const arraySecond = [1, 2, 3, 4, 5];
    console.log(
    arrayFirst.length === arraySecond.length &&
    arrayFirst.every((value, index) => value === arraySecond[index])
    ); // true
    

    If you would like to compare arrays irrespective of order then you should sort them before,

    const arrayFirst = [2, 3, 1, 4, 5];
    const arraySecond = [1, 2, 3, 4, 5];
    console.log(
    arrayFirst.length === arraySecond.length &&
    arrayFirst
    .sort()
    .every((value, index) => value === arraySecond[index])
    ); //true
    
  • Question 288

    How to get the value from get parameters

    The new URL() object accepts the url string and searchParams property of this object can be used to access the get parameters.

    let urlString = "http://www.some-domain.com/about.html?x=1&y=2&z=3"; //window.location.href
    let url = new URL(urlString);
    let parameterZ = url.searchParams.get("z");
    console.log(parameterZ); // 3
    
  • Question 289

    How do you print numbers with commas as thousand separators

    You can use the Number.prototype.toLocaleString() method which returns a string with a language-sensitive representation such as thousand separator, currency etc. of this number.

    function convertToThousandFormat(x) {
    return x.toLocaleString(); // 12,345.679
    }
    
    console.log(convertToThousandFormat(12345.6789));
    
  • Question 290

    What is the difference between java and javascript

    Both are totally unrelated programming languages and no relation between them. Java is statically typed, compiled, runs on its own VM. Whereas JavaScript is dynamically typed, interpreted, and runs in a browser and nodejs environments. Let's see the major differences in a tabular format,

    FeatureJavaJavaScript
    TypedIt's a strongly typed languageIt's a dynamic typed language
    ParadigmObject oriented programmingPrototype based programming
    ScopingBlock scopedFunction-scoped, block scoped since ES6
    ConcurrencyThread basedevent based
  • Question 291

    Does JavaScript support namespaces

    JavaScript doesn’t support namespaces by default. So if you create any element (function, method, object, variable) then it becomes global and pollutes the global namespace. Let's take an example of defining two functions without any namespace,

    function func1() {
    console.log("This is a first definition");
    }
    function func1() {
    console.log("This is a second definition");
    }
    func1(); // This is a second definition
    

    It always calls the second function definition. In this case, namespaces will solve the name collision problem.

  • Question 292

    How do you declare a namespace

    Even though JavaScript lacks namespaces, we can use Objects, an IIFE (Immediately Invoked Function Expression) or let/const to create namespaces.

    1. Using Object Literal Notation: Let's wrap variables and functions inside an Object literal which acts as a namespace. After that you can access them using object notation
    var namespaceOne = {
    function func1() {
    console.log("This is a first definition");
    }
    }
    var namespaceTwo = {
    function func1() {
    console.log("This is a second definition");
    }
    }
    namespaceOne.func1(); // This is a first definition
    namespaceTwo.func1(); // This is a second definition
    
    1. Using IIFE (Immediately invoked function expression): The outer pair of parentheses of IIFE creates a local scope for all the code inside of it and makes the anonymous function a function expression. Due to that, you can create the same function in two different function expressions to act as a namespace.
    (function () {
    function fun1() {
    console.log("This is a first definition");
    }
    fun1();
    })();
    
    (function () {
    function fun1() {
    console.log("This is a second definition");
    }
    fun1();
    })();
    
    1. Using a block and a let/const declaration: In ECMAScript 6, you can simply use a block and a let declaration to restrict the scope of a variable to a block.
    {
    let myFunction = function fun1() {
    console.log("This is a first definition");
    };
    myFunction();
    }
    //myFunction(): ReferenceError: myFunction is not defined.
    
    {
    let myFunction = function fun1() {
    console.log("This is a second definition");
    };
    myFunction();
    }
    //myFunction(): ReferenceError: myFunction is not defined.
    
  • Question 293

    How do you invoke javascript code in an iframe from the parent page

    Initially iFrame needs to be accessed using either document.getElementBy or window.frames. After that contentWindow property of iFrame gives the access for targetFunction

    document.getElementById("targetFrame").contentWindow.targetFunction();
    window.frames[0].frameElement.contentWindow.targetFunction(); // Accessing iframe this way may not work in latest versions chrome and firefox
    
  • Question 294

    How do you get the timezone offset of a date object

    You can use the getTimezoneOffset method of the date object. This method returns the time zone difference, in minutes, from current locale (host system settings) to UTC

    var offset = new Date().getTimezoneOffset();
    console.log(offset); // -480
    
  • Question 295

    How do you load CSS and JS files dynamically

    You can create both link and script elements in the DOM and append them as child to head tag. Let's create a function to add script and style resources as below,

    function loadAssets(filename, filetype) {
    if (filetype == "css") {
    // External CSS file
    var fileReference = document.createElement("link");
    fileReference.setAttribute("rel", "stylesheet");
    fileReference.setAttribute("type", "text/css");
    fileReference.setAttribute("href", filename);
    } else if (filetype == "js") {
    // External JavaScript file
    var fileReference = document.createElement("script");
    fileReference.setAttribute("type", "text/javascript");
    fileReference.setAttribute("src", filename);
    }
    if (typeof fileReference != "undefined")
    document.getElementsByTagName("head")[0].appendChild(fileReference);
    }
    
  • Question 296

    What are the different methods to find HTML elements in DOM

    If you want to access any element in an HTML page, you need to start with accessing the document object. Later you can use any of the below methods to find the HTML element,

    1. document.getElementById(id): It finds an element by Id
    2. document.getElementsByTagName(name): It finds an element by tag name (returns an node list)
    3. document.getElementsByClassName(name): It finds an element by class name (returns an node list)
    4. document.querySelector(cssSelector): It finds an element by css selector
    5. document.querySelectorAll(cssSelector): It finds all elements by css selector (returns a node list)
  • Question 297

    What is jQuery

    jQuery is a popular cross-browser JavaScript library that provides Document Object Model (DOM) traversal, event handling, animations and AJAX interactions by minimizing the discrepancies across browsers. It is widely famous with its philosophy of “Write less, do more”. For example, you can display welcome message on the page load using jQuery as below,

    $(document).ready(function () {
    // It selects the document and apply the function on page load
    alert("Welcome to jQuery world");
    });
    

    Note: You can download it from jquery's official site or install it from CDNs, like google.

  • Question 298

    What is V8 JavaScript engine

    V8 is an open source high-performance JavaScript engine used by the Google Chrome browser, written in C++. It is also being used in the node.js project. It implements ECMAScript and WebAssembly, and runs on Windows 7 or later, macOS 10.12+, and Linux systems that use x64, IA-32, ARM, or MIPS processors. Note: It can run standalone, or can be embedded into any C++ application.

  • Question 299

    Why do we call javascript as dynamic language

    JavaScript is a loosely typed or a dynamic language because variables in JavaScript are not directly associated with any particular value type, and any variable can be assigned/reassigned with values of all types.

    let age = 50; // age is a number now
    age = "old"; // age is a string now
    age = true; // age is a boolean
    
  • Question 300

    What is a void operator

    The void operator evaluates the given expression and then returns undefined (i.e, without returning value). The syntax would be as below,

    void expression;
    void expression;
    

    Let's display a message without any redirection or reload

    Click here to see a message
    

    Note: This operator is often used to obtain the undefined primitive value, using void(0). Also it can be used to call asynchronous functions without waiting for the result.

Get LinkedIn Premium at Rs 399