Skip to content

Latest commit

 

History

History
942 lines (658 loc) · 41.4 KB

File metadata and controls

942 lines (658 loc) · 41.4 KB

Table of Contents

No. Questions

| 301 | How do you create an infinite loop | | 302 | Why do you need to avoid with statement | | 303 | What is the output of below for loops | | 304 | List down some of the features of ES6 | | 305 | What is ES6 | | 306 | Can I redeclare let and const variables | | 307 | Is const variable makes the value immutable | | 308 | What are default parameters | | 309 | What are template literals | | 310 | How do you write multi-line strings in template literals | | 311 | What are nesting templates | | 312 | What are tagged templates | | 313 | What are raw strings | | 314 | What is destructuring assignment | | 315 | What are default values in destructuring assignment | | 316 | How do you swap variables in destructuring assignment | | 317 | What are enhanced object literals | | 318 | What are dynamic imports | | 319 | What are the use cases for dynamic imports | | 320 | What are typed arrays | | 321 | What are the advantages of module loaders | | 322 | What is collation | | 323 | What is for...of statement | | 324 | What is the output of below spread operator array | | 325 | Is PostMessage secure | | 326 | What are the problems with postmessage target origin as wildcard | | 327 | How do you avoid receiving postMessages from attackers | | 328 | Can I avoid using postMessages completely | | 329 | Is postMessages synchronous | | 330 | What paradigm is Javascript | | 331 | What is the difference between internal and external javascript | | 332 | Is JavaScript faster than server side script | | 333 | How do you get the status of a checkbox | | 334 | What is the purpose of double tilde operator | | 335 | How do you convert character to ASCII code | | 336 | What is ArrayBuffer | | 337 | What is the output of below string expression | | 338 | What is the purpose of Error object | | 339 | What is the purpose of EvalError object | | 340 | What are the list of cases error thrown from non-strict mode to strict mode | | 341 | Do all objects have prototypes | | 342 | What is the difference between a parameter and an argument | | 343 | What is the purpose of some method in arrays | | 344 | How do you combine two or more arrays | | 345 | What is the difference between Shallow and Deep copy | | 346 | How do you create specific number of copies of a string | | 347 | How do you return all matching strings against a regular expression | | 348 | How do you trim a string at the beginning or ending | | 349 | What is the output of below console statement with unary operator | | 350 | Does javascript uses mixins |

  1. How do you create an infinite loop

    You can create infinite loops using for and while loops without using any expressions. The for loop construct or syntax is better approach in terms of ESLint and code optimizer tools,

    for (;;) {}
    while (true) {}

    ⬆ Back to Top

  2. Why do you need to avoid with statement

    JavaScript's with statement was intended to provide a shorthand for writing recurring accesses to objects. So it can help reduce file size by reducing the need to repeat a lengthy object reference without performance penalty. Let's take an example where it is used to avoid redundancy when accessing an object several times.

    a.b.c.greeting = "welcome";
    a.b.c.age = 32;

    Using with it turns this into:

    with (a.b.c) {
      greeting = "welcome";
      age = 32;
    }

    But this with statement creates performance problems since one cannot predict whether an argument will refer to a real variable or to a property inside the with argument.

    ⬆ Back to Top

  3. What is the output of below for loops

    for (var i = 0; i < 4; i++) {
      // global scope
      setTimeout(() => console.log(i));
    }
    
    for (let i = 0; i < 4; i++) {
      // block scope
      setTimeout(() => console.log(i));
    }

    The output of the above for loops is 4 4 4 4 and 0 1 2 3

    Explanation: Due to the event queue/loop of javascript, the setTimeout callback function is called after the loop has been executed. Since the variable i is declared with the var keyword it became a global variable and the value was equal to 4 using iteration when the time setTimeout function is invoked. Hence, the output of the first loop is 4 4 4 4.

    Whereas in the second loop, the variable i is declared as the let keyword it becomes a block scoped variable and it holds a new value(0, 1 ,2 3) for each iteration. Hence, the output of the first loop is 0 1 2 3.

    ⬆ Back to Top

  4. List down some of the features of ES6

    Below are the list of some new features of ES6,

    1. Support for constants or immutable variables
    2. Block-scope support for variables, constants and functions
    3. Arrow functions
    4. Default parameters
    5. Rest and Spread Parameters
    6. Template Literals
    7. Multi-line Strings
    8. Destructuring Assignment
    9. Enhanced Object Literals
    10. Promises
    11. Classes
    12. Modules

    ⬆ Back to Top

  5. What is ES6

    ES6 is the sixth edition of the javascript language and it was released in June 2015. It was initially known as ECMAScript 6 (ES6) and later renamed to ECMAScript 2015. Almost all the modern browsers support ES6 but for the old browsers there are many transpilers, like Babel.js etc.

    ⬆ Back to Top

  6. Can I redeclare let and const variables

    No, you cannot redeclare let and const variables. If you do, it throws below error

    Uncaught SyntaxError: Identifier 'someVariable' has already been declared

    Explanation: The variable declaration with var keyword refers to a function scope and the variable is treated as if it were declared at the top of the enclosing scope due to hoisting feature. So all the multiple declarations contributing to the same hoisted variable without any error. Let's take an example of re-declaring variables in the same scope for both var and let/const variables.

    var name = "John";
    function myFunc() {
      var name = "Nick";
      var name = "Abraham"; // Re-assigned in the same function block
      alert(name); // Abraham
    }
    myFunc();
    alert(name); // John

    The block-scoped multi-declaration throws syntax error,

    let name = "John";
    function myFunc() {
      let name = "Nick";
      let name = "Abraham"; // Uncaught SyntaxError: Identifier 'name' has already been declared
      alert(name);
    }
    
    myFunc();
    alert(name);

    ⬆ Back to Top

  7. Is const variable makes the value immutable

    No, the const variable doesn't make the value immutable. But it disallows subsequent assignments(i.e, You can declare with assignment but can't assign another value later)

    const userList = [];
    userList.push("John"); // Can mutate even though it can't re-assign
    console.log(userList); // ['John']

    ⬆ Back to Top

  8. What are default parameters

    In ES5, we need to depend on logical OR operators to handle default values of function parameters. Whereas in ES6, Default function parameters feature allows parameters to be initialized with default values if no value or undefined is passed. Let's compare the behavior with an examples,

    //ES5
    var calculateArea = function (height, width) {
      height = height || 50;
      width = width || 60;
    
      return width * height;
    };
    console.log(calculateArea()); //300

    The default parameters makes the initialization more simpler,

    //ES6
    var calculateArea = function (height = 50, width = 60) {
      return width * height;
    };
    
    console.log(calculateArea()); //300

    ⬆ Back to Top

  9. What are template literals

    Template literals or template strings are string literals allowing embedded expressions. These are enclosed by the back-tick (`) character instead of double or single quotes. In ES6, this feature enables using dynamic expressions as below,

    var greeting = `Welcome to JS World, Mr. ${firstName} ${lastName}.`;

    In ES5, you need break string like below,

    var greeting = 'Welcome to JS World, Mr. ' + firstName + ' ' + lastName.`

    Note: You can use multi-line strings and string interpolation features with template literals.

    ⬆ Back to Top

  10. How do you write multi-line strings in template literals

    In ES5, you would have to use newline escape characters('\n') and concatenation symbols(+) in order to get multi-line strings.

    console.log("This is string sentence 1\n" + "This is string sentence 2");

    Whereas in ES6, You don't need to mention any newline sequence character,

    console.log(`This is string sentence
    'This is string sentence 2`);

    ⬆ Back to Top

  11. What are nesting templates

    The nesting template is a feature supported within template literals syntax to allow inner backticks inside a placeholder ${ } within the template. For example, the below nesting template is used to display the icons based on user permissions whereas outer template checks for platform type,

    const iconStyles = `icon ${
      isMobilePlatform()
        ? ""
        : `icon-${user.isAuthorized ? "submit" : "disabled"}`
    }`;

    You can write the above use case without nesting template features as well. However, the nesting template feature is more compact and readable.

    //Without nesting templates
     const iconStyles = `icon ${ isMobilePlatform() ? '' :
       user.isAuthorized ? 'icon-submit' : 'icon-disabled'}`;

    ⬆ Back to Top

  12. What are tagged templates

    Tagged templates are the advanced form of templates in which tags allow you to parse template literals with a function. The tag function accepts the first parameter as an array of strings and remaining parameters as expressions. This function can also return manipulated strings based on parameters. Let's see the usage of this tagged template behavior of an IT professional skill set in an organization,

    var user1 = "John";
    var skill1 = "JavaScript";
    var experience1 = 15;
    
    var user2 = "Kane";
    var skill2 = "JavaScript";
    var experience2 = 5;
    
    function myInfoTag(strings, userExp, experienceExp, skillExp) {
      var str0 = strings[0]; // "Mr/Ms. "
      var str1 = strings[1]; // " is a/an "
      var str2 = strings[2]; // "in"
    
      var expertiseStr;
      if (experienceExp > 10) {
        expertiseStr = "expert developer";
      } else if (skillExp > 5 && skillExp <= 10) {
        expertiseStr = "senior developer";
      } else {
        expertiseStr = "junior developer";
      }
    
      return `${str0}${userExp}${str1}${expertiseStr}${str2}${skillExp}`;
    }
    
    var output1 = myInfoTag`Mr/Ms. ${user1} is a/an ${experience1} in ${skill1}`;
    var output2 = myInfoTag`Mr/Ms. ${user2} is a/an ${experience2} in ${skill2}`;
    
    console.log(output1); // Mr/Ms. John is a/an expert developer in JavaScript
    console.log(output2); // Mr/Ms. Kane is a/an junior developer in JavaScript

    ⬆ Back to Top

  13. What are raw strings

    ES6 provides a raw strings feature using the String.raw() method which is used to get the raw string form of template strings. This feature allows you to access the raw strings as they were entered, without processing escape sequences. For example, the usage would be as below,

    var calculationString = String.raw`The sum of numbers is \n${
      1 + 2 + 3 + 4
    }!`;
    console.log(calculationString); // The sum of numbers is 10

    If you don't use raw strings, the newline character sequence will be processed by displaying the output in multiple lines

    var calculationString = `The sum of numbers is \n${1 + 2 + 3 + 4}!`;
    console.log(calculationString);
    // The sum of numbers is
    // 10

    Also, the raw property is available on the first argument to the tag function

    function tag(strings) {
      console.log(strings.raw[0]);
    }

    ⬆ Back to Top

  14. What is destructuring assignment

    The destructuring assignment is a JavaScript expression that makes it possible to unpack values from arrays or properties from objects into distinct variables. Let's get the month values from an array using destructuring assignment

    var [one, two, three] = ["JAN", "FEB", "MARCH"];
    
    console.log(one); // "JAN"
    console.log(two); // "FEB"
    console.log(three); // "MARCH"

    and you can get user properties of an object using destructuring assignment,

    var { name, age } = { name: "John", age: 32 };
    
    console.log(name); // John
    console.log(age); // 32

    ⬆ Back to Top

  15. What are default values in destructuring assignment

    A variable can be assigned a default value when the value unpacked from the array or object is undefined during destructuring assignment. It helps to avoid setting default values separately for each assignment. Let's take an example for both arrays and object use cases,

    Arrays destructuring:

    var x, y, z;
    
    [x = 2, y = 4, z = 6] = [10];
    console.log(x); // 10
    console.log(y); // 4
    console.log(z); // 6

    Objects destructuring:

    var { x = 2, y = 4, z = 6 } = { x: 10 };
    
    console.log(x); // 10
    console.log(y); // 4
    console.log(z); // 6

    ⬆ Back to Top

  16. How do you swap variables in destructuring assignment

    If you don't use destructuring assignment, swapping two values requires a temporary variable. Whereas using a destructuring feature, two variable values can be swapped in one destructuring expression. Let's swap two number variables in array destructuring assignment,

    var x = 10,
      y = 20;
    
    [x, y] = [y, x];
    console.log(x); // 20
    console.log(y); // 10

    ⬆ Back to Top

  17. What are enhanced object literals

    Object literals make it easy to quickly create objects with properties inside the curly braces. For example, it provides shorter syntax for common object property definition as below.

    //ES6
    var x = 10,
      y = 20;
    obj = { x, y };
    console.log(obj); // {x: 10, y:20}
    //ES5
    var x = 10,
      y = 20;
    obj = { x: x, y: y };
    console.log(obj); // {x: 10, y:20}

    ⬆ Back to Top

  18. What are dynamic imports

    The dynamic imports using import() function syntax allows us to load modules on demand by using promises or the async/await syntax. Currently this feature is in stage4 proposal. The main advantage of dynamic imports is reduction of our bundle's sizes, the size/payload response of our requests and overall improvements in the user experience. The syntax of dynamic imports would be as below,

    import("./Module").then((Module) => Module.method());

    ⬆ Back to Top

  19. What are the use cases for dynamic imports

    Below are some of the use cases of using dynamic imports over static imports,

    1. Import a module on-demand or conditionally. For example, if you want to load a polyfill on legacy browser
    if (isLegacyBrowser()) {
        import(···)
        .then(···);
    }
    1. Compute the module specifier at runtime. For example, you can use it for internationalization.
    import(`messages_${getLocale()}.js`).then(···);
    1. Import a module from within a regular script instead a module.

    ⬆ Back to Top

  20. What are typed arrays

    Typed arrays are array-like objects from ECMAScript 6 API for handling binary data. JavaScript provides 8 Typed array types,

    1. Int8Array: An array of 8-bit signed integers
    2. Int16Array: An array of 16-bit signed integers
    3. Int32Array: An array of 32-bit signed integers
    4. Uint8Array: An array of 8-bit unsigned integers
    5. Uint16Array: An array of 16-bit unsigned integers
    6. Uint32Array: An array of 32-bit unsigned integers
    7. Float32Array: An array of 32-bit floating point numbers
    8. Float64Array: An array of 64-bit floating point numbers

    For example, you can create an array of 8-bit signed integers as below

    const a = new Int8Array();
    // You can pre-allocate n bytes
    const bytes = 1024;
    const a = new Int8Array(bytes);

    ⬆ Back to Top

  21. What are the advantages of module loaders

    The module loaders provides the below features,

    1. Dynamic loading
    2. State isolation
    3. Global namespace isolation
    4. Compilation hooks
    5. Nested virtualization

    ⬆ Back to Top

  22. What is collation

    Collation is used for sorting a set of strings and searching within a set of strings. It is parameterized by locale and aware of Unicode. Let's take comparison and sorting features,

    1. Comparison:
    var list = ["ä", "a", "z"]; // In German,  "ä" sorts with "a" Whereas in Swedish, "ä" sorts after "z"
    var l10nDE = new Intl.Collator("de");
    var l10nSV = new Intl.Collator("sv");
    console.log(l10nDE.compare("ä", "z") === -1); // true
    console.log(l10nSV.compare("ä", "z") === +1); // true
    1. Sorting:
    var list = ["ä", "a", "z"]; // In German,  "ä" sorts with "a" Whereas in Swedish, "ä" sorts after "z"
    var l10nDE = new Intl.Collator("de");
    var l10nSV = new Intl.Collator("sv");
    console.log(list.sort(l10nDE.compare)); // [ "a", "ä", "z" ]
    console.log(list.sort(l10nSV.compare)); // [ "a", "z", "ä" ]

    ⬆ Back to Top

  23. What is for...of statement

    The for...of statement creates a loop iterating over iterable objects or elements such as built-in String, Array, Array-like objects (like arguments or NodeList), TypedArray, Map, Set, and user-defined iterables. The basic usage of for...of statement on arrays would be as below,

    let arrayIterable = [10, 20, 30, 40, 50];
    
    for (let value of arrayIterable) {
      value++;
      console.log(value); // 11 21 31 41 51
    }

    ⬆ Back to Top

  24. What is the output of below spread operator array

    [..."John Resig"];

    The output of the array is ['J', 'o', 'h', 'n', '', 'R', 'e', 's', 'i', 'g'] Explanation: The string is an iterable type and the spread operator within an array maps every character of an iterable to one element. Hence, each character of a string becomes an element within an Array.

    ⬆ Back to Top

  25. Is PostMessage secure

    Yes, postMessages can be considered very secure as long as the programmer/developer is careful about checking the origin and source of an arriving message. But if you try to send/receive a message without verifying its source will create cross-site scripting attacks.

    ⬆ Back to Top

  26. What are the problems with postmessage target origin as wildcard

    The second argument of postMessage method specifies which origin is allowed to receive the message. If you use the wildcard “*” as an argument then any origin is allowed to receive the message. In this case, there is no way for the sender window to know if the target window is at the target origin when sending the message. If the target window has been navigated to another origin, the other origin would receive the data. Hence, this may lead to XSS vulnerabilities.

    targetWindow.postMessage(message, "*");

    ⬆ Back to Top

  27. How do you avoid receiving postMessages from attackers

    Since the listener listens for any message, an attacker can trick the application by sending a message from the attacker’s origin, which gives an impression that the receiver received the message from the actual sender’s window. You can avoid this issue by validating the origin of the message on the receiver's end using the “message.origin” attribute. For examples, let's check the sender's origin http://www.some-sender.com on receiver side www.some-receiver.com,

    //Listener on http://www.some-receiver.com/
    window.addEventListener("message", function(message){
        if(/^http://www\.some-sender\.com$/.test(message.origin)){
             console.log('You received the data from valid sender', message.data);
       }
    });

    ⬆ Back to Top

  28. Can I avoid using postMessages completely

    You cannot avoid using postMessages completely(or 100%). Even though your application doesn’t use postMessage considering the risks, a lot of third party scripts use postMessage to communicate with the third party service. So your application might be using postMessage without your knowledge.

    ⬆ Back to Top

  29. Is postMessages synchronous

    The postMessages are synchronous in IE8 browser but they are asynchronous in IE9 and all other modern browsers (i.e, IE9+, Firefox, Chrome, Safari).Due to this asynchronous behaviour, we use a callback mechanism when the postMessage is returned.

    ⬆ Back to Top

  30. What paradigm is Javascript

    JavaScript is a multi-paradigm language, supporting imperative/procedural programming, Object-Oriented Programming and functional programming. JavaScript supports Object-Oriented Programming with prototypical inheritance.

    ⬆ Back to Top

  31. What is the difference between internal and external javascript

    Internal JavaScript: It is the source code within the script tag. External JavaScript: The source code is stored in an external file(stored with .js extension) and referred with in the tag.

    ⬆ Back to Top

  32. Is JavaScript faster than server side script

    Yes, JavaScript is faster than server side scripts. Because JavaScript is a client-side script it does not require any web server’s help for its computation or calculation. So JavaScript is always faster than any server-side script like ASP, PHP, etc.

    ⬆ Back to Top

  33. How do you get the status of a checkbox

    You can apply the checked property on the selected checkbox in the DOM. If the value is true it means the checkbox is checked, otherwise it is unchecked. For example, the below HTML checkbox element can be access using javascript as below:

    <input type="checkbox" id="checkboxname" value="Agree" /> Agree the
    conditions<br />
    console.log(document.getElementById(‘checkboxname’).checked); // true or false

    ⬆ Back to Top

  34. What is the purpose of double tilde operator

    The double tilde operator(~~) is known as double NOT bitwise operator. This operator is a slightly quicker substitute for Math.floor().

    ⬆ Back to Top

  35. How do you convert character to ASCII code

    You can use the String.prototype.charCodeAt() method to convert string characters to ASCII numbers. For example, let's find ASCII code for the first letter of 'ABC' string,

    "ABC".charCodeAt(0); // returns 65

    Whereas String.fromCharCode() method converts numbers to equal ASCII characters.

    String.fromCharCode(65, 66, 67); // returns 'ABC'

    ⬆ Back to Top

  36. What is ArrayBuffer

    An ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. You can create it as below,

    let buffer = new ArrayBuffer(16); // create a buffer of length 16
    alert(buffer.byteLength); // 16

    To manipulate an ArrayBuffer, we need to use a “view” object.

    //Create a DataView referring to the buffer
    let view = new DataView(buffer);

    ⬆ Back to Top

  37. What is the output of below string expression

    console.log("Welcome to JS world"[0]);

    The output of the above expression is "W". Explanation: The bracket notation with specific index on a string returns the character at a specific location. Hence, it returns the character "W" of the string. Since this is not supported in IE7 and below versions, you may need to use the .charAt() method to get the desired result.

    ⬆ Back to Top

  38. What is the purpose of Error object

    The Error constructor creates an error object and the instances of error objects are thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions. The syntax of error object would be as below,

    new Error([message[, fileName[, lineNumber]]])

    You can throw user defined exceptions or errors using Error object in try...catch block as below,

    try {
      if (withdraw > balance)
        throw new Error("Oops! You don't have enough balance");
    } catch (e) {
      console.log(e.name + ": " + e.message);
    }

    ⬆ Back to Top

  39. What is the purpose of EvalError object

    The EvalError object indicates an error regarding the global eval() function. Even though this exception is not thrown by JavaScript anymore, the EvalError object remains for compatibility. The syntax of this expression would be as below,

    new EvalError([message[, fileName[, lineNumber]]])

    You can throw EvalError with in try...catch block as below,

    try {
      throw new EvalError('Eval function error', 'someFile.js', 100);
    } catch (e) {
      console.log(e.message, e.name, e.fileName);              // "Eval function error", "EvalError", "someFile.js"

    ⬆ Back to Top

  40. What are the list of cases error thrown from non-strict mode to strict mode

    When you apply 'use strict'; syntax, some of the below cases will throw a SyntaxError before executing the script

    1. When you use Octal syntax
    var n = 022;
    1. Using with statement
    2. When you use delete operator on a variable name
    3. Using eval or arguments as variable or function argument name
    4. When you use newly reserved keywords
    5. When you declare a function in a block
    if (someCondition) {
      function f() {}
    }

    Hence, the errors from above cases are helpful to avoid errors in development/production environments.

    ⬆ Back to Top

  41. Do all objects have prototypes

    No. All objects have prototypes except for the base object which is created by the user, or an object that is created using the new keyword.

    ⬆ Back to Top

  42. What is the difference between a parameter and an argument

    Parameter is the variable name of a function definition whereas an argument represents the value given to a function when it is invoked. Let's explain this with a simple function

    function myFunction(parameter1, parameter2, parameter3) {
      console.log(arguments[0]); // "argument1"
      console.log(arguments[1]); // "argument2"
      console.log(arguments[2]); // "argument3"
    }
    myFunction("argument1", "argument2", "argument3");

    ⬆ Back to Top

  43. What is the purpose of some method in arrays

    The some() method is used to test whether at least one element in the array passes the test implemented by the provided function. The method returns a boolean value. Let's take an example to test for any odd elements,

    var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    
    var odd = (element) => element % 2 !== 0;
    
    console.log(array.some(odd)); // true (the odd element exists)

    ⬆ Back to Top

  44. How do you combine two or more arrays

    The concat() method is used to join two or more arrays by returning a new array containing all the elements. The syntax would be as below,

    array1.concat(array2, array3, ..., arrayX)

    Let's take an example of array's concatenation with veggies and fruits arrays,

    var veggies = ["Tomato", "Carrot", "Cabbage"];
    var fruits = ["Apple", "Orange", "Pears"];
    var veggiesAndFruits = veggies.concat(fruits);
    console.log(veggiesAndFruits); // Tomato, Carrot, Cabbage, Apple, Orange, Pears

    ⬆ Back to Top

  45. What is the difference between Shallow and Deep copy

    There are two ways to copy an object,

    Shallow Copy: Shallow copy is a bitwise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.

    Example

    var empDetails = {
      name: "John",
      age: 25,
      expertise: "Software Developer",
    };

    to create a duplicate

    var empDetailsShallowCopy = empDetails; //Shallow copying!

    if we change some property value in the duplicate one like this:

    empDetailsShallowCopy.name = "Johnson";

    The above statement will also change the name of empDetails, since we have a shallow copy. That means we're losing the original data as well.

    Deep copy: A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.

    Example

    var empDetails = {
      name: "John",
      age: 25,
      expertise: "Software Developer",
    };

    Create a deep copy by using the properties from the original object into new variable

    var empDetailsDeepCopy = {
      name: empDetails.name,
      age: empDetails.age,
      expertise: empDetails.expertise,
    };

    Now if you change empDetailsDeepCopy.name, it will only affect empDetailsDeepCopy & not empDetails

    ⬆ Back to Top

  46. How do you create specific number of copies of a string

    The repeat() method is used to construct and return a new string which contains the specified number of copies of the string on which it was called, concatenated together. Remember that this method has been added to the ECMAScript 2015 specification. Let's take an example of Hello string to repeat it 4 times,

    "Hello".repeat(4); // 'HelloHelloHelloHello'
  47. How do you return all matching strings against a regular expression

    The matchAll() method can be used to return an iterator of all results matching a string against a regular expression. For example, the below example returns an array of matching string results against a regular expression,

    let regexp = /Hello(\d?))/g;
    let greeting = "Hello1Hello2Hello3";
    
    let greetingList = [...greeting.matchAll(regexp)];
    
    console.log(greetingList[0]); //Hello1
    console.log(greetingList[1]); //Hello2
    console.log(greetingList[2]); //Hello3

    ⬆ Back to Top

  48. How do you trim a string at the beginning or ending

    The trim method of string prototype is used to trim on both sides of a string. But if you want to trim especially at the beginning or ending of the string then you can use trimStart/trimLeft and trimEnd/trimRight methods. Let's see an example of these methods on a greeting message,

    var greeting = "   Hello, Goodmorning!   ";
    
    console.log(greeting); // "   Hello, Goodmorning!   "
    console.log(greeting.trimStart()); // "Hello, Goodmorning!   "
    console.log(greeting.trimLeft()); // "Hello, Goodmorning!   "
    
    console.log(greeting.trimEnd()); // "   Hello, Goodmorning!"
    console.log(greeting.trimRight()); // "   Hello, Goodmorning!"

    ⬆ Back to Top

  49. What is the output of below console statement with unary operator

    Let's take console statement with unary operator as given below,

    console.log(+"Hello");

    The output of the above console log statement returns NaN. Because the element is prefixed by the unary operator and the JavaScript interpreter will try to convert that element into a number type. Since the conversion fails, the value of the statement results in NaN value.

    ⬆ Back to Top

  50. Does javascript uses mixins

    Mixin is a generic object-oriented programming term - is a class containing methods that can be used by other classes without a need to inherit from it. In JavaScript we can only inherit from a single object. ie. There can be only one [[prototype]] for an object.

    But sometimes we require to extend more than one, to overcome this we can use Mixin which helps to copy methods to the prototype of another class.

    Say for instance, we've two classes User and CleanRoom. Suppose we need to add CleanRoom functionality to User, so that user can clean the room at demand. Here's where concept called mixins comes into picture.

    // mixin
    let cleanRoomMixin = {
      cleanRoom() {
        alert(`Hello ${this.name}, your room is clean now`);
      },
      sayBye() {
        alert(`Bye ${this.name}`);
      },
    };
    
    // usage:
    class User {
      constructor(name) {
        this.name = name;
      }
    }
    
    // copy the methods
    Object.assign(User.prototype, cleanRoomMixin);
    
    // now User can clean the room
    new User("Dude").cleanRoom(); // Hello Dude, your room is clean now!

    ⬆ Back to Top