Part-3 : 500 JavaScript Important Questions with Answers and Explanation

Part-3 : 500 JavaScript Important Questions with Answers and Explanation

201-300 JS questions

·

40 min read

JavaScript Interview Questions & Answers

Table of Contents

No.Questions
201How can you get the list of keys of any object
202How do you create an object with prototype
203What is a WeakSet
204What are the differences between WeakSet and Set
205List down the collection of methods available on WeakSet
206What is a WeakMap
207What are the differences between WeakMap and Map
208List down the collection of methods available on WeakMap
209What is the purpose of uneval
210How do you encode an URL
211How do you decode an URL
212How do you print the contents of web page
213What is the difference between uneval and eval
214What is an anonymous function
215What is the precedence order between local and global variables
216What are javascript accessors
217How do you define property on Object constructor
218What is the difference between get and defineProperty
219What are the advantages of Getters and Setters
220Can I add getters and setters using defineProperty method
221What is the purpose of switch-case
222What are the conventions to be followed for the usage of swtich case
223What are primitive data types
224What are the different ways to access object properties
225What are the function parameter rules
226What is an error object
227When you get a syntax error
228What are the different error names from error object
229What are the various statements in error handling
230What are the two types of loops in javascript
231What is nodejs
232What is an Intl object
233How do you perform language specific date and time formatting
234What is an Iterator
235How does synchronous iteration works
236What is an event loop
237What is call stack
238What is an event queue
239What is a decorator
240What are the properties of Intl object
241What is an Unary operator
242How do you sort elements in an array
243What is the purpose of compareFunction while sorting arrays
244How do you reversing an array
245How do you find min and max value in an array
246How do you find min and max values without Math functions
247What is an empty statement and purpose of it
248How do you get meta data of a module
249What is a comma operator
250What is the advantage of a comma operator
251What is typescript
252What are the differences between javascript and typescript
253What are the advantages of typescript over javascript
254What is an object initializer
255What is a constructor method
256What happens if you write constructor more than once in a class
257How do you call the constructor of a parent class
258How do you get the prototype of an object
259What happens If I pass string type for getPrototype method
260How do you set prototype of one object to another
261How do you check whether an object can be extendable or not
262How do you prevent an object to extend
263What are the different ways to make an object non-extensible
264How do you define multiple properties on an object
265What is MEAN in javascript
266What Is Obfuscation in javascript
267Why do you need Obfuscation
268What is Minification
269What are the advantages of minification
270What are the differences between Obfuscation and Encryption
271What are the common tools used for minification
272How do you perform form validation using javascript
273How do you perform form validation without javascript
274What are the DOM methods available for constraint validation
275What are the available constraint validation DOM properties
276What are the list of validity properties
277Give an example usage of rangeOverflow property
278Is enums feature available in javascript
279What is an enum
280How do you list all properties of an object
281How do you get property descriptors of an object
282What are the attributes provided by a property descriptor
283How do you extend classes
284How do I modify the url without reloading the page
285How do you check whether an array includes a particular value or not
286How do you compare scalar arrays
287How to get the value from get parameters
288How do you print numbers with commas as thousand separators
289What is the difference between java and javascript
290Is javascript supports namespace
291How do you declare namespace
292How do you invoke javascript code in an iframe from parent page
293How do get the timezone offset from date
294How do you load CSS and JS files dynamically
295What are the different methods to find HTML elements in DOM
296What is jQuery
297What is V8 JavaScript engine
298Why do we call javascript as dynamic language
299What is a void operator
300How to set the cursor to wait
  1. How can you get the list of keys of any object

    You can use the Object.keys() method which is used to return an array of a given object's own property names, in the same order as we get with a normal loop. For example, you can get the keys of a user object,

    const user = {
      name: 'John',
      gender: 'male',
      age: 40
    };
    
    console.log(Object.keys(user)); //['name', 'gender', 'age']
    

    ⬆ Back to Top

  2. How do you create an object with prototype

    The Object.create() method is used to create a new object with the specified prototype object and properties. i.e, It uses an existing object as the prototype of the newly created object. It returns a new object with the specified prototype object and properties.

     const user = {
       name: 'John',
       printInfo: function () {
         console.log(`My name is ${this.name}.`);
       }
     };
    
     const admin = Object.create(user);
    
     admin.name = "Nick"; // Remember that "name" is a property set on "admin" but not on "user" object
    
     admin.printInfo(); // My name is Nick
    

    ⬆ Back to Top

  3. What is a WeakSet

    WeakSet is used to store a collection of weakly(weak references) held objects. The syntax would be as follows,

    new WeakSet([iterable]);
    

    Let's see the below example to explain it's behavior,

    var ws = new WeakSet();
    var user = {};
    ws.add(user);
    ws.has(user);    // true
    ws.delete(user); // removes user from the set
    ws.has(user);    // false, user has been removed
    

    ⬆ Back to Top

  4. What are the differences between WeakSet and Set

    The main difference is that references to objects in Set are strong while references to objects in WeakSet are weak. i.e, An object in WeakSet can be garbage collected if there is no other reference to it. Other differences are,

    1. Sets can store any value Whereas WeakSets can store only collections of objects
    2. WeakSet does not have size property unlike Set
    3. WeakSet does not have methods such as clear, keys, values, entries, forEach.
    4. WeakSet is not iterable.

    ⬆ Back to Top

  5. List down the collection of methods available on WeakSet

    Below are the list of methods available on WeakSet,

    1. add(value): A new object is appended with the given value to the weakset
    2. delete(value): Deletes the value from the WeakSet collection.
    3. has(value): It returns true if the value is present in the WeakSet Collection, otherwise it returns false.
    4. length(): It returns the length of weakSetObject Let's see the functionality of all the above methods in an example,
    var weakSetObject = new WeakSet();
    var firstObject = {};
    var secondObject = {};
    // add(value)
    weakSetObject.add(firstObject);
    weakSetObject.add(secondObject);
    console.log(weakSetObject.has(firstObject)); //true
    console.log(weakSetObject.length()); //2
    weakSetObject.delete(secondObject);
    

    ⬆ Back to Top

  6. What is a WeakMap

    The WeakMap object is a collection of key/value pairs in which the keys are weakly referenced. In this case, keys must be objects and the values can be arbitrary values. The syntax is looking like as below,

    new WeakMap([iterable])
    

    Let's see the below example to explain it's behavior,

     var ws = new WeakMap();
     var user = {};
     ws.set(user);
     ws.has(user);    // true
     ws.delete(user); // removes user from the map
     ws.has(user);    // false, user has been removed
    

    ⬆ Back to Top

  7. What are the differences between WeakMap and Map

    The main difference is that references to key objects in Map are strong while references to key objects in WeakMap are weak. i.e, A key object in WeakMap can be garbage collected if there is no other reference to it. Other differences are,

    1. Maps can store any key type Whereas WeakMaps can store only collections of key objects
    2. WeakMap does not have size property unlike Map
    3. WeakMap does not have methods such as clear, keys, values, entries, forEach.
    4. WeakMap is not iterable.

    ⬆ Back to Top

  8. List down the collection of methods available on WeakMap

    Below are the list of methods available on WeakMap,

    1. set(key, value): Sets the value for the key in the WeakMap object. Returns the WeakMap object.
    2. delete(key): Removes any value associated to the key.
    3. has(key): Returns a Boolean asserting whether a value has been associated to the key in the WeakMap object or not.
    4. get(key): Returns the value associated to the key, or undefined if there is none. Let's see the functionality of all the above methods in an example,
    var weakMapObject = new WeakMap();
    var firstObject = {};
    var secondObject = {};
    // set(key, value)
    weakMapObject.set(firstObject, 'John');
    weakMapObject.set(secondObject, 100);
    console.log(weakMapObject.has(firstObject)); //true
    console.log(weakMapObject.get(firstObject)); // John
    weakMapObject.delete(secondObject);
    

    ⬆ Back to Top

  9. What is the purpose of uneval

    The uneval() is an inbuilt function which is used to create a string representation of the source code of an Object. It is a top-level function and is not associated with any object. Let's see the below example to know more about it's functionality,

    var a = 1;
    uneval(a); // returns a String containing 1
    uneval(function user() {}); // returns "(function user(){})"
    

    ⬆ Back to Top

  10. How do you encode an URL

    The encodeURI() function is used to encode complete URI which has special characters except (, / ? : @ & = + $ #) characters.

    var uri = 'https://mozilla.org/?x=шеллы';
    var encoded = encodeURI(uri);
    console.log(encoded); // https://mozilla.org/?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B
    

    ⬆ Back to Top

  11. How do you decode an URL

    The decodeURI() function is used to decode a Uniform Resource Identifier (URI) previously created by encodeURI().

     var uri = 'https://mozilla.org/?x=шеллы';
     var encoded = encodeURI(uri);
     console.log(encoded); // https://mozilla.org/?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B
    try {
      console.log(decodeURI(encoded)); // "https://mozilla.org/?x=шеллы"
    } catch(e) { // catches a malformed URI
      console.error(e);
    }
    

    ⬆ Back to Top

  12. How do you print the contents of web page

    The window object provided a print() method which is used to print the contents of the current window. It opens a Print dialog box which lets you choose between various printing options. Let's see the usage of print method in an example,

       <input type="button" value="Print" onclick="window.print()" />
    

    Note: In most browsers, it will block while the print dialog is open.

    ⬆ Back to Top

  13. What is the difference between uneval and eval

    The uneval function returns the source of a given object; whereas the eval function does the opposite, by evaluating that source code in a different memory area. Let's see an example to clarify the difference,

    var msg = uneval(function greeting() { return 'Hello, Good morning'; });
    var greeting = eval(msg);
    greeting(); // returns "Hello, Good morning"
    

    ⬆ Back to Top

  14. What is an anonymous function

    An anonymous function is a function without a name! Anonymous functions are commonly assigned to a variable name or used as a callback function. The syntax would be as below,

    function (optionalParameters) {
      //do something
    }
    
    const myFunction = function(){ //Anonymous function assigned to a variable
      //do something
    };
    
    [1, 2, 3].map(function(element){ //Anonymous function used as a callback function
      //do something
    });
    

    Let's see the above anonymous function in an example,

    var x = function (a, b) {return a * b};
    var z = x(5, 10);
    console.log(z); // 50
    

    ⬆ Back to Top

  15. What is the precedence order between local and global variables

    A local variable takes precedence over a global variable with the same name. Let's see this behavior in an example.

    var msg = "Good morning";
    function greeting() {
       msg = "Good Evening";
       console.log(msg);
    }
    greeting();
    

    ⬆ Back to Top

  16. What are javascript accessors

    ECMAScript 5 introduced javascript object accessors or computed properties through getters and setters. Getters uses the get keyword whereas Setters uses the set keyword.

    var user = {
      firstName: "John",
      lastName : "Abraham",
      language : "en",
      get lang() {
        return this.language;
      }
      set lang(lang) {
      this.language = lang;
      }
    };
    console.log(user.lang); // getter access lang as en
    user.lang = 'fr';
    console.log(user.lang); // setter used to set lang as fr
    

    ⬆ Back to Top

  17. How do you define property on Object constructor

    The Object.defineProperty() static method is used to define a new property directly on an object, or modify an existing property on an object, and returns the object. Let's see an example to know how to define property,

    const newObject = {};
    
    Object.defineProperty(newObject, 'newProperty', {
      value: 100,
      writable: false
    });
    
    console.log(newObject.newProperty); // 100
    
    newObject.newProperty = 200; // It throws an error in strict mode due to writable setting
    

    ⬆ Back to Top

  18. What is the difference between get and defineProperty

    Both have similar results until unless you use classes. If you use get the property will be defined on the prototype of the object whereas using Object.defineProperty() the property will be defined on the instance it is applied to.

    ⬆ Back to Top

  19. What are the advantages of Getters and Setters

    Below are the list of benefits of Getters and Setters,

    1. They provide simpler syntax
    2. They are used for defining computed properties, or accessors in JS.
    3. Useful to provide equivalence relation between properties and methods
    4. They can provide better data quality
    5. Useful for doing things behind the scenes with the encapsulated logic.

    ⬆ Back to Top

  20. Can I add getters and setters using defineProperty method

    Yes, You can use the Object.defineProperty() method to add Getters and Setters. For example, the below counter object uses increment, decrement, add and subtract properties,

    var obj = {counter : 0};
    
    // Define getters
    Object.defineProperty(obj, "increment", {
      get : function () {this.counter++;}
    });
    Object.defineProperty(obj, "decrement", {
      get : function () {this.counter--;}
    });
    
    // Define setters
    Object.defineProperty(obj, "add", {
      set : function (value) {this.counter += value;}
    });
    Object.defineProperty(obj, "subtract", {
      set : function (value) {this.counter -= value;}
    });
    
    obj.add = 10;
    obj.subtract = 5;
    console.log(obj.increment); //6
    console.log(obj.decrement); //5
    

    ⬆ Back to Top

  21. What is the purpose of switch-case

    The switch case statement in JavaScript is used for decision making purposes. In a few cases, using the switch case statement is going to be more convenient than if-else statements. The syntax would be as below,

    switch (expression)
    {
        case value1:
            statement1;
            break;
        case value2:
            statement2;
            break;
        .
        .
        case valueN:
            statementN;
            break;
        default:
            statementDefault;
    }
    

    The above multi-way branch statement provides an easy way to dispatch execution to different parts of code based on the value of the expression.

    ⬆ Back to Top

  22. What are the conventions to be followed for the usage of switch case

    Below are the list of conventions should be taken care,

    1. The expression can be of type either number or string.
    2. Duplicate values are not allowed for the expression.
    3. The default statement is optional. If the expression passed to switch does not match with any case value then the statement within default case will be executed.
    4. The break statement is used inside the switch to terminate a statement sequence.
    5. The break statement is optional. But if it is omitted, the execution will continue on into the next case.

    ⬆ Back to Top

  23. What are primitive data types

    A primitive data type is data that has a primitive value (which has no properties or methods). There are 5 types of primitive data types.

    1. string
    2. number
    3. boolean
    4. null
    5. undefined

    ⬆ Back to Top

  24. What are the different ways to access object properties

    There are 3 possible ways for accessing the property of an object.

    1. Dot notation: It uses dot for accessing the properties
    objectName.property
    
    1. Square brackets notation: It uses square brackets for property access
    objectName["property"]
    
    1. Expression notation: It uses expression in the square brackets
    objectName[expression]
    

    ⬆ Back to Top

  25. What are the function parameter rules

    JavaScript functions follow below rules for parameters,

    1. The function definitions do not specify data types for parameters.
    2. Do not perform type checking on the passed arguments.
    3. Do not check the number of arguments received. i.e, The below function follows the above rules,
    function functionName(parameter1, parameter2, parameter3) {
      console.log(parameter1); // 1
    }
    functionName(1);
    

    ⬆ Back to Top

  26. What is an error object

    An error object is a built in error object that provides error information when an error occurs. It has two properties: name and message. For example, the below function logs error details,

    try {
      greeting("Welcome");
    }
    catch(err) {
      console.log(err.name + "<br>" + err.message);
    }
    

    ⬆ Back to Top

  27. When you get a syntax error

    A SyntaxError is thrown if you try to evaluate code with a syntax error. For example, the below missing quote for the function parameter throws a syntax error

    try {
      eval("greeting('welcome)");   // Missing ' will produce an error
    }
    catch(err) {
      console.log(err.name);
    }
    

    ⬆ Back to Top

  28. What are the different error names from error object

    There are 6 different types of error names returned from error object, | Error Name | Description | |---- | --------- | EvalError | An error has occurred in the eval() function | | RangeError | An error has occurred with a number "out of range" | | ReferenceError | An error due to an illegal reference| | SyntaxError | An error due to a syntax error| | TypeError | An error due to a type error | | URIError | An error due to encodeURI() |

    ⬆ Back to Top

  29. What are the various statements in error handling

    Below are the list of statements used in an error handling,

    1. try: This statement is used to test a block of code for errors
    2. catch: This statement is used to handle the error
    3. throw: This statement is used to create custom errors.
    4. finally: This statement is used to execute code after try and catch regardless of the result.

    ⬆ Back to Top

  30. What are the two types of loops in javascript

    1. Entry Controlled loops: In this kind of loop type, the test condition is tested before entering the loop body. For example, For Loop and While Loop comes under this category.
    2. Exit Controlled Loops: In this kind of loop type, the test condition is tested or evaluated at the end of the loop body. i.e, the loop body will execute at least once irrespective of test condition true or false. For example, do-while loop comes under this category.

    ⬆ Back to Top

  31. What is nodejs

    Node.js is a server-side platform built on Chrome's JavaScript runtime for easily building fast and scalable network applications. It is an event-based, non-blocking, asynchronous I/O runtime that uses Google's V8 JavaScript engine and libuv library.

    ⬆ Back to Top

  32. What is an Intl object

    The Intl object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting. It provides access to several constructors and language sensitive functions.

    ⬆ Back to Top

  33. How do you perform language specific date and time formatting

    You can use the Intl.DateTimeFormat object which is a constructor for objects that enable language-sensitive date and time formatting. Let's see this behavior with an example,

    var date = new Date(Date.UTC(2019, 07, 07, 3, 0, 0));
    console.log(new Intl.DateTimeFormat('en-GB').format(date)); // 07/08/2019
    console.log(new Intl.DateTimeFormat('en-AU').format(date)); // 07/08/2019
    

    ⬆ Back to Top

  34. What is an Iterator

    An iterator is an object which defines a sequence and a return value upon its termination. It implements the Iterator protocol with a next() method which returns an object with two properties: value (the next value in the sequence) and done (which is true if the last value in the sequence has been consumed).

    ⬆ Back to Top

  35. How does synchronous iteration works

    Synchronous iteration was introduced in ES6 and it works with below set of components,

    Iterable: It is an object which can be iterated over via a method whose key is Symbol.iterator. Iterator: It is an object returned by invoking [Symbol.iterator]() on an iterable. This iterator object wraps each iterated element in an object and returns it via next() method one by one. IteratorResult: It is an object returned by next() method. The object contains two properties; the value property contains an iterated element and the done property determines whether the element is the last element or not.

    Let's demonstrate synchronous iteration with an array as below,

    const iterable = ['one', 'two', 'three'];
    const iterator = iterable[Symbol.iterator]();
    console.log(iterator.next());  // { value: 'one', done: false }
    console.log(iterator.next());  // { value: 'two', done: false }
    console.log(iterator.next());  // { value: 'three', done: false }
    console.log(iterator.next());  // { value: 'undefined, done: true }
    

    ⬆ Back to Top

  36. What is an event loop

    The Event Loop is a queue of callback functions. When an async function executes, the callback function is pushed into the queue. The JavaScript engine doesn't start processing the event loop until the async function has finished executing the code. Note: It allows Node.js to perform non-blocking I/O operations even though JavaScript is single-threaded.

    ⬆ Back to Top

  37. What is call stack

    Call Stack is a data structure for javascript interpreters to keep track of function calls in the program. It has two major actions,

    1. Whenever you call a function for its execution, you are pushing it to the stack.
    2. Whenever the execution is completed, the function is popped out of the stack.

    Let's take an example and it's state representation in a diagram format

    function hungry() {
       eatFruits();
    }
    function eatFruits() {
       return "I'm eating fruits";
    }
    
    // Invoke the `hungry` function
    hungry();
    

    The above code processed in a call stack as below,

    1. Add the hungry() function to the call stack list and execute the code.
    2. Add the eatFruits() function to the call stack list and execute the code.
    3. Delete the eatFruits() function from our call stack list.
    4. Delete the hungry() function from the call stack list since there are no items anymore.

    Screenshot

    ⬆ Back to Top

  38. What is an event queue

    ⬆ Back to Top

  39. What is a decorator

    A decorator is an expression that evaluates to a function and that takes the target, name, and decorator descriptor as arguments. Also, it optionally returns a decorator descriptor to install on the target object. Let's define admin decorator for user class at design time,

    function admin(isAdmin) {
       return function(target) {
           target.isAdmin = isAdmin;
       }
    }
    
    @admin(true)
    class User() {
    }
    console.log(User.isAdmin); //true
    
     @admin(false)
     class User() {
     }
     console.log(User.isAdmin); //false
    

    ⬆ Back to Top

  40. What are the properties of Intl object

    Below are the list of properties available on Intl object,

    1. Collator: These are the objects that enable language-sensitive string comparison.
    2. DateTimeFormat: These are the objects that enable language-sensitive date and time formatting.
    3. ListFormat: These are the objects that enable language-sensitive list formatting.
    4. NumberFormat: Objects that enable language-sensitive number formatting.
    5. PluralRules: Objects that enable plural-sensitive formatting and language-specific rules for plurals.
    6. RelativeTimeFormat: Objects that enable language-sensitive relative time formatting.

    ⬆ Back to Top

  41. What is an Unary operator

    The unary(+) operator is used to convert a variable to a number.If the variable cannot be converted, it will still become a number but with the value NaN. Let's see this behavior in an action.

    var x = "100";
    var y = + x;
    console.log(typeof x, typeof y); // string, number
    
    var a = "Hello";
    var b = + a;
    console.log(typeof a, typeof b, b); // string, number, NaN
    

    ⬆ Back to Top

  42. How do you sort elements in an array

    The sort() method is used to sort the elements of an array in place and returns the sorted array. The example usage would be as below,

    var months = ["Aug", "Sep", "Jan", "June"];
    months.sort();
    console.log(months); //  ["Aug", "Jan", "June", "Sep"]
    

    ⬆ Back to Top

  43. What is the purpose of compareFunction while sorting arrays

    The compareFunction is used to define the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value. Let's take an example to see the usage of compareFunction,

    let numbers = [1, 2, 5, 3, 4];
    numbers.sort((a, b) => b - a);
    console.log(numbers); // [5, 4, 3, 2, 1]
    

    ⬆ Back to Top

  44. How do you reversing an array

    You can use the reverse() method to reverse the elements in an array. This method is useful to sort an array in descending order. Let's see the usage of reverse() method in an example,

    let numbers = [1, 2, 5, 3, 4];
    numbers.sort((a, b) => b - a);
    numbers.reverse();
    console.log(numbers); // [1, 2, 3, 4 ,5]
    

    ⬆ Back to Top

  45. How do you find min and max value in an array

    You can use Math.min and Math.max methods on array variables to find the minimum and maximum elements within an array. Let's create two functions to find the min and max value with in an array,

    var marks = [50, 20, 70, 60, 45, 30];
    function findMin(arr) {
      return Math.min.apply(null, arr);
    }
    function findMax(arr) {
      return Math.max.apply(null, arr);
    }
    
    console.log(findMin(marks));
    console.log(findMax(marks));
    

    ⬆ Back to Top

  46. How do you find min and max values without Math functions

    You can write functions which loop through an array comparing each value with the lowest value or highest value to find the min and max values. Let's create those functions to find min and max values,

     var marks = [50, 20, 70, 60, 45, 30];
     function findMin(arr) {
       var length = arr.length
       var min = Infinity;
       while (length--) {
         if (arr[length] < min) {
           min = arr[len];
         }
       }
       return min;
     }
    
     function findMax(arr) {
       var length = arr.length
       var max = -Infinity;
       while (len--) {
         if (arr[length] > max) {
           max = arr[length];
         }
       }
       return max;
     }
    
     console.log(findMin(marks));
     console.log(findMax(marks));
    

    ⬆ Back to Top

  47. What is an empty statement and purpose of it

    The empty statement is a semicolon (;) indicating that no statement will be executed, even if JavaScript syntax requires one. Since there is no action with an empty statement you might think that it's usage is quite less, but the empty statement is occasionally useful when you want to create a loop that has an empty body. For example, you can initialize an array with zero values as below,

    // Initialize an array a
    for(int i=0; i < a.length; a[i++] = 0) ;
    

    ⬆ Back to Top

  48. How do you get metadata of a module

    You can use the import.meta object which is a meta-property exposing context-specific meta data to a JavaScript module. It contains information about the current module, such as the module's URL. In browsers, you might get different meta data than NodeJS.

    <script type="module" src="welcome-module.js"></script>
    console.log(import.meta); // { url: "file:///home/user/welcome-module.js" }
    

    ⬆ Back to Top

  49. What is a comma operator

    The comma operator is used to evaluate each of its operands from left to right and returns the value of the last operand. This is totally different from comma usage within arrays, objects, and function arguments and parameters. For example, the usage for numeric expressions would be as below,

    var x = 1;
    x = (x++, x);
    
    console.log(x); // 2
    

    ⬆ Back to Top

  50. What is the advantage of a comma operator

    It is normally used to include multiple expressions in a location that requires a single expression. One of the common usages of this comma operator is to supply multiple parameters in a for loop. For example, the below for loop uses multiple expressions in a single location using comma operator,

    for (var a = 0, b =10; a <= 10; a++, b--)
    

    You can also use the comma operator in a return statement where it processes before returning.

    function myFunction() {
       var a = 1;
       return (a += 10, a); // 11
    }
    

    ⬆ Back to Top

  51. What is typescript

    TypeScript is a typed superset of JavaScript created by Microsoft that adds optional types, classes, async/await, and many other features, and compiles to plain JavaScript. Angular built entirely in TypeScript and used as a primary language. You can install it globally as

     npm install -g typescript
    

    Let's see a simple example of TypeScript usage,

     function greeting(name: string): string {
        return "Hello, " + name;
     }
    
     let user = "Sudheer";
    
     console.log(greeting(user));
    

    The greeting method allows only string type as argument.

    ⬆ Back to Top

  52. What are the differences between javascript and typescript

    Below are the list of differences between javascript and typescript,

    | feature | typescript | javascript | |---- | --------- | ---- | Language paradigm | Object oriented programming language | Scripting language | | Typing support | Supports static typing | It has dynamic typing | | Modules | Supported | Not supported | | Interface | It has interfaces concept | Doesn't support interfaces | | Optional parameters | Functions support optional parameters | No support of optional parameters for functions |

    ⬆ Back to Top

  53. What are the advantages of typescript over javascript

    Below are some of the advantages of typescript over javascript,

    1. TypeScript is able to find compile time errors at the development time only and it makes sures less runtime errors. Whereas javascript is an interpreted language.
    2. TypeScript is strongly-typed or supports static typing which allows for checking type correctness at compile time. This is not available in javascript.
    3. TypeScript compiler can compile the .ts files into ES3,ES4 and ES5 unlike ES6 features of javascript which may not be supported in some browsers.

    ⬆ Back to Top

  54. What is an object initializer

    An object initializer is an expression that describes the initialization of an Object. The syntax for this expression is represented as a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). This is also known as literal notation. It is one of the ways to create an object.

    var initObject = {a: 'John', b: 50, c: {}};
    
    console.log(initObject.a); // John
    

    ⬆ Back to Top

  55. What is a constructor method

    The constructor method is a special method for creating and initializing an object created within a class. If you do not specify a constructor method, a default constructor is used. The example usage of constructor would be as below,

    class Employee {
      constructor() {
        this.name = "John";
      }
    }
    
    var employeeObject = new Employee();
    
    console.log(employeeObject.name); // John
    

    ⬆ Back to Top

  56. What happens if you write constructor more than once in a class

    The "constructor" in a class is a special method and it should be defined only once in a class. i.e, If you write a constructor method more than once in a class it will throw a SyntaxError error.

     class Employee {
       constructor() {
         this.name = "John";
       }
       constructor() {   //  Uncaught SyntaxError: A class may only have one constructor
         this.age = 30;
       }
     }
    
     var employeeObject = new Employee();
    
     console.log(employeeObject.name);
    

    ⬆ Back to Top

  57. How do you call the constructor of a parent class

    You can use the super keyword to call the constructor of a parent class. Remember that super() must be called before using 'this' reference. Otherwise it will cause a reference error. Let's the usage of it,

    class Square extends Rectangle {
      constructor(length) {
        super(length, length);
        this.name = 'Square';
      }
    
      get area() {
        return this.width * this.height;
      }
    
      set area(value) {
        this.area = value;
      }
    }
    

    ⬆ Back to Top

  58. How do you get the prototype of an object

    You can use the Object.getPrototypeOf(obj) method to return the prototype of the specified object. i.e. The value of the internal prototype property. If there are no inherited properties then null value is returned.

    const newPrototype = {};
    const newObject = Object.create(newPrototype);
    
    console.log(Object.getPrototypeOf(newObject) === newPrototype); // true
    

    ⬆ Back to Top

  59. What happens If I pass string type for getPrototype method

    In ES5, it will throw a TypeError exception if the obj parameter isn't an object. Whereas in ES2015, the parameter will be coerced to an Object.

    // ES5
    Object.getPrototypeOf('James'); // TypeError: "James" is not an object
    // ES2015
    Object.getPrototypeOf('James'); // String.prototype
    

    ⬆ Back to Top

  60. How do you set prototype of one object to another

    You can use the Object.setPrototypeOf() method that sets the prototype (i.e., the internal Prototype property) of a specified object to another object or null. For example, if you want to set prototype of a square object to rectangle object would be as follows,

    Object.setPrototypeOf(Square.prototype, Rectangle.prototype);
    Object.setPrototypeOf({}, null);
    

    ⬆ Back to Top

  61. How do you check whether an object can be extendable or not

    The Object.isExtensible() method is used to determine if an object is extendable or not. i.e, Whether it can have new properties added to it or not.

    const newObject = {};
    console.log(Object.isExtensible(newObject)); //true
    

    Note: By default, all the objects are extendable. i.e, The new properties can be added or modified.

    ⬆ Back to Top

  62. How do you prevent an object to extend

    The Object.preventExtensions() method is used to prevent new properties from ever being added to an object. In other words, it prevents future extensions to the object. Let's see the usage of this property,

    const newObject = {};
    Object.preventExtensions(newObject); // NOT extendable
    
    try {
      Object.defineProperty(newObject, 'newProperty', { // Adding new property
        value: 100
      });
    } catch (e) {
      console.log(e); // TypeError: Cannot define property newProperty, object is not extensible
    }
    

    ⬆ Back to Top

  63. What are the different ways to make an object non-extensible

    You can mark an object non-extensible in 3 ways,

    1. Object.preventExtensions
    2. Object.seal
    3. Object.freeze
    var newObject = {};
    
    Object.preventExtensions(newObject); // Prevent objects are non-extensible
    Object.isExtensible(newObject); // false
    
    var sealedObject = Object.seal({}); // Sealed objects are non-extensible
    Object.isExtensible(sealedObject); // false
    
    var frozenObject = Object.freeze({}); // Frozen objects are non-extensible
    Object.isExtensible(frozenObject); // false
    

    ⬆ Back to Top

  64. How do you define multiple properties on an object

    The Object.defineProperties() method is used to define new or modify existing properties directly on an object and returning the object. Let's define multiple properties on an empty object,

    const newObject = {};
    
    Object.defineProperties(newObject, {
      newProperty1: {
        value: 'John',
        writable: true
      },
      newProperty2: {}
    });
    

    ⬆ Back to Top

  65. What is MEAN in javascript

    The MEAN (MongoDB, Express, AngularJS, and Node.js) stack is the most popular open-source JavaScript software tech stack available for building dynamic web apps where you can write both the server-side and client-side halves of the web project entirely in JavaScript.

    ⬆ Back to Top

  66. What Is Obfuscation in javascript

    Obfuscation is the deliberate act of creating obfuscated javascript code(i.e, source or machine code) that is difficult for humans to understand. It is something similar to encryption, but a machine can understand the code and execute it. Let's see the below function before Obfuscation,

    function greeting() {
       console.log('Hello, welcome to JS world');
    }
    

    And after the code Obfuscation, it would be appeared as below,

    eval(function(p,a,c,k,e,d){e=function(c){return c};if(!''.replace(/^/,String)){while(c--){d[c]=k[c]||c}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('2 1(){0.3(\'4, 7 6 5 8\')}',9,9,'console|greeting|function|log|Hello|JS|to|welcome|world'.split('|'),0,{}))
    

    ⬆ Back to Top

  67. Why do you need Obfuscation

    Below are the few reasons for Obfuscation,

    1. The Code size will be reduced. So data transfers between server and client will be fast.
    2. It hides the business logic from outside world and protects the code from others
    3. Reverse engineering is highly difficult
    4. The download time will be reduced

    ⬆ Back to Top

  68. What is Minification

    Minification is the process of removing all unnecessary characters(empty spaces are removed) and variables will be renamed without changing it's functionality. It is also a type of obfuscation .

    ⬆ Back to Top

  69. What are the advantages of minification

    Normally it is recommended to use minification for heavy traffic and intensive requirements of resources. It reduces file sizes with below benefits,

    1. Decreases loading times of a web page
    2. Saves bandwidth usages

    ⬆ Back to Top

  70. What are the differences between Obfuscation and Encryption

    Below are the main differences between Obfuscation and Encryption,

    | Feature | Obfuscation | Encryption | |---- | --------- | ---- | Definition | Changing the form of any data in any other form | Changing the form of information to an unreadable format by using a key | | A key to decode | It can be decoded without any key | It is required | | Target data format | It will be converted to a complex form | Converted into an unreadable format |

    ⬆ Back to Top

  71. What are the common tools used for minification

    There are many online/offline tools to minify the javascript files,

    1. Google's Closure Compiler
    2. UglifyJS2
    3. jsmin
    4. javascript-minifier.com
    5. prettydiff.com

    ⬆ Back to Top

  72. How do you perform form validation using javascript

    JavaScript can be used to perform HTML form validation. For example, if the form field is empty, the function needs to notify, and return false, to prevent the form being submitted. Lets' perform user login in an html form,

    <form name="myForm" onsubmit="return validateForm()" method="post">
    User name: <input type="text" name="uname">
    <input type="submit" value="Submit">
    </form>
    

    And the validation on user login is below,

    function validateForm() {
      var x = document.forms["myForm"]["uname"].value;
      if (x == "") {
        alert("The username shouldn't be empty");
        return false;
      }
    }
    

    ⬆ Back to Top

  73. How do you perform form validation without javascript

    You can perform HTML form validation automatically without using javascript. The validation enabled by applying the required attribute to prevent form submission when the input is empty.

    <form method="post">
      <input type="text" name="uname" required>
      <input type="submit" value="Submit">
    </form>
    

    Note: Automatic form validation does not work in Internet Explorer 9 or earlier.

    ⬆ Back to Top

  74. What are the DOM methods available for constraint validation

    The below DOM methods are available for constraint validation on an invalid input,

    1. checkValidity(): It returns true if an input element contains valid data.
    2. setCustomValidity(): It is used to set the validationMessage property of an input element. Let's take an user login form with DOM validations
    function myFunction() {
      var userName = document.getElementById("uname");
      if (!userName.checkValidity()) {
        document.getElementById("message").innerHTML = userName.validationMessage;
      } else {
        document.getElementById("message").innerHTML = "Entered a valid username";
      }
    }
    

    ⬆ Back to Top

  75. What are the available constraint validation DOM properties

    Below are the list of some of the constraint validation DOM properties available,

    1. validity: It provides a list of boolean properties related to the validity of an input element.
    2. validationMessage: It displays the message when the validity is false.
    3. willValidate: It indicates if an input element will be validated or not.

    ⬆ Back to Top

  76. What are the list of validity properties

    The validity property of an input element provides a set of properties related to the validity of data.

    1. customError: It returns true, if a custom validity message is set.
    2. patternMismatch: It returns true, if an element's value does not match its pattern attribute.
    3. rangeOverflow: It returns true, if an element's value is greater than its max attribute.
    4. rangeUnderflow: It returns true, if an element's value is less than its min attribute.
    5. stepMismatch: It returns true, if an element's value is invalid according to step attribute.
    6. tooLong: It returns true, if an element's value exceeds its maxLength attribute.
    7. typeMismatch: It returns true, if an element's value is invalid according to type attribute.
    8. valueMissing: It returns true, if an element with a required attribute has no value.
    9. valid: It returns true, if an element's value is valid.

    ⬆ Back to Top

  77. Give an example usage of rangeOverflow property

    If an element's value is greater than its max attribute then rangeOverflow property returns true. For example, the below form submission throws an error if the value is more than 100,

    <input id="age" type="number" max="100">
    <button onclick="myOverflowFunction()">OK</button>
    
    function myOverflowFunction() {
      if (document.getElementById("age").validity.rangeOverflow) {
        alert("The mentioned age is not allowed");
      }
    }
    

    ⬆ Back to Top

  78. Is enums feature available in javascript

    No, javascript does not natively support enums. But there are different kinds of solutions to simulate them even though they may not provide exact equivalents. For example, you can use freeze or seal on object,

    var DaysEnum = Object.freeze({"monday":1, "tuesday":2, "wednesday":3, ...})
    

    ⬆ Back to Top

  79. What is an enum

    An enum is a type restricting variables to one value from a predefined set of constants. JavaScript has no enums but typescript provides built-in enum support.

    enum Color {
     RED, GREEN, BLUE
    }
    

    ⬆ Back to Top

  80. How do you list all properties of an object

    You can use the Object.getOwnPropertyNames() method which returns an array of all properties found directly in a given object. Let's the usage of it in an example,

    const newObject = {
      a: 1,
      b: 2,
      c: 3
    };
    
    console.log(Object.getOwnPropertyNames(newObject));  ["a", "b", "c"]
    

    ⬆ Back to Top

  81. How do you get property descriptors of an object

    You can use the Object.getOwnPropertyDescriptors() method which returns all own property descriptors of a given object. The example usage of this method is below,

     const newObject = {
       a: 1,
       b: 2,
       c: 3
     };
    const descriptorsObject = Object.getOwnPropertyDescriptors(newObject);
    console.log(descriptorsObject.a.writable); //true
    console.log(descriptorsObject.a.configurable); //true
    console.log(descriptorsObject.a.enumerable); //true
    console.log(descriptorsObject.a.value); // 1
    

    ⬆ Back to Top

  82. What are the attributes provided by a property descriptor

    A property descriptor is a record which has the following attributes

    1. value: The value associated with the property
    2. writable: Determines whether the value associated with the property can be changed or not
    3. configurable: Returns true if the type of this property descriptor can be changed and if the property can be deleted from the corresponding object.
    4. enumerable: Determines whether the property appears during enumeration of the properties on the corresponding object or not.
    5. set: A function which serves as a setter for the property
    6. get: A function which serves as a getter for the property

    ⬆ Back to Top

  83. How do you extend classes

    The extends keyword is used in class declarations/expressions to create a class which is a child of another class. It can be used to subclass custom classes as well as built-in objects. The syntax would be as below,

    class ChildClass extends ParentClass { ... }
    

    Let's take an example of Square subclass from Polygon parent class,

     class Square extends Rectangle {
       constructor(length) {
         super(length, length);
         this.name = 'Square';
       }
    
       get area() {
         return this.width * this.height;
       }
    
       set area(value) {
         this.area = value;
       }
     }
    

    ⬆ Back to Top

  84. How do I modify the url without reloading the page

    The window.location.url property will be helpful to modify the url but it reloads the page. HTML5 introduced the history.pushState() and history.replaceState() methods, which allow you to add and modify history entries, respectively. For example, you can use pushState as below,

    window.history.pushState('page2', 'Title', '/page2.html');
    

    ⬆ Back to Top

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

    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
    

    ⬆ Back to Top

  86. How do you compare scalar arrays

    You can use length and every method of arrays to compare two scalar(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
    `
    

    ⬆ Back to Top

  87. 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. Remember that you may need to use polyfill or window.location to access the URL in older browsers(including IE).

    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
    

    ⬆ Back to Top

  88. 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));
    

    ⬆ Back to Top

  89. 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, | Feature | Java | JavaScript | |---- | ---- | ----- | Typed | It's a strongly typed language | It's a dynamic typed language | | Paradigm | Object oriented programming | Prototype based programming | | Scoping | Block scoped | Function-scoped | | Concurrency | Thread based | event based | | Memory | Uses more memory | Uses less memory. Hence it will be used for web pages |

    ⬆ Back to Top

  90. Is javascript supports namespace

    JavaScript doesn’t support namespace 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, namespace will solve the name collision problem.

    ⬆ Back to Top

  91. How do you declare namespace

    Even though JavaScript lacks namespaces, we can use Objects , IIFE 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.
    

    ⬆ Back to Top

  92. How do you invoke javascript code in an iframe from 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
    

    ⬆ Back to Top

  93. How do get the timezone offset from date

    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
    

    ⬆ Back to Top

  94. 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)
     }
    

    ⬆ Back to Top

  95. 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
    3. document.getElementsByClassName(name): It finds an element by class name

    ⬆ Back to Top

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

    ⬆ Back to Top

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

    ⬆ Back to Top

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

    ⬆ Back to Top

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

    <a href="javascript:void(alert('Welcome to JS world'))">Click here to see a message</a>
    

    Note: This operator is often used to obtain the undefined primitive value, using "void(0)".

    ⬆ Back to Top

  100. How to set the cursor to wait

    The cursor can be set to wait in JavaScript by using the property "cursor". Let's perform this behavior on page load using the below function.

    function myFunction() {
    window.document.body.style.cursor = "wait";
    }
    

    and this function invoked on page load

    <body onload="myFunction()">
    

    ⬆ Back to Top

Did you find this article valuable?

Support CapsCode's Blog by becoming a sponsor. Any amount is appreciated!