Interview questions javascript pdf
For example, the syntax of promise. Note: Remember that the order of the promises output the result is maintained as per input order. Let's take an example of race method where promise2 is resolved first. This way it prevents certain actions from being taken and throws more exceptions. The literal expression "use strict"; instructs the browser to use the javascript code in the Strict mode. Strict mode is useful to write "secure" JavaScript by notifying "bad syntax" into real errors.
For example, it eliminates accidentally creating a global variable by throwing an error and also throws an error for assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object. The strict mode is declared by adding "use strict"; to the beginning of a script or a function.
If declared at the beginning of a script, it has global scope. The double exclamation or negation!! If it was falsey e. For example, you can test IE version using this expression as below,. Note: The expression!! You can use the JavaScript typeof operator to find the type of a JavaScript variable. It returns the type of a variable or an expression. The undefined property indicates that a variable has not been assigned a value, or not declared at all. The type of undefined value is undefined too.
The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values. The type of null value is object. You can empty the variable by setting the value to null. The eval function evaluates JavaScript code represented as a string. The string can be a JavaScript expression, variable, statement, or sequence of statements. The window. You can load previous and next URLs in the history using back and next methods.
The mouseEvent getModifierState is used to return a boolean value that indicates whether the specified modifier key is activated or not. The modifiers such as CapsLock, ScrollLock and NumLock are activated when they are clicked, and deactivated when they are clicked again.
The isNaN function is used to determine whether a value is an illegal number Not-a-Number or not. Otherwise it returns false. Global variables are those that are available throughout the length of the code without any scope. The var keyword is used to declare a local variable but if you omit it then it will become global variable. The problem with global variables is the conflict of variable names of local and global scope. It is also difficult to debug and test the code that relies on global variables.
The NaN property is a global property that represents "Not-a-Number" value. It is very rare to use NaN in a program but it can be used as return value for few cases. The isFinite function is used to determine whether a number is a finite, legal number. Event flow is the order in which event is received on the web page. When you click an element that is nested in various other elements, before your click actually reaches its destination, or target element, it must trigger the click event for each of its parent elements first, starting at the top with the global window object.
There are two ways of event flow. Event bubbling is a type of event propagation where the event first triggers on the innermost target element, and then successively triggers on the ancestors parents of the target element in the same nesting hierarchy till it reaches the outermost DOM element. Event capturing is a type of event propagation where the event is first captured by the outermost element, and then successively triggers on the descendants children of the target element in the same nesting hierarchy till it reaches the innermost DOM element.
You can submit a form using document. All the form input's information is submitted using onsubmit event handler. Some of the OS properties are available under platform property,. The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for assets stylesheets, images, and subframes to finish loading. Whereas The load event is fired when the whole page has loaded, including all dependent resources stylesheets, images.
Host objects are objects provided by the browser or runtime environment Node. User objects are objects defined in the javascript code. For example, User objects created for profile information. For example, the below HTML element has 2 attributes type and value,.
The same-origin policy is a policy that prevents JavaScript from making requests across domain boundaries. An origin is defined as a combination of URI scheme, hostname, 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.
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. But this behavior will be prevented using this expression. For example, the below link notify the message without reloading the page. 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.
Yes, JavaScript is a case sensitive language. No, they are entirely two different programming languages and have nothing to do with each other.
But both of them are Object Oriented Programming languages and like many other languages, they follow similar syntax for basic features if, else, for, switch, break, continue etc. Events are "things" that happen to HTML elements. Some of the examples of HTML events are,. Initially it was developed under the name Mocha , but later the language was officially called LiveScript when it first shipped in beta releases of Netscape.
The preventDefault method cancels the event if it is cancelable, meaning that the default action or behaviour that belongs to the event will not occur. For example, prevent form submission when clicking on submit button and prevent opening the page URL when clicking on hyperlink are some common use cases. The stopPropagation method is used to stop the event from bubbling up the event chain. For example, the below nested divs with stopPropagation method prevents default event propagation when clicking on nested div Div1.
It consists of the objects navigator, history, screen, location and document which are children of the window. The Browser Object Model is not standardized and can change based on different browsers. The setTimeout method is used to call a function or evaluate an expression after a specified number of milliseconds.
For example, let's log a message after 2 seconds using setTimeout method,. The setInterval method is used to call a function or evaluate an expression at specified intervals in milliseconds. For example, let's log a message after 2 seconds using setInterval method,. JavaScript is a single-threaded language.
Because the language specification does not allow the programmer to write code so that the interpreter can run parts of it in parallel in multiple threads or processes. Event delegation is a technique for listening to events where you delegate a parent element as the listener for all of the events that happen inside it.
For example, if you wanted to detect field changes in inside a specific form, you can use event delegation technique,. It is based on a subset of JavaScript language in the way objects are built in JavaScript.
When sending data to a web server, the data has to be in a string format. You can achieve this by converting JSON object into a string using stringify method. When receiving the data from a web server, the data is always in a string format. But you can convert this string value to a javascript object using parse method. When exchanging data between a browser and a server, the data can only be text. Since JSON is text only, it can easily be sent to and from a server, and used as a data format by any programming language.
The clearTimeout function is used in javascript to clear the timeout which has been set by setTimeout function before that. For example, the below setTimeout method is used to display the message after 3 seconds.
This timeout can be cleared by the clearTimeout method. The clearInterval function is used in javascript to clear the interval which has been set by setInterval function. For example, the below setInterval method is used to display the message for every 3 seconds. This interval can be cleared by the clearInterval method. In vanilla javascript, you can redirect to a new page using the location property of window object.
The syntax would be as follows,. You can validate an email in javascript using regular expressions. It is recommended to do validations on the server side instead of the client side.
Because the javascript can be disabled on the client side. You can use window. You can also use document.
URL for read-only purposes but this solution has issues in FF. The below Location object properties can be used to access URL components of the page,. Let's see an example to get the client code value from URL query string,. You can use the for-in loop to loop through javascript object. You can also make sure that the key you get is an actual property of an object, and doesn't come from the prototype using hasOwnProperty method.
The arguments object is an Array-like object accessible inside functions that contains the values of the arguments passed to that function. For example, let's see how to use arguments object inside sum function,. Note: You can't apply array methods on arguments object. But you can convert into a regular array as below. You can create a function which uses a chain of string methods such as charAt, toUpperCase and slice methods to generate a string with the first letter in uppercase.
The for-loop is a commonly used iteration syntax in javascript. It has both pros and cons. You can use new Date to generate a new Date object containing the current date and time. You need to use date. But it is not yet supported in all browsers. Let's see an example to see this usage,. JavaScript provided a trim method on string types to trim any whitespaces present at the beginning or ending of the string.
There are two possible solutions to add new properties to an object. Let's take a simple object to explain these solutions. No,that's not a special operator. But it is a combination of 2 standard operators one after the other,. You can use the logical or operator in an assignment expression to provide a default value. The syntax looks like as below,. As per the above expression, variable 'a 'will get the value of 'c' only if 'b' is falsy if is null, false, undefined, 0, empty string, or NaN , otherwise 'a' will get the value of 'b'.
An application shell or app shell architecture is one way to build a Progressive Web App that reliably and instantly loads on your users' screens, similar to what you see in native applications.
It is useful for getting some initial HTML to the screen fast without a network. You can use function. Let's take an example of sum function to calculate the sum of numbers,. A polyfill is a piece of JS code used to provide modern functionality on older browsers that do not natively support it.
The break statement is used to "jump out" of a loop. The continue statement is used to "jump over" one iteration in the loop. 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,. It is recommended to keep all declarations at the top of each script or function.
The benefits of doing this are,. 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. JSON arrays are written inside square brackets and arrays contain javascript objects. For example, the JSON array of users would be as below,. You can use Math. For example, if you want generate random integers between 1 to 10, the multiplication factor should be 10,.
Note: Math. Yes, you can create a proper random function to return a random number between min and max both included. 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 ES module syntax, i. Initially this has been popularized by the ES module bundler rollup. Tree Shaking can significantly reduce the code size in any application.
Tree shaking is implemented in Rollup and Webpack bundlers. 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.
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,. For example, the regular expression or search pattern with case-insensitive username would be,.
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. The replace method is used to return a modified string where the pattern is replaced.
Modifiers can be used to perform case-insensitive and global searches. Let's list down some of the modifiers,. Regular Expressions provide a group of patterns in order to match characters. Basically they are categorized into 3 types,.
RegExp object is a regular expression object with predefined properties and methods. Let's see the simple usage of RegExp object,. 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.
The output is going to be 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 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. 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. No, you cannot use the reserved words as variables, labels, object or function names. Let's see one simple example,.
You can use regex which returns a true or false value depending on whether or not the user is browsing with a mobile. 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,. You can programmatically get the image and check the dimensions width and height using 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,. 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,. The conditional ternary operator is the only JavaScript operator that takes three operands which acts as a shortcut for if statements. The syntax is going to be as below,.
It is recommended to use semicolons after every statement in JavaScript. For example, in the below case it throws an error ".. 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 " 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.
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. Title case means that the first letter of each word is capitalized. You can convert a string to title case using the below function,. An operator is capable of manipulating mathematical and logical computations a certain value or operand.
There are various operators supported by JavaScript as below,. 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,. The rest parameter should be the last argument, as its job is to collect all the remaining arguments into an array. Let's take an example to see this behavior,. An object is frozen if all of the below conditions hold true,. The Object. For example, the usage with different types of values would be,. You can use the Object.
It returns the target object which has properties and values copied from the target object. As observed in the above code, there is a common property b from source to target so it's value has been overwritten. The Proxy object is used to define custom behavior for fundamental operations such as property lookup, assignment, enumeration, function invocation, etc.
In the above code, it uses get handler which define the behavior of the proxy when an operation is performed on it. But values of present properties can still be changed as long as they are writable. Let's see the below example to understand more about seal method. If an object is frozen using the Object. An object is sealed if all of the below conditions hold true. Let's see the functionality of object.
For example, you can get the keys of a user object,. It returns a new object with the specified prototype object and properties. WeakSet is used to store a collection of weakly weak references held objects. The main difference is that references to objects in Set are strong while references to objects in WeakSet are weak. Other differences are,. In this case, keys must be objects and the values can be arbitrary values. The syntax is looking like as below,.
The main difference is that references to key objects in Map are strong while references to key objects in WeakMap are weak. The uneval is an inbuilt function which is used to create a string representation of the source code of an Object.
It is a top-level function and is not associated with any object. Let's see the below example to know more about it's functionality,.
The window object provided a print method which is used to print the contents of the current window. It opens a Print dialog box which lets you choose between various printing options. Let's see the usage of print method in an example,. Note: In most browsers, it will block while the print dialog is open. The uneval function returns the source of a given object; whereas the eval function does the opposite, by evaluating that source code in a different memory area. Let's see an example to clarify the difference,.
An anonymous function is a function without a name! Anonymous functions are commonly assigned to a variable name or used as a callback function. A local variable takes precedence over a global variable with the same name.
Let's see this behavior in an example. ECMAScript 5 introduced javascript object accessors or computed properties through getters and setters. Getters uses the get keyword whereas Setters uses the set keyword. Let's see an example to know how to define property,. Both have similar results until unless you use classes.
If you use get the property will be defined on the prototype of the object whereas using Object. Yes, You can use the Object. For example, the below counter object uses increment, decrement, add and subtract properties,. The switch case statement in JavaScript is used for decision making purposes. In a few cases, using the switch case statement is going to be more convenient than if-else statements. The above multi-way branch statement provides an easy way to dispatch execution to different parts of code based on the value of the expression.
A primitive data type is data that has a primitive value which has no properties or methods. There are 7 types of primitive data types. An error object is a built in error object that provides error information when an error occurs.
It has two properties: name and message. For example, the below function logs error details,. A SyntaxError is thrown if you try to evaluate code with a syntax error. For example, the below missing quote for the function parameter throws a syntax error. Skip to content. Star 7. List of JavaScript Interview Questions 7.
Branches Tags. Could not load branches. Could not load tags. Latest commit. Git stats commits. Failed to load latest commit information. Update pandoc version. Oct 2, Add superArrayOfObjects to the coding-exercies.
Jul 18, Add BOM diagram. Jun 27, Jun 19, Dec 24, View code. How to invoke an IIFE without any extra brackets? Is that possible to use expressions in switch cases? What is the easiest way to ignore promise errors?
How do style the console output using CSS? What is nullish coalescing operator?? How do you group and nest console output? What is the difference between dense and sparse arrays? What are the different ways to create sparse arrays? Coding Exercise 1. What is the output of below code Answer: 4 2. What is the output of below code Answer: 3 3. What is the output of below code Answer: 4 4. What is the output of below equality check Answer: 1 5.
What is the output of below code Answer: 4 6. What is the output of below code Answer: 3 7. What is the output of below code Answer: 3 8. What is the output of below code in latest Chrome Answer: 2 9. What is the output of below code Answer: 1 What is the output of below code Answer: 2 What is the output of below code in non-strict mode Answer: 2 What is the output of below code Answer: 3 What is the output of below code Answer: 4 What is the output of below code?
Answer: 1 What is the output of below code in non strict mode? Answer: 4 What are the possible ways to create objects in JavaScript There are many ways to create objects in javascript as below Object constructor: The simplest way to create an empty object is using the Object constructor. Hence, can only be accessed using the square bracket notation.
No Web Storage support.. No Web Worker support.. Let's have some code here! What are the possible ways to create objects in JavaScript. What is the difference between Call, Apply and Bind. What is the purpose of the array slice method. What is the purpose of the array splice method. What is the difference between slice and splice. What is the difference between let and var. What is the reason to choose the name let as a keyword. How do you redeclare variables in switch block without an error.
How do you manipulate DOM using a service worker. How do you reuse information across service worker restarts. What are the differences between cookie, local storage and session storage.
What is the main difference between localStorage and sessionStorage. What are the methods available on session storage. What is a storage event and its event handler. How do you check web storage browser support. How do you check web workers browser support. What are the restrictions of web workers on DOM. How do you receive server-sent event notifications. JavaScript, also abbreviated as JS, is a high-level server-side programming language.
JavaScript is widely used worldwide to build various web applications, which means there are huge opportunities for JavaScript programming. To build a JavaScript programming career, candidates need to crack the interview. They are asked for various JavaScript interview questions and answers. Following is a list of JavaScript interview questions and answers, which are likely to be asked during the interview. Candidates are likely to be asked basic JavaScript interview questions to advance JS interview questions depending on their experience and various other factors.
The below list covers all the JavaScript questions for freshers and JavaScript interview questions for professional-level candidates. This JS interview questions guide will help you crack the interview and help you get your dream job for JavaScript Programming. JavaScript is a client-side and server-side scripting language inserted into HTML pages and is understood by web browsers.
JavaScript is also an Object-based Programming language 2. Enumerate the differences between Java and JavaScript? Java is a complete programming language.
These two languages are not at all inter-dependent and are designed for different intent. JavaScript is faster. JavaScript is a client-side language,, and thus it does not need the assistance of the webserver to execute.
Javascript now is also a server-side language nodejs. Negative Infinity is a number in JavaScript which can be derived by dividing negative number by zero. And if you change to a new line when not within a string statement, then javaScript ignores the break in the line. The above code is perfectly fine, though not advisable as it hampers debugging.
Which company developed JavaScript? 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. Global variables are available throughout the length of the code so that it has 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. The problems 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. A prompt box is a box that allows the user to enter input by providing a text box.
A label and box will be provided to enter the text or number. Timers are used to execute a piece of code at a set time or repeat the code in a given interval. This is done by using the functions setTimeout, setInterval, and clearInterval.
The setTimeout function, delay function is used to start a timer that calls a particular function after the mentioned delay. The setInterval function, delay function repeatedly executes the given function in the mentioned delay and only halts when canceled. The clearInterval id function instructs the timer to stop. Timers are operated within a single thread, and thus events might queue up, waiting to be executed.
What is the difference between ViewState and SessionState? Yes, JavaScript does support automatic type conversion. It is the common way of type conversion used by JavaScript developers. Variable typing is used to assign a number to a variable. The same variable can be assigned to a string. The parseInt function is used to convert numbers between different bases. The second parameter is the base of the given string.
Since 3 and 2 are integers, they will be added numerically. And since 7 is a string, its concatenation will be done. So the result would be In order to detect the operating system on the client machine, the navigator. Platform string property should be used. The NULL value is used to represent no value or no object. It implies no object or null string, no valid boolean value, no number, and no array object. But a Confirmation box displays two buttons, namely OK and cancel.
What are escape characters? Escape characters Backslash is used when working with special characters like single quotes, double quotes, apostrophes, and ampersands. Place backslash before the characters to make it display. Cookies are the small test files stored in a computer, and they get created when the user visits the websites to store information that they need.
Examples could be User Name details and shopping cart information from previous visits. The pop method takes the last element off of the given array and returns it. The array on which it is called is then altered. JavaScript does not have concept-level scope. The variable declared inside the function has scope inside the function.
Primitive types are number and Boolean data types. Reference types are more complex types like strings and dates. Variable typing assigns a number to a variable and then assigns a string to the same variable. An example is as follows:. The push method is used to add or append one or more elements to an Array end.
Using this method, we can append multiple elements by passing multiple arguments. Unshift method is like the push method, which works at the beginning of the array.
This method is used to prepend one or more elements to the beginning of the array. Strict Mode adds certain compulsions to JavaScript. Under the strict Mode, JavaScript shows errors for a piece of code, which did not show an error before, but might be problematic and potentially unsafe. Strict Mode also solves some mistakes that hamper the JavaScript engines from working efficiently.
This can be illustrated by the given example:. The navigator. The onload function is not run until all the information on the page is loaded. This leads to a substantial delay before any code is executed. This allows early manipulation of the code. The closure is a locally declared variable related to a function that stays in memory when it has returned.
In each repetition, one property from the object is associated with the variable name. The loop is continued till all the properties of the object are depleted. A function that is declared without any named identifier is known as an anonymous function. In general, an anonymous function is inaccessible after its declaration. The function. On the other hand,. The basic difference between. Their usage can be illustrated by the given example. JavaScript allows DOM elements to be nested inside each other.
In such a case, if the handler of the child is clicked, the handler of the parent will also work as if it were clicked too. Yes, JavaScript is case-sensitive. For example, a function parseInt is not the same as the function Parseint. The break statement is used to come out of the current loop. In contrast, the continue statement continues the current loop with a new recurrence.
Both web-garden and web-farm are web hosting systems. The only difference is that web-garden is a setup that includes many processors in a single server. At the same time,web-farm is a larger setup that uses more than one server. Assigning properties to objects is done in the same way as a value is assigned to a variable. This can be done by Using JavaScript extensions runs from JavaScript Editor , for example, for the opening of a file —.
DOM stands for Document Object Model and is responsible for how various objects in a document interact with each other. DOM is required for developing web pages, which includes objects like paragraphs, links, etc. These objects can be operated to include actions like add or delete.
DOM is also required to add extra capabilities to a web page. On top of that, the use of API gives an advantage over other existing models. Events are the actions that result from activities, such as clicking a link or filling a form by the user.
An event handler is required to manage the proper execution of all these events. Event handlers are an extra attribute of the object. If the server is slow or the script is particularly heavy, then the web page is delayed. While using Deferred, scripts delays execution of the script till the time the HTML parser is running. This reduces the loading time of web pages, and they get displayed faster. The properties of screen objects are —.
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 —. The escape function is responsible for coding a string to transfer the information from one computer to the other across a network.
0コメント