35+ ESSENTIAL JavaScript Interview Questions & Answers of 2020

35+ ESSENTIAL JavaScript Interview Question & Answer

Last updated on 03rd Jul 2020, Blog, Interview Questions

About author

Ranjith (Sr Technical Project Manager )

Highly Expertise in Respective Industry Domain with 10+ Years of Experience Also, He is a Technical Blog Writer for Past 4 Years to Renders A Kind Of Informative Knowledge for JOB Seeker

(5.0) | 16547 Ratings 1483

JavaScript is a high-level programming language, probably one of the most used programming languages in the world right now. It can be used to program the web browser or even servers.

To know the importance of JavaScript, disable JavaScript on your browser and try to load the Web page in it. Those Web pages will not work properly. Many contents in them may misbehave. Almost all modern browsers use the combination of JavaScript, CSS, and HTML.

JavaScript is an interpreted programming language. An interpreter is embedded in browsers like Google Chrome, Microsoft Internet Explorer, etc. So, its code can be handled by the JavaScript Engine of the browser.

JavaScript appeared in December 1995 and was initially called Live Script, although the name was soon changed for marketing reasons. It should not be confused with ‘Java’ which is also bearing some resemblance but is a completely different language.

1. What is JavaScript?

Ans: 

  JavaScript is a client-side as well as server side scripting language that can be inserted into HTML pages and is understood by web browsers. JavaScript is also an Object based Programming language

2. What are the features of JavaScript?

Ans: 

The Following are the features of JavaScript:

  • It is a lightweight, interpreted programming language.
  • It is designed for creating network-centric applications.
  • It is complementary to and integrated with Java.
  • It is an open and cross-platform scripting language.
java-script-features

3. Is JavaScript a case-sensitive language?

Ans: 

Yes, JavaScript is a case sensitive language.  The language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.

4. What are the advantages of JavaScript?

Ans: 

Following are the advantages of using JavaScript −

  • Less server interaction − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server.
  • Immediate feedback to the visitors − They don’t have to wait for a page reload to see if they have forgotten to enter something.
  • Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard.
  • Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors.
java-script-advantages

5. How can you create an object in JavaScript?

Ans: 

JavaScript supports Object concept very well. You can create an object using the object literal as follows −

  • var emp = {name: “Daniel”,age: 23};

6. How can you create an Array in JavaScript?

Ans: 

You can define arrays using the array literal as follows-

  • var x = [];var y = [1, 2, 3, 4, 5];

7. What is a name function in JavaScript & how to define it?

Ans: 

A named function declares a name as soon as it is defined. It can be defined using function keyword as :

  • function named(){// write code here} 

8. Can you assign an anonymous function to a variable and pass it as an argument to another function?

Ans: 

Yes! An anonymous function can be assigned to a variable. It can also be passed as an argument to another function.

9. What are argument objects in JavaScript & how to get the type of arguments passed to a function?

Ans: 

JavaScript variable arguments represents the arguments that are passed to a function. Using typeof operator, we can get the type of arguments passed to a function. For example −

  • function func(x){console.log(typeof x, arguments.length);}func(); //==> “undefined”, 0func(7); //==> “number”, 1func(“1”, “2”, “3”); //==> “string”, 3 

10. What are the scopes of a variable in JavaScript?

Ans: 

The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes.

  • Global Variables − A global variable has global scope which means it is visible everywhere in your JavaScript code.
  • Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

11. What is the purpose of ‘This’ operator in JavaScript?

Ans: 

The JavaScript this keyword refers to the object it belongs to. This has different values depending on where it is used. In a method, this refers to the owner object and in a function, this refers to the global object.

12.. What is Callback?

Ans: 

A callback is a plain JavaScript function passed to some method as an argument or option. It is a function that is to be executed after another function has finished executing, hence the name ‘call back‘. In JavaScript, functions are objects. Because of this, functions can take functions as arguments, and can be returned by other functions.

13. What is Closure? Give an example.

Ans: 

Closures are created whenever a variable that is defined outside the current scope is accessed from within some inner scope. It gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created. To use a closure, simply define a function inside another function and expose it.

14. Name some of the built-in methods and the values returned by them?

Ans: 

Built in MethodValues
CharAt()It returns the character at the specified index.
Concat()It joins two or more strings.
forEach()It calls a function for each element in the array.
indexOf()It returns the index within the calling String object of the first occurrence of the specified value.
length()It returns the length of the string.
pop()It removes the last element from an array and returns that element.
push()It adds one or more elements to the end of an array and returns the new length of the array.
reverse()It reverses the order of the elements of an array.

15. What are the variable naming conventions in JavaScript?

Ans: 

The following rules are to be followed while naming variables in JavaScript:

  • You should not use any of the JavaScript reserved keyword as variable name. For example, break or boolean variable names are not valid.
  • JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or the underscore character. For example, 123name is an invalid variable name but _123name or name123 is a valid one.
  • JavaScript variable names are case sensitive. For example, Test and test are two different variables.

16. How does Type of Operator work?

Ans: 

The typeof operator is used to get the data type of its operand. The operand can be either a literal or a data structure such as a variable, a function, or an object. It is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand.

17.  What is the use of window object?

Ans: 

  • The window object is created automatically by the browser that represents a window of a browser. It is not an object of JavaScript. It is a browser object.
  • The window object is used to display the popup dialog box.

Let’s see with description:

MethodDescription
alert()displays the alert box containing the message with ok button.
confirm()displays the confirm dialog box containing the message with ok and cancel button.
prompt()displays a dialog box to get input from the user.
open()opens the new window.
close()closes the current window.
setTimeout()performs the action after specified time like calling function, evaluating expressions.

18. Enumerate the differences between Java and JavaScript?

Ans: 

Java is a complete programming language. In contrast, JavaScript is a coded program that can be introduced to HTML pages. These two languages are not at all interdependent and are designed for the different intent. Java is an object – oriented programming (OOPS) or structured programming language like C++ or C whereas JavaScript is a client-side scripting language.

19. Which company developed JavaScript?

Ans: 

Netscape is the software company who developed JavaScript.

20. What are undeclared and undefined variables?

Ans: 

  • Undeclared variables are those that do not exist in a program and are not declared. If the program tries to read the value of an undeclared variable, then a runtime error is encountered.
  • Undefined variables are those that are declared in the program but have not been given any value. If the program tries to read the value of an undefined variable, an undefined value is returned.

    Subscribe For Free Demo

    21. Write the code for adding new elements dynamically?

    Ans: 

    • <html> 
    • <head> 
    • <title>t1</title> 
    • <script type=”text/javascript”> 
    • function addNode() { var newP = document.createElement(“p”); 
    • var textNode = document.createTextNode(” This is a new text node”); 
    • newP.appendChild(textNode); document.getElementById(“firstP”).appendChild(newP); } 
    • </script> </head> 
    • <body> <p id=”firstP”>firstP<p> </body> 
    • </html>

    22. What are global variables? How are these variable declared and what are the problems associated with using them?

    Ans: 

    Global variables are those that are available throughout the length of the code, that is, these have no scope. The var keyword is used to declare a local variable or object. If the var keyword is omitted, a global variable is declared.

    Example:

    • // Declare a global globalVariable = “Test”;

    The problems that are faced by using global variables are the clash of variable names of local and global scope. Also, it is difficult to debug and test the code that relies on global variables.

    23. What is BOM?

    Ans: 

    BOM stands for Browser Object Model. It provides interaction with the browser. The default object of a browser is a window. So, you can call all the functions of the window by specifying the window or directly. The window object provides various properties like document, history, screen, navigator, location, innerHeight, innerWidth,

    bom-image

    java script object model

    24. What is a prompt box?

    Ans: 

    A prompt box is a box which allows the user to enter input by providing a text box. Label and box will be provided to enter the text or number.

    25. Explain the unshift() method ?

    Ans: 

    This method is functional at the starting of the array, unlike the push(). It adds the desired number of elements to the top of an array.

    For example –

    • var name = [ “john” ];
    • name.unshift( “charlie” );
    • name.unshift( “joseph”, “Jane” );
    • console.log(name);

    The output is shown below:

    [” joseph “,” Jane “, ” charlie “, ” john “]

    26. Define unescape() and escape() functions? 

    Ans: 

    The escape () function is responsible for coding a string so as to make the transfer of the information from one computer to the other, across a network.

    For Example:

    • <script>
    • document.write(escape(“Hello? How are you!”));
    • </script>

    Output:

    Hello%3F%20How%20are%20you%21

    The unescape() function is very important as it decodes the coded string.

    It works in the following way. For example:

    • <script>
    • document.write(unescape(“Hello%3F%20How%20are%20you%21”));
    • </script>

    Output: Hello? How are you!

    27. What are disadvantages of using JavaScript?

    Ans: 

    We can not treat JavaScript as a full fledged programming language. It lacks the following important features:

    • Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason.
    • JavaScript can not be used for Networking applications because there is no such support available.
    • JavaScript doesn’t have any multithreading or multiprocess capabilities.

    28. What is same-origin policy?

    Ans: 

    The same-origin policy is a policy that prevents JavaScript from making requests across domain boundaries. An origin is defined as a combination of URL scheme, host name, and port number. If you enable this policy then it prevents a malicious script on one page from obtaining access to sensitive data on another web page using Document Object Model(DOM).

    29. In JavaScript what is an argument object?

    Ans: 

    The variables of JavaScript represent the arguments; that are passed to a function.

    30. What is the difference between test () and exec () methods?

    Ans: 

    Both test () and exec () are RegExp expression methods.

    • By using a test (), we will search a string for a given pattern, if it finds the matching text then it returns the Boolean value ‘true’ or else it returns ‘false’.
    • But in exec (), we will search a string for a given pattern, if it finds the matching text then it returns the pattern itself or else it returns ‘null’ value.
    Course Curriculum

    Get Trained with JavaScript Training from Top-Rated Industry Experts

    • Instructor-led Sessions
    • Real-life Case Studies
    • Assignments
    Explore Curriculum

    31. In the following code snippet can you please predict the output or If you get an error; please explain the error?

    <!DOCTYPE html><html><body><h2> <strong> Sample: Software Testing Help</strong> </h2><p style=’text-decoration:underline’>Example Const Variable </p><p id=”display”></p><script>const first_num;first_num =1000;document.getElementById(“display”).innerHTML = “First Number:”+ first_num;</script></body></html>

    Ans: 

    The ‘const’ variable ’first_num’ is not initialized with a value, so the code will produce a Syntax Error.

    Output of the code snippet:

    Error: Uncaught SyntaxError: Missing initializer in the const declaration

    32. Have you used any browser for debugging? If yes, how is it done?

    Ans: 

    By pressing the ‘F12’ key in the keyboard we can enable debugging in the browser. Chose the ‘Console’ tab to view the result.

    In Console, we can set breakpoints and view the value in variables. All the modern browsers have a built-in debugger with them (For Example: Chrome, Firefox, Opera, and Safari). This feature can be turned ON and OFF.

    33. What is the use of the ‘debugger’ keyword in JavaScript code?

    Ans: 

    Using the ‘debugger’ keyword in the code is like using breakpoints in the debugger. To test the code, the debugger must be enabled for the browser. If debugging is disabled for the browser, the code will not work. During debugging of the code, the remaining part should stop executing, before it goes to the next line.

    34. What is the purpose of void 0?

    Ans: 

    Void(0) is used to prevent the page from refreshing. This will be helpful to eliminate the unwanted side-effect, because it will return the undefined primitive value. It is commonly used for HTML document that uses href=”JavaScript:Void(0);” within an element. i.e, when you click a link, the browser loads a new page or refreshes the same page. But this behavior will be prevented using this expression. For example, the below link notify the message without reloading the page

    link:

    • <a href=”JavaScript:void(0);” onclick=”alert(‘Well done!’)”>Click Me!</a>

    35. Is JavaScript a compiled or interpreted language?

    Ans: 

    JavaScript is an interpreted language, not a compiled language. An interpreter in the browser reads over the JavaScript code, interprets each line, and runs it. Nowadays modern browsers use a technology known as Just-In-Time (JIT) compilation, which compiles JavaScript to executable bytecode just as it is about to run.

    36. What are the distinct types of Error Name Values?

    Ans: 

    There are 6 types of values in ‘Error Name’ Property.

    ErrorDescription
    Range ErrorWe will get this error if we use a number outside the range
    Syntax ErrorThis error raises when we use the incorrect syntax. (Please refer Ques No: 7)
    Reference ErrorThis error is thrown if used an undeclared variable Please refer Ques No: 19
    Eval ErrorThrown due to the error in eval(). New JavaScript version doesn’t have this error
    Type ErrorValue is outside the range of types used. Please refer Ques No :22
    URI ErrorDue to the usage of illegal characters.

    37. What is JavaScript Hoisting?

    Ans: 

    • While using the ‘JavaScript Hoisting’ method, when an interpreter runs the code, all the variables are hoisted to the top of the original /current scope. If you have a variable declared anywhere inside the code, then it is brought to the top.
    • This method is only applicable to the declaration of a variable and is not applicable for the initialization of a variable. Functions are also hoisted to the top, whereas function explanations are not hoisted to the top.

    Basically, where we declared the variable inside the code doesn’t matter much.

    38.  What are the characteristics of JavaScript ‘Strict Mode’?

    Ans: 

    Given below are the characteristics of ‘Strict Mode’:

    • ‘Strict Mode’ will stop developers from creating global variables.
    • Developers are restricted from using duplicate parameters.
    • Strict mode will restrict you from using the JavaScript keyword as a variable name or function name.
    • Strict mode is declared with ‘use strict’ keyword at the beginning of the script.
    • All browsers support strict mode.

    39. What are Self Invoking Functions?

    Ans: 

    They are also known as ‘Immediately Invoked Function Expressions’ or ‘Self Executing Anonymous Functions’. These functions are invoked automatically in the code, hence they are named as ‘Self Invoking Functions’.

    Usually, we define a function and invoke it, but if we want to execute a function automatically where it is explained, and if we are not going to call it again, we can use anonymous functions. And these types of functions have no name.

    40.What close() does in Java script?

    Ans: 

    In Javascript close() method is used to close the current window. You must write window.close() to ensure that this command is associated with a window object and not some other JavaScript object.

    41. What is the difference between let and var?

    Ans: 

    Both var and let are used for variable/ method declaration in javascript but the main difference between let and var is that var is function scoped whereas let is block scoped.

    42. Explain Closures in JavaScript?

    Ans: 

    Closures are the combination of lexical environment and function within which the function was declared. This allows JavaScript programmers to write better, more creative, concise and expressive codes. The closure will consist of all the local variables that were in-scope when the closure was created.

    Sure, closures appear to be complex and beyond the scope, but after you read this article, closures will be much more easy to understand and more simple for your everyday JavaScript programming tasks. JavaScript is  a very function-oriented language it gives the user freedom to use functions as the wish of the programmer.

    43. Explain JavaScript Event Delegation Model?

    Ans: 

    In JavaScript, there is some cool stuff that makes it the best of all. One of them is Delegation Model. When capturing and bubbling, allow functions to implement one single handler to many elements at one particular time then that is called event delegation. Event delegation allows you to add event listeners to one parent instead of specified nodes. That particular listener analyzes bubbled events to find a match on the child elements. Many people think it to be complicated but in reality, it is very simple if one starts understanding it.

    44. Describe negative infinity in JavaScript?

    Ans: 

    NEGATIVE_INFINITY property represents negative infinity and is a number in javascript, which is derived by ‘dividing negative number by zero’. It can be better understood as a number that is lower than any other number. Its properties are as follows:

    A number of objects need not to be created to access this static property.The value of negative infinity is the same as the negative value of the infinity property of the global object.

    The values behave differently than the mathematical infinity:

    • Any positive value, including POSITIVE_INFINITY, multiplied by NEGATIVE_INFINITY is NEGATIVE_INFINITY.
    • Any negative value, including NEGATIVE_INFINITY, multiplied by NEGATIVE_INFINITY is POSITIVE_INFINITY.
    • Zero multiplied by NEGATIVE_INFINITY is NaN.
    • NaN multiplied by NEGATIVE_INFINITY is NaN.
    • NEGATIVE_INFINITY, divided by any negative value except NEGATIVE_INFINITY, is POSITIVE_INFINITY.
    • NEGATIVE_INFINITY, divided by any positive value except POSITIVE_INFINITY, is NEGATIVE_INFINITY.
    • NEGATIVE_INFINITY, divided by either NEGATIVE_INFINITY or POSITIVE_INFINITY, is NaN.
    • Any number divided by NEGATIVE_INFINITY is zero.

    45. Explain function hoisting in JavaScript?

    Ans: 

    JavaScript’s default behavior that allows moving declarations to the top is called Hoisting. The 2 ways of creating functions in JavaScript are Function Declaration and Function Expression. Let’s find out more about these:

    Function Declaration

    A function with the specific parameters is known as function declarations. To create a variable in JavaScript is called declarations.

    e.g:

    • hoisted(); // logs “foo”
    • function hoisted() {
    • console.log(‘foo’);
    • }

    Function Expression

    When a function is created by using an expression it is called function expression.

    e.g:

    • notHoisted(); // TypeError: notHoisted is not a function
    • var notHoisted = function() {
    •    console.log(‘bar’);
    • };

    46. What is the use of let & const in JavaScript?

    Ans: 

    In modern javascript let & const are different ways of creating variables. Earlier in javascript, we use the var keyword for creating variables. let & const keyword is introduced in version ES6 with the vision of creating two different types of variables in javascript one is immutable and other is mutable.

    • const: It is used to create an immutable variable. Immutable variables are variables whose value is never changed in the complete life cycle of the program.
    • let: let is used to create a mutable variable. Mutable variables are normal variables like var that can be changed any number of time.

    47. Explain Arrow functions?

    Ans: 

    An arrow function is a concise and short way to write function expressions in Es6 or above.A row functions cannot be used as constructors and also does not supports this, arguments, super, or new.target keywords. It is best suited for non-method functions. In general an arrow function looks like

    • const function_name= ()=>{}
    • const greet=()=>{console.log(‘hello’);}
    •  greet();

    48. What are exports and imports?

    Ans: 

    Imports and exports help us to write modular javascript code. Using Imports and exports we can split our code into multiple files. Imports allow taking only some specific variables or methods of a file. We can import methods or variables that are exported by a module. See the below example for more detail.

    • //index.js
    •  import name,age from ‘./person’; 
    •  console.log(name);
    •  console.log(age);
    •  //person.js
    •  let name =’Sharad’, occupation=’developer’, age =26;
    •  export { name, age}; 

    49. What is difference between module.exports and export?

    Ans: 

    The module is a plain JavaScript object with an exports property. Exports is a plain JavaScript variable that happens to be set to module.exports. At the end of your file, node.js will basically ‘return’ module.exports to the require function. A simplified way to view a JS file in Node could be this:

    • var module = { exports: {} };
    • var exports = module.exports;
    • // your code
    • return module.exports;

    If you set a property on exports, like exports.a = 9;, that will set module.exports.a as well because objects are passed around as references in JavaScript, which means that if you set multiple variables to the same object, they are all the same object; so then exports and module.exports are the same objects.

    But if you set exports to something new, it will no longer be set to module.exports, so exports and module.exports are no longer the same objects.

    50. How to import all exports of a file as an object? 

    Ans: 

    import * as object name from ‘./file.js’ is used to import all exported members as an object. You can simply access the exported variables or methods using dot (.) operator of the object.

    Example:

    • objectname.member1;
    • objectname.member2;
    • objectname.memberfunc();

    51. Explain “use strict” ? 

    Ans: 

    “use strict” is a java script directive that is introduced in Es5. The purpose of using .“use s1trict” directive is to enforce the code is executed in strict mode. In strict mode we can’t use a variable without declaring it. “use strict” is ignored by earlier versions of Java script.

    Course Curriculum

    Gain In-Depth Knowledge On JavaScript Certification Course to Build Your Skills

    Weekday / Weekend BatchesSee Batch Details

    52. Explain Event bubbling and Event Capturing in JavaScript? 

    Ans: 

    Event Capture and Bubbling: In HTML DOM API there are two ways of event propagation and determines the order in which event will be received. The two ways are Event Bubbling and Event Capturing. The first method event bubbling directs the event to its intended target, and the second is called event capture in which the event goes down to the element.

    Event Capture

    The capture procedure is rarely used but when it’s used it proves to be very helpful. This process is also called ‘trickling’. In this process, the event is captured first by the outermost element and then propagated to the innermost element. For example:

    • <div>
    • <ul>
    • <li></li>
    • </ul>
    • </div>

    From the above example, suppose the click event did occur in the ‘li’ element, in that case capturing event it will be first handled ‘div’, then ‘ul’ and at last the target element will be hit that is ‘li’

    Event Bubbling

    Bubbling just works like the bubbles, the event gets handled by the innermost element and then propagated to the outer element.

    • <div>
    •  <ul>
    • <li></li>
    • </ul>
    • </div>

    From the above example, suppose the click event did occur in the ‘li’ element in bubbling model the event will be handled first by ‘li’ then by ‘ul’ and at last by ‘div’ element.

    53. In Javascript are calculations with fractional numbers guaranteed to be precise? 

    Ans: 

    NO, calculations with fractional numbers are not guaranteed to be precise in Javascript

    54. List the comparison operators supported by Javascript?

    Ans: 

    Java script supports below comparison operators

    • > Greater than
    • < Less than
    • <= Less than or equal to
    • >= Greater than or equal to
    • == Equal to
    • != Not Equal to
    • === Equal to with datatype check
    • !== Not equal to with datatype check

    55. How do you declare variables in Java script?

    Ans: 

    In Javascript variable are declared using the var keyword.A variable must begin with A letter, $ or _.

    eg:

    • var myVar=”Online Interview Questions”;

    PS: All variables in Javascript are Case sensitive.

    56. What will happen if an infinite while loop is run in Javascript? 

    Ans: 

    The program will crash the browser.

    57.  List HTML DOM mouse events? 

    Ans: 

    HTML DOM mouse events

    • onclick
    • ondblclick
    • mousemove
    • mousedown
    • mouseover
    • mouseout
    • mouseup

    58.  How to get the last index of a string in Javascript? 

    Ans: 

    string.length-1 is used to get the last index of a string in Javascript

    Example Usage:-

    • var myString=”JavascriptQuestions”;
    • console.log(myString.length-1);

    59. How to get the primitive value of a string in Javascript? 

    Ans: 

    In Javascript valueOf() method is used to get the primitive value of a string.

    Example Usage:

    • var myVar= “Hi!”
    • console.log(myVar.valueOf())

    60. What does the instanceof operator do?

    Ans: 

    In Java script instance of operator checks whether the object is an instance of a class or not:

    Example Usage

    • Square.prototype = new Square();
    • console.log(sq instanceof Square); // true

    61. What is Javascript BOM? 

    Ans: 

    BOM stands for “Browser Object Modal” that allows Java script to ‘talk’ to the browser, no standards, modern browsers implement similar BOMS – window, screen, location, history, navigator, timing, cookies.

    62.What are different types of Popup boxes available in Javascript?

    Ans: 


      In Javascript there are 3 types of Popup Boxes are available, they are

    • Alert
    • Confirm
    • Prompt

    63. What are the ways that you create an array in Javascript?

    Ans: 

    There are 3 different ways to create an array in Javascript. They are

    • By array literal usage:

    • var myArray=[value1,value2…valueN];

    • By creating instance of Array usage:

    • var myArray=new Array();

    • By using an Array constructor usage:

    • var myArray=new Array(‘value1′,’value2′,…,’valueN’);

    64. What is the ‘Strict’ mode in JavaScript and how can it be enabled?

    Ans: 

    Strict mode is a way to introduce better error-checking into your code. When you use strict mode, you cannot, for example, use implicitly declared variables, or assign a value to a read-only property, or add a property to an object that is not extensible.

    You can enable strict mode by adding “use strict”; at the beginning of a file, a program, or a function. This kind of declaration is known as a directive prologue. The scope of a strict mode declaration depends on its context. If it is declared in a global context (outside the scope of a function), all the code in the program is in strict mode. If it is declared in a function, all the code in the function is in strict mode.

    65. How to calculate Fibonacci numbers in JavaScript? 

    Ans: 

    Calculating Fibonacci series in JavaScript

    Fibonacci numbers are a sequence of numbers where each value is the sum of the previous two, starting with 0 and 1. The first few values are 0, 1, 1, 2, 3, 5, 8, 13 ,…,

    • function fib(n) {
    • var a=0, b=1;
    • for (var i=0; i < n; i++) {
    • var temp = a+b; 
    • a = b;
    • b = temp;
    • }
    • return a;
    • }

    66. What is the difference between the substr() and substring() functions in JavaScript?

    Ans: 

    Difference between the substr() and substring() functions in JavaScript.

    The substr() function has the form substr(startIndex,length). It returns the substring from startIndex and returns ‘length’ number of characters.

    • var s = “hello”;
    • ( s.substr(1,4) == “ello” ) // true

    The substring() function has the form substring(startIndex,endIndex). It returns the substring from startIndex up to endIndex – 1.

    • var s = “hello”;
    • ( s.substring(1,4) == “ell” ) // true

    67. What are different types of Inheritance? Which Inheritance is followed in Javascript? 

    Ans: 

    There are two types of Inheritance in OOPS Classic and Prototypical Inheritance. Javascript follows Prototypical Inheritance.

    68.  What is the Different between Null and Undefined? 

    Ans: 

    Both null and undefined have an empty value, but the difference between these two is:

    • In undefined case, we don’t assign a value for the variable.
    • In the null case, we assign a zero value to the variable.

    69.  What are the ways used to read and write a file in JavaScript?

    Ans: 

    Two ways are available to read and write a file, they are:

    • JavaScript Expressions
    • Webpages and Active X objects

    70. How to create an array in the JavaScript?

    Ans: 

    Arrays are used to store various values in the single variable.

    Defining an array in JavaScript:

    • var mobile = [“Oppo”, “ Samsung”, “Vivo”] By using a new keyword: Var mobile = new array(“ Oppo”, “Samsung”, “Vivo”) 

    Javascript Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

    71. Mention the different types of functions that are supported by JavaScript? Define each of them?

    Ans: 

    There are two types of functions which are supported by JavaScript. They are –

    • Anonymous function- This type of function generally has no name and this is the difference between it and a normal function.  
    • Named function- On the other hand, this function is named properly and specifically.

    72. What is the difference between the scope of the variables in JavaScript? 

    Ans: 

    JavaScript variables have different scope. Scope of the variable is nothing but the functionality of the variable.

    • Global variables- Global variables consist of global scope whereas these variables can be utilized in the whole program repeatedly.
    • Local Variables- Local variables have no scope and used only once in the whole program.

    73.  What is mean by name function?

    Ans: 

    The named function in JavaScript defines the name as well as value to a function. It is defined by using the keyword 

    “function”

    • function named(){// write code}

    74. What is argument objects in javascript?

    Ans: 

    The JavaScript variable represents the arguments that can be passed to the function. By using, ‘type of’ operator we can represent the argument objects.

    Example:

    • function  fun(a){console.log(type of a, arguments.length);}
    • fun(7);
    • fun( “2”, “3”, “4”);
    • fun(); 

      75. What are the primitive data types in JavaScript?

    Ans: 

    A primitive is a basic data type that’s not built out of other data types. It can only represent one single value. All primitives are built-in data types by necessity, (the compiler has to know about them,) but not all built-in data types are primitives.

    In JavaScript there are 5 primitive data types are available they are undefined, null, boolean, string and number are available.Everything else in Javascript is an object

    76. What is “===” operator?

    Ans: 

    “===” is a strict equality operator, returns a true value, if the two operands have the same value.

     77. How can we read the properties of a JavaScript?

    Ans: 

    Using dot(.) notation we can read and write the properties of JS.

    78. What is the difference between Attributes and properties?

    Ans: 

    • Attributes- Attributes provide the information about the details given to objects like name, age, id, etc,
    • Properties- Properties gives information about the values given to the objects.

    79. What are the possible ways to define a variable in JavaScript?

    Ans: 

    There are three possible ways to declare a variable in JavaScript are:

    • Var- variables and values of variables can be declared to the Variable statement by Variable statement. Example – var b = 20;. Declaration of variables should be done before the execution of code.
    • Const- A constant variables are assigned with one value only once before the execution of code.
    • let- If let statements are used in the variable declaration, the variable values can be reassigned before the execution of code.

    80. What are the terms BOM and DOM in JavaScript?

    Ans: 

    • BOM- BOM is a Browser Object Model, in which the window object is supported by all the browsers. The JavaScript objects, variables and functions also become the members of the window object. This model deals with the objects of browsers like location, navigator, history, and screen.
    • DOM- DOM is a Document Object Model in a JavaScript helps to access document and HTML elements. When a web page is loaded the browser creates a DOM for the page. All the objects on the page all .arranged in an order.

    81. What’s the difference between undefined and not defined in JavaScript

    Ans: 

    In JavaScript if you try to use a variable that doesn’t exist and has not been declared, then JavaScript will throw an error var name is not defined and the script will stop executing thereafter. But If you use typeof undeclared_variable then it will return undefined.

    Before starting further discussion let’s understand the difference between declaration and definition.

    var x is a declaration because you are not defining what value it holds yet, but you are declaring its existence and the need for memory allocation.

    • var x; // declaring x
    • console.log(x); // output: undefined

    var x = 1 is both declaration and definition (also we can say we are doing initialisation), Here declaration and assignment of value happen inline for variable x, In JavaScript every variable declaration and function declaration brings to the top of its current scope in which it’s declared then assignment happen in order this term is called hoisting.

    A variable can be declared but not defined. When we try to access it, It will result undefined.

    • var x; // Declaration
    • typeof x === ‘undefined’; // Will return true

    A variable can be neither declared nor defined. When we try to reference such variable then the result will be not defined.

    • console.log(y);  // Output: ReferenceError: y is not defined

    82. For which value of x the results of the following statements are not the same?

    //  if( x <= 100 ) {…}

    if( !(x > 100) ) {…}

    Ans: 

    NaN <= 100 is false and NaN > 100 is also false, so if the value of x is NaN, the statements are not the same.

    The same holds true for any value of x that being converted to Number, returns NaN, e.g.: undefined, [1,2,5], {a:22} , etc.

    This is why you need to pay attention when you deal with numeric variables. NaN can’t be equal, less than or more than any other numeric value, so the only reliable way to check if the value is NaN, is to use isNaN() function.

    83. What is the drawback of declaring methods directly in JavaScript objects?

    Ans: 

    One of the drawback of declaring methods directly in JavaScript objects is that they are very memory inefficient. When you do that, a new copy of the method is created for each instance of an object. Let’s see it on example:

    • var Employee = function (name, company, salary) {
    •   this.name = name || “”;       
    •   this.company = company || “”;
    •   this.salary = salary || 5000;
    •   // We can create a method like this:
    •   this.formatSalary = function () {
    •       return “$ ” + this.salary;
    •   };
    • };
    • // we can also create method in Employee’s prototype:
    • Employee.prototype.formatSalary2 = function() {
    •     return “$ ” + this.salary;
    • }
    • //creating objects
    • var emp1 = new Employee(‘Yuri Garagin’, ‘Company 1’, 1000000);
    • var emp2 = new Employee(‘Dinesh Gupta’, ‘Company 2’, 1039999);
    • var emp3 = new Employee(‘Erich Fromm’, ‘Company 3’, 1299483);

    Here each instance variable emp1, emp2, emp3 has own copy of formatSalary method. However the formatSalary2 will only be added once to an object Employee.prototype.

    84. What is “closure” in javascript? Can you provide an example?

    Ans: 

    A closure is a function defined inside another function (called parent function) and has access to the variable which is declared and defined in parent function scope.

    The closure has access to the variable in three scopes:

    • Variable declared in his own scope
    • Variable declared in parent function scope
    • Variable declared in the global namespace

    • var globalVar = “abc”;
    • // Parent self invoking function
    • (function outerFunction (outerArg) { // begin of scope outerFunction
    •   // Variable declared in outerFunction function scope
    •   var outerFuncVar = ‘x’;    
    •   // Closure self-invoking function
    •   (function innerFunction (innerArg) { // begin of scope innerFunction
    •     // variable declared in innerFunction function scope
    •     var innerFuncVar = “y”;
    •     console.log(         
    •       “outerArg = ” + outerArg + “\n” +
    •       “outerFuncVar = ” + outerFuncVar + “\n” +
    •       “innerArg = ” + innerArg + “\n” +
    •       “innerFuncVar = ” + innerFuncVar + “\n” +
    •       “globalVar = ” + globalVar);
    •   // end of scope innerFunction
    •   })(5); // Pass 5 as parameter
    • // end of scope outerFunction
    • })(7); // Pass 7 as parameter

    InnerFunction is closure which is defined inside outerFunction and has access to all variable which is declared and defined in outerFunction scope. In addition to this function defined inside the function as closure has access to the variable which is declared in global namespace.

    Output of above code would be:

    outerArg = 7

    outerFuncVar = x

    innerArg = 5

    innerFuncVar = y

    globalVar = abc

    85. Write a mul function which will work properly when invoked with following syntax.

    console.log(mul(2)(3)(4)); // output : 24

    console.log(mul(4)(3)(4)); // output : 48

    Ans: 

    Below is the code followed by the explanation of how it works:

    • function mul (x) {
    •   return function (y) { // anonymous function
    •     return function (z) { // anonymous function
    •       return x * y * z;
    •     };
    •   };
    • }

    Here the mul function accepts the first argument and returns the anonymous function which takes the second parameter and returns the anonymous function which takes the third parameter and returns the multiplication of arguments which is being passed in successive

    In Javascript function defined inside has access to outer function variable and function is the first class object so it can be returned by the function as well and passed as an argument in another function.

    • A function is an instance of the Object type
    • A function can have properties and has a link back to its constructor method
    • A function can be stored as variable
    • A function can be pass as a parameter to another function
    • A function can be returned from another function

    86. How to empty an array in JavaScript?

    For instance:

    var arrayList =  [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’];

    How can we empty the array above?

    Ans: 

    There are a couple of ways by which we can empty an array, So let’s discuss all the possible way by which we can empty an array

    Method 1

    • arrayList = [];

    The code above will set the variable arrayList to a new empty array. This is recommended if you don’t have references to the original array arrayList anywhere else because It will actually create a new empty array. You should be careful with this way of empty the array, because if you have referenced this array from another variable, then the original reference array will remain unchanged, Only use this way if you have only referenced the array by its original variable arrayList.

    For instance:

    • var arrayList = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]; // Created array
    • var anotherArrayList = arrayList;  // Referenced arrayList by another variable
    • arrayList = []; // Empty the array
    • console.log(anotherArrayList); // Output [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]

    Method 2

    • arrayList.length = 0;

    The code above will clear the existing array by setting its length to 0. This way of emptying an array will also update all the reference variables that point to the original array.

    For instance:

    • var arrayList = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]; // Created array
    • var anotherArrayList = arrayList;  // Referenced arrayList by another variable
    • arrayList.length = 0; // Empty the array by setting length to 0
    • console.log(anotherArrayList); // Output []

    Method 3

    • arrayList.splice(0, arrayList.length);

    Above implementation will also work perfectly. This way of empty the array will also update all the references of the original array.

    • var arrayList = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]; // Created array
    • var anotherArrayList = arrayList;  // Referenced arrayList by another variable
    • arrayList.splice(0, arrayList.length); // Empty the array by setting length to 0
    • console.log(anotherArrayList); // Output []

    Method 4

    • while(arrayList.length) {
    •   arrayList.pop();
    • }

    Above implementation can also empty the array. But not recommended to use often.

    87. How to check if an object is an array or not?

    Ans: 

    The best way to find whether an object is instance of a particular class or not using toString method from Object.prototype

    • var arrayList = [1 , 2, 3];

    One of the best use cases of type checking of an object is when we do method overloading in JavaScript. To understand this, let’s say we have a method called greet which can take a single string and also a list of strings. To make our greet method workable in both situation we need to know what kind of parameter is being passed: is it single value or list of values?

    • function greet(param) {
    •   if() {
    •     // here have to check whether param is array or not
    •   }
    •   else {
    •   }
    • }

    However, in the above implementation it might not necessary to check the type of the array, we can check for single value string and put array logic code in else block, let see below code for the same.

    • function greet(param) {
    •    if(typeof param === ‘string’) {
    •    }
    •    else {
    •      // If param is of type array then this block of code would execute
    •    }
    •  }

    Now it’s fine we can go with the previous two implementations, but when we have a situation like a parameter can be single value, array, and object type then we will be in trouble.

    Coming back to checking the type of an object, As we mentioned that we can use Object.prototype.toString

    • if(Object.prototype.toString.call(arrayList) === ‘[object Array]’) {
    •   console.log(‘Array!’);
    • }

    If you are using jQuery then you can also used jQuery isArray method:

    • if($.isArray(arrayList)) {
    •   console.log(‘Array’);
    • } else {
    •   console.log(‘Not an array’);
    • }

    FYI jQuery uses Object.prototype.toString.call internally to check whether an object is an array or not.

    In modern browser, you can also use:

    • Array.isArray(arrayList);

    Array.isArray is supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5

    88. What will be the output of the following code?

    var output = (function(x) {

      delete x;

      return x;

    })(0);

    console.log(output);

    Ans: 

    The code above will output 0 as output. delete operator is used to delete a property from an object. Here x is not an object it’s local variable. delete operator doesn’t affect local variables.

    89. What will be the output of the following code?

    var x = 1;

    var; output = (function() {

      delete x;

      return x;

    })();

    console.log(output);

    Ans: 

    The code above will output 1 as output. delete operator is used to delete a property from an object. Here x is not an object it’s global variable of type number.

    90. What will be the output of the following code?

    var x = { foo : 1};

    var output = (function() {

      delete x.foo;

      return x.foo;

    })();

    console.log(output);

    Ans: 

    The code above will output undefined as output. delete operator is used to delete a property from an object. Here x is an object which has foo as a property and from a self-invoking function, we are deleting the foo property of object x and after deletion, we are trying to reference deleted property foo which result undefined.

    91. What is the difference between native, host and user objects?

    Ans: 

    Native objects are objects that are part of the JavaScript language defined by the ECMAScript specification. For example, String, Math, RegExp, Object, Function etc core objects defined in the ECMAScript spec. Host objects are objects provided by the browser or runtime environment (Node). For example, window, Xml, Http, Request, DOM nodes etc considered as host objects. User objects are objects defined in the javascript code. For example, User object created for profile information.

    92. What are the tools or techniques used for debugging JavaScript code?

    Ans: 

    You can use below tools or techniques for debugging javascript

    • Chrome Devtools
    • debugger statement
    • Good old console.log statement

    93. What are the pros and cons of promises over callbacks?

    Ans: 

    Below are the list of pros and cons of promises over callbacks,

    Pros:

    • It avoids callback hell which is unreadable
    • Easy to write sequential asynchronous code with .then()
    • Easy to write parallel asynchronous code with Promise.all()
    • Solves some of the common problems of callbacks(call the callback too late, too early, many times and swallow errors/exceptions)

    Cons:

    • It makes little complex code
    • You need to load a polyfill if ES6 is not supported

    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free