Skip to content

Latest commit

 

History

History
867 lines (625 loc) · 38.9 KB

File metadata and controls

867 lines (625 loc) · 38.9 KB

Table of Contents

No. Questions

| 141 | What is the way to find the number of parameters expected by a function | | 142 | What is a polyfill | | 143 | What are break and continue statements | | 144 | What are js labels | | 145 | What are the benefits of keeping declarations at the top | | 146 | What are the benefits of initializing variables | | 147 | What are the recommendations to create new object | | 148 | How do you define JSON arrays | | 149 | How do you generate random integers | | 150 | Can you write a random integers function to print integers with in a range | | 151 | What is tree shaking | | 152 | What is the need of tree shaking | | 153 | Is it recommended to use eval | | 154 | What is a Regular Expression | | 155 | What are the string methods available in Regular expression | | 156 | What are modifiers in regular expression | | 157 | What are regular expression patterns | | 158 | What is a RegExp object | | 159 | How do you search a string for a pattern | | 160 | What is the purpose of exec method | | 161 | How do you change the style of a HTML element | | 162 | What would be the result of 1+2+'3' | | 163 | What is a debugger statement | | 164 | What is the purpose of breakpoints in debugging | | 165 | Can I use reserved words as identifiers | | 166 | How do you detect a mobile browser | | 167 | How do you detect a mobile browser without regexp | | 168 | How do you get the image width and height using JS | | 169 | How do you make synchronous HTTP request | | 170 | How do you make asynchronous HTTP request | | 171 | How do you convert date to another timezone in javascript | | 172 | What are the properties used to get size of window | | 173 | What is a conditional operator in javascript | | 174 | Can you apply chaining on conditional operator | | 175 | What are the ways to execute javascript after page load | | 176 | What is the difference between proto and prototype | | 177 | Give an example where do you really need semicolon | | 178 | What is a freeze method | | 179 | What is the purpose of freeze method | | 180 | Why do I need to use freeze method | | 181 | How do you detect a browser language preference | | 182 | How to convert string to title case with javascript | | 183 | How do you detect javascript disabled in the page | | 184 | What are various operators supported by javascript | | 185 | What is a rest parameter | | 186 | What happens if you do not use rest parameter as a last argument | | 187 | What are the bitwise operators available in javascript | | 188 | What is a spread operator | | 189 | How do you determine whether object is frozen or not | | 190 | How do you determine two values same or not using object |

  1. What is the way to find the number of parameters expected by a function

    You can use function.length syntax to find the number of parameters expected by a function. Let's take an example of sum function to calculate the sum of numbers,

    function sum(num1, num2, num3, num4) {
      return num1 + num2 + num3 + num4;
    }
    sum.length; // 4 is the number of parameters expected.

    ⬆ Back to Top

  2. What is a polyfill

    A polyfill is a piece of JS code used to provide modern functionality on older browsers that do not natively support it. For example, Silverlight plugin polyfill can be used to mimic the functionality of an HTML Canvas element on Microsoft Internet Explorer 7.

    ⬆ Back to Top

  3. What are break and continue statements

    The break statement is used to "jump out" of a loop. i.e, It breaks the loop and continues executing the code after the loop.

    for (i = 0; i < 10; i++) {
      if (i === 5) {
        break;
      }
      text += "Number: " + i + "<br>";
    }

    The continue statement is used to "jump over" one iteration in the loop. i.e, It breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

    for (i = 0; i < 10; i++) {
      if (i === 5) {
        continue;
      }
      text += "Number: " + i + "<br>";
    }

    ⬆ Back to Top

  4. What are js labels

    The label statement allows us to name loops and blocks in JavaScript. We can then use these labels to refer back to the code later. For example, the below code with labels avoids printing the numbers when they are same,

    var i, j;
    
    loop1: for (i = 0; i < 3; i++) {
      loop2: for (j = 0; j < 3; j++) {
        if (i === j) {
          continue loop1;
        }
        console.log("i = " + i + ", j = " + j);
      }
    }
    
    // Output is:
    //   "i = 1, j = 0"
    //   "i = 2, j = 0"
    //   "i = 2, j = 1"

    ⬆ Back to Top

  5. What are the benefits of keeping declarations at the top

    It is recommended to keep all declarations at the top of each script or function. The benefits of doing this are,

    1. Gives cleaner code
    2. It provides a single place to look for local variables
    3. Easy to avoid unwanted global variables
    4. It reduces the possibility of unwanted re-declarations

    ⬆ Back to Top

  6. What are the benefits of initializing variables

    It is recommended to initialize variables because of the below benefits,

    1. It gives cleaner code
    2. It provides a single place to initialize variables
    3. Avoid undefined values in the code

    ⬆ Back to Top

  7. What are the recommendations to create new object

    It is recommended to avoid creating new objects using new Object(). Instead you can initialize values based on it's type to create the objects.

    1. Assign {} instead of new Object()
    2. Assign "" instead of new String()
    3. Assign 0 instead of new Number()
    4. Assign false instead of new Boolean()
    5. Assign [] instead of new Array()
    6. Assign /()/ instead of new RegExp()
    7. Assign function (){} instead of new Function()

    You can define them as an example,

    var v1 = {};
    var v2 = "";
    var v3 = 0;
    var v4 = false;
    var v5 = [];
    var v6 = /()/;
    var v7 = function () {};

    ⬆ Back to Top

  8. How do you define JSON arrays

    JSON arrays are written inside square brackets and arrays contain javascript objects. For example, the JSON array of users would be as below,

    "users":[
      {"firstName":"John", "lastName":"Abrahm"},
      {"firstName":"Anna", "lastName":"Smith"},
      {"firstName":"Shane", "lastName":"Warn"}
    ]

    ⬆ Back to Top

  9. How do you generate random integers

    You can use Math.random() with Math.floor() to return random integers. For example, if you want generate random integers between 1 to 10, the multiplication factor should be 10,

    Math.floor(Math.random() * 10) + 1; // returns a random integer from 1 to 10
    Math.floor(Math.random() * 100) + 1; // returns a random integer from 1 to 100

    Note: Math.random() returns a random number between 0 (inclusive), and 1 (exclusive)

    ⬆ Back to Top

  10. Can you write a random integers function to print integers with in a range

    Yes, you can create a proper random function to return a random number between min and max (both included)

    function randomInteger(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    randomInteger(1, 100); // returns a random integer from 1 to 100
    randomInteger(1, 1000); // returns a random integer from 1 to 1000

    ⬆ Back to Top

  11. What is tree shaking

    Tree shaking is a form of dead code elimination. It means that unused modules will not be included in the bundle during the build process and for that it relies on the static structure of ES2015 module syntax,( i.e. import and export). Initially this has been popularized by the ES2015 module bundler rollup.

    ⬆ Back to Top

  12. What is the need of tree shaking

    Tree Shaking can significantly reduce the code size in any application. i.e, The less code we send over the wire the more performant the application will be. For example, if we just want to create a “Hello World” Application using SPA frameworks then it will take around a few MBs, but by tree shaking it can bring down the size to just a few hundred KBs. Tree shaking is implemented in Rollup and Webpack bundlers.

    ⬆ Back to Top

  13. Is it recommended to use eval

    No, it allows arbitrary code to be run which causes a security problem. As we know that the eval() function is used to run text as code. In most of the cases, it should not be necessary to use it.

    ⬆ Back to Top

  14. What is a Regular Expression

    A regular expression is a sequence of characters that forms a search pattern. You can use this search pattern for searching data in a text. These can be used to perform all types of text search and text replace operations. Let's see the syntax format now,

    /pattern/modifiers;

    For example, the regular expression or search pattern with case-insensitive username would be,

    /John/i;

    ⬆ Back to Top

  15. What are the string methods available in Regular expression

    Regular Expressions has two string methods: search() and replace(). The search() method uses an expression to search for a match, and returns the position of the match.

    var msg = "Hello John";
    var n = msg.search(/John/i); // 6

    The replace() method is used to return a modified string where the pattern is replaced.

    var msg = "Hello John";
    var n = msg.replace(/John/i, "Buttler"); // Hello Buttler

    ⬆ Back to Top

  16. What are modifiers in regular expression

    Modifiers can be used to perform case-insensitive and global searches. Let's list down some of the modifiers,

    Modifier Description
    i Perform case-insensitive matching
    g Perform a global match rather than stops at first match
    m Perform multiline matching

    Let's take an example of global modifier,

    var text = "Learn JS one by one";
    var pattern = /one/g;
    var result = text.match(pattern); // one,one

    ⬆ Back to Top

  17. What are regular expression patterns

    Regular Expressions provide a group of patterns in order to match characters. Basically they are categorized into 3 types,

    1. Brackets: These are used to find a range of characters. For example, below are some use cases,
      1. [abc]: Used to find any of the characters between the brackets(a,b,c)
      2. [0-9]: Used to find any of the digits between the brackets
      3. (a|b): Used to find any of the alternatives separated with |
    2. Metacharacters: These are characters with a special meaning For example, below are some use cases,
      1. \d: Used to find a digit
      2. \s: Used to find a whitespace character
      3. \b: Used to find a match at the beginning or ending of a word
    3. Quantifiers: These are useful to define quantities For example, below are some use cases,
      1. n+: Used to find matches for any string that contains at least one n
      2. n*: Used to find matches for any string that contains zero or more occurrences of n
      3. n?: Used to find matches for any string that contains zero or one occurrences of n

    ⬆ Back to Top

  18. What is a RegExp object

    RegExp object is a regular expression object with predefined properties and methods. Let's see the simple usage of RegExp object,

    var regexp = new RegExp("\\w+");
    console.log(regexp);
    // expected output: /\w+/

    ⬆ Back to Top

  19. How do you search a string for a pattern

    You can use the test() method of regular expression in order to search a string for a pattern, and return true or false depending on the result.

    var pattern = /you/;
    console.log(pattern.test("How are you?")); //true

    ⬆ Back to Top

  20. What is the purpose of exec method

    The purpose of exec method is similar to test method but it executes a search for a match in a specified string and returns a result array, or null instead of returning true/false.

    var pattern = /you/;
    console.log(pattern.exec("How are you?")); //["you", index: 8, input: "How are you?", groups: undefined]

    ⬆ Back to Top

  21. How do you change the style of a HTML element

    You can change inline style or classname of a HTML element using javascript

    1. Using style property: You can modify inline style using style property
    document.getElementById("title").style.fontSize = "30px";
    1. Using ClassName property: It is easy to modify element class using className property
    document.getElementById("title").className = "custom-title";

    ⬆ Back to Top

  22. What would be the result of 1+2+'3'

    The output is going to be 33. Since 1 and 2 are numeric values, the result of the first two digits is going to be a numeric value 3. The next digit is a string type value because of that the addition of numeric value 3 and string type value 3 is just going to be a concatenation value 33.

    ⬆ Back to Top

  23. What is a debugger statement

    The debugger statement invokes any available debugging functionality, such as setting a breakpoint. If no debugging functionality is available, this statement has no effect. For example, in the below function a debugger statement has been inserted. So execution is paused at the debugger statement just like a breakpoint in the script source.

    function getProfile() {
      // code goes here
      debugger;
      // code goes here
    }

    ⬆ Back to Top

  24. What is the purpose of breakpoints in debugging

    You can set breakpoints in the javascript code once the debugger statement is executed and the debugger window pops up. At each breakpoint, javascript will stop executing, and let you examine the JavaScript values. After examining values, you can resume the execution of code using the play button.

    ⬆ Back to Top

  25. Can I use reserved words as identifiers

    No, you cannot use the reserved words as variables, labels, object or function names. Let's see one simple example,

    var else = "hello"; // Uncaught SyntaxError: Unexpected token else

    ⬆ Back to Top

  26. How do you detect a mobile browser

    You can use regex which returns a true or false value depending on whether or not the user is browsing with a mobile.

    window.mobilecheck = function () {
      var mobileCheck = false;
      (function (a) {
        if (
          /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(
            a
          ) ||
          /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(
            a.substr(0, 4)
          )
        )
          mobileCheck = true;
      })(navigator.userAgent || navigator.vendor || window.opera);
      return mobileCheck;
    };

    ⬆ Back to Top

  27. How do you detect a mobile browser without regexp

    You can detect mobile browsers by simply running through a list of devices and checking if the useragent matches anything. This is an alternative solution for RegExp usage,

    function detectmob() {
      if (
        navigator.userAgent.match(/Android/i) ||
        navigator.userAgent.match(/webOS/i) ||
        navigator.userAgent.match(/iPhone/i) ||
        navigator.userAgent.match(/iPad/i) ||
        navigator.userAgent.match(/iPod/i) ||
        navigator.userAgent.match(/BlackBerry/i) ||
        navigator.userAgent.match(/Windows Phone/i)
      ) {
        return true;
      } else {
        return false;
      }
    }

    ⬆ Back to Top

  28. How do you get the image width and height using JS

    You can programmatically get the image and check the dimensions(width and height) using Javascript.

    var img = new Image();
    img.onload = function () {
      console.log(this.width + "x" + this.height);
    };
    img.src = "http://www.google.com/intl/en_ALL/images/logo.gif";

    ⬆ Back to Top

  29. How do you make synchronous HTTP request

    Browsers provide an XMLHttpRequest object which can be used to make synchronous HTTP requests from JavaScript

    function httpGet(theUrl) {
      var xmlHttpReq = new XMLHttpRequest();
      xmlHttpReq.open("GET", theUrl, false); // false for synchronous request
      xmlHttpReq.send(null);
      return xmlHttpReq.responseText;
    }

    ⬆ Back to Top

  30. How do you make asynchronous HTTP request

    Browsers provide an XMLHttpRequest object which can be used to make asynchronous HTTP requests from JavaScript by passing the 3rd parameter as true.

    function httpGetAsync(theUrl, callback) {
      var xmlHttpReq = new XMLHttpRequest();
      xmlHttpReq.onreadystatechange = function () {
        if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200)
          callback(xmlHttpReq.responseText);
      };
      xmlHttp.open("GET", theUrl, true); // true for asynchronous
      xmlHttp.send(null);
    }

    ⬆ Back to Top

  31. How do you convert date to another timezone in javascript

    You can use the toLocaleString() method to convert dates in one timezone to another. For example, let's convert current date to British English timezone as below,

    console.log(event.toLocaleString("en-GB", { timeZone: "UTC" })); //29/06/2019, 09:56:00

    ⬆ Back to Top

  32. What are the properties used to get size of window

    You can use innerWidth, innerHeight, clientWidth, clientHeight properties of windows, document element and document body objects to find the size of a window. Let's use them combination of these properties to calculate the size of a window or document,

    var width =
      window.innerWidth ||
      document.documentElement.clientWidth ||
      document.body.clientWidth;
    
    var height =
      window.innerHeight ||
      document.documentElement.clientHeight ||
      document.body.clientHeight;

    ⬆ Back to Top

  33. What is a conditional operator in javascript

    The conditional (ternary) operator is the only JavaScript operator that takes three operands which acts as a shortcut for if statements.

    var isAuthenticated = false;
    console.log(
      isAuthenticated ? "Hello, welcome" : "Sorry, you are not authenticated"
    ); //Sorry, you are not authenticated

    ⬆ Back to Top

  34. Can you apply chaining on conditional operator

    Yes, you can apply chaining on conditional operators similar to if … else if … else if … else chain. The syntax is going to be as below,

    function traceValue(someParam) {
      return condition1
        ? value1
        : condition2
        ? value2
        : condition3
        ? value3
        : value4;
    }
    
    // The above conditional operator is equivalent to:
    
    function traceValue(someParam) {
      if (condition1) {
        return value1;
      } else if (condition2) {
        return value2;
      } else if (condition3) {
        return value3;
      } else {
        return value4;
      }
    }

    ⬆ Back to Top

  35. What are the ways to execute javascript after page load

    You can execute javascript after page load in many different ways,

    1. window.onload:
    window.onload = function ...
    1. document.onload:
    document.onload = function ...
    1. body onload:
    <body onload="script();">

    ⬆ Back to Top

  36. What is the difference between proto and prototype

    The __proto__ object is the actual object that is used in the lookup chain to resolve methods, etc. Whereas prototype is the object that is used to build __proto__ when you create an object with new.

    new Employee().__proto__ === Employee.prototype;
    new Employee().prototype === undefined;

    There are few more differences,

    feature Prototype proto
    Access All the function constructors have prototype properties. All the objects have __proto__ property
    Purpose Used to reduce memory wastage with a single copy of function Used in lookup chain to resolve methods, constructors etc.
    ECMAScript Introduced in ES6 Introduced in ES5
    Usage Frequently used Rarely used

    ⬆ Back to Top

  37. Give an example where do you really need semicolon

    It is recommended to use semicolons after every statement in JavaScript. For example, in the below case it throws an error ".. is not a function" at runtime due to missing semicolon.

    // define a function
    var fn = (function () {
      //...
    })(
      // semicolon missing at this line
    
      // then execute some code inside a closure
      function () {
        //...
      }
    )();

    and it will be interpreted as

    var fn = (function () {
      //...
    })(function () {
      //...
    })();

    In this case, we are passing the second function as an argument to the first function and then trying to call the result of the first function call as a function. Hence, the second function will fail with a "... is not a function" error at runtime.

    ⬆ Back to Top

  38. What is a freeze method

    The freeze() method is used to freeze an object. Freezing an object does not allow adding new properties to an object,prevents from removing and prevents changing the enumerability, configurability, or writability of existing properties. i.e, It returns the passed object and does not create a frozen copy.

    const obj = {
      prop: 100,
    };
    
    Object.freeze(obj);
    obj.prop = 200; // Throws an error in strict mode
    
    console.log(obj.prop); //100

    Remember freezing is only applied to the top-level properties in objects but not for nested objects. For example, let's try to freeze user object which has employment details as nested object and observe that details have been changed.

    const user = {
      name: 'John',
      employment: {
        department: 'IT'
      }
    };
    
    Object.freeze(user);
    user.employment.department = 'HR';

    Note: It causes a TypeError if the argument passed is not an object.

    ⬆ Back to Top

  39. What is the purpose of freeze method

    Below are the main benefits of using freeze method,

    1. It is used for freezing objects and arrays.
    2. It is used to make an object immutable.

    ⬆ Back to Top

  40. Why do I need to use freeze method

    In the Object-oriented paradigm, an existing API contains certain elements that are not intended to be extended, modified, or re-used outside of their current context. Hence it works as the final keyword which is used in various languages.

    ⬆ Back to Top

  41. How do you detect a browser language preference

    You can use navigator object to detect a browser language preference as below,

    var language =
      (navigator.languages && navigator.languages[0]) || // Chrome / Firefox
      navigator.language || // All browsers
      navigator.userLanguage; // IE <= 10
    
    console.log(language);

    ⬆ Back to Top

  42. How to convert string to title case with javascript

    Title case means that the first letter of each word is capitalized. You can convert a string to title case using the below function,

    function toTitleCase(str) {
      return str.replace(/\w\S*/g, function (txt) {
        return txt.charAt(0).toUpperCase() + txt.substring(1).toLowerCase();
      });
    }
    toTitleCase("good morning john"); // Good Morning John

    ⬆ Back to Top

  43. How do you detect javascript disabled in the page

    You can use the <noscript> tag to detect javascript disabled or not. The code block inside <noscript> gets executed when JavaScript is disabled, and is typically used to display alternative content when the page generated in JavaScript.

    <script type="javascript">
        // JS related code goes here
    </script>
    <noscript>
        <a href="next_page.html?noJS=true">JavaScript is disabled in the page. Please click Next Page</a>
    </noscript>

    ⬆ Back to Top

  44. What are various operators supported by javascript

    An operator is capable of manipulating(mathematical and logical computations) a certain value or operand. There are various operators supported by JavaScript as below,

    1. Arithmetic Operators: Includes + (Addition),– (Subtraction), * (Multiplication), / (Division), % (Modulus), + + (Increment) and – – (Decrement)
    2. Comparison Operators: Includes = =(Equal),!= (Not Equal), ===(Equal with type), > (Greater than),> = (Greater than or Equal to),< (Less than),<= (Less than or Equal to)
    3. Logical Operators: Includes &&(Logical AND),||(Logical OR),!(Logical NOT)
    4. Assignment Operators: Includes = (Assignment Operator), += (Add and Assignment Operator), – = (Subtract and Assignment Operator), *= (Multiply and Assignment), /= (Divide and Assignment), %= (Modules and Assignment)
    5. Ternary Operators: It includes conditional(: ?) Operator
    6. typeof Operator: It uses to find type of variable. The syntax looks like typeof variable

    ⬆ Back to Top

  45. What is a rest parameter

    Rest parameter is an improved way to handle function parameters which allows us to represent an indefinite number of arguments as an array. The syntax would be as below,

    function f(a, b, ...theArgs) {
      // ...
    }

    For example, let's take a sum example to calculate on dynamic number of parameters,

    function total(…args){
    let sum = 0;
    for(let i of args){
    sum+=i;
    }
    return sum;
    }
    console.log(fun(1,2)); //3
    console.log(fun(1,2,3)); //6
    console.log(fun(1,2,3,4)); //13
    console.log(fun(1,2,3,4,5)); //15

    Note: Rest parameter is added in ES2015 or ES6

    ⬆ Back to Top

  46. What happens if you do not use rest parameter as a last argument

    The rest parameter should be the last argument, as its job is to collect all the remaining arguments into an array. For example, if you define a function like below it doesn’t make any sense and will throw an error.

    function someFunc(a,…b,c){
    //You code goes here
    return;
    }

    ⬆ Back to Top

  47. What are the bitwise operators available in javascript

    Below are the list of bitwise logical operators used in JavaScript

    1. Bitwise AND ( & )
    2. Bitwise OR ( | )
    3. Bitwise XOR ( ^ )
    4. Bitwise NOT ( ~ )
    5. Left Shift ( << )
    6. Sign Propagating Right Shift ( >> )
    7. Zero fill Right Shift ( >>> )

    ⬆ Back to Top

  48. What is a spread operator

    Spread operator allows iterables( arrays / objects / strings ) to be expanded into single arguments/elements. Let's take an example to see this behavior,

    function calculateSum(x, y, z) {
      return x + y + z;
    }
    
    const numbers = [1, 2, 3];
    
    console.log(calculateSum(...numbers)); // 6

    ⬆ Back to Top

  49. How do you determine whether object is frozen or not

    Object.isFrozen() method is used to determine if an object is frozen or not.An object is frozen if all of the below conditions hold true,

    1. If it is not extensible.
    2. If all of its properties are non-configurable.
    3. If all its data properties are non-writable. The usage is going to be as follows,
    const object = {
      property: "Welcome JS world",
    };
    Object.freeze(object);
    console.log(Object.isFrozen(object));

    ⬆ Back to Top

  50. How do you determine two values same or not using object

    The Object.is() method determines whether two values are the same value. For example, the usage with different types of values would be,

    Object.is("hello", "hello"); // true
    Object.is(window, window); // true
    Object.is([], []); // false

    Two values are the same if one of the following holds:

    1. both undefined
    2. both null
    3. both true or both false
    4. both strings of the same length with the same characters in the same order
    5. both the same object (means both object have same reference)
    6. both numbers and both +0 both -0 both NaN both non-zero and both not NaN and both have the same value.

    ⬆ Back to Top