JS interview Questions

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

What is the value of "1"+2+4

"124". For this one "1" + 2 will produce "12" and "12"+4 will generates "124".

What is the value of typeof null

"object"

If you have var y = 1, x = y = typeof x; What is the value of x?

"undefined"

What is the value of typeof bar

"undefined"

What is the value of parseFloat('12.3.4')

12.3

What is the difference between Cookies, Local Storage and Session Storage?

Browser storage: data is never transferred to the server & can only be read on client-side; storage limit is about 5MB Session vs local storage: session is only temporary — data is stored until tab/browser is closed; local doesn't have an expiration date Cons for storage: not secure, limited to strings, danger for XSS Cookie: stores data with expiration date, storage limit about 4KB, is sent to the server for each request, read/write on both client & server side (if HttpOnly then it is inaccessible to client-side scripts)

What is functional programming?

Functional programming produces programs by composing mathematical functions and avoids shared state & mutable data. Lisp (specified in 1958) was among the first languages to support functional programming, and was heavily inspired by lambda calculus. Lisp and many Lisp family languages are still in common use today. Functional programming is an essential concept in JavaScript (one of the two pillars of JavaScript). Several common functional utilities were added to JavaScript in ES5.

What is a Blob?

In JavaScript, Blobs are used to represent files as a immutable raw data. In the console, the Blob we created in the previous example looks like this: As you can see, a Blob has two properties: size and type. The size is the size of the data in Bytes. The type is a string supposed to contain the MIME type. I didn't give any type when creating my Blob, but I should have done something like this:

What is the value of Math.max([2,3,4,5]);

NaN

What is typeof []

Object. Actually Array is derived from Object. If you want to check array use Array.isArray(arr)

What is a Callback?

Simply put: A callback is a function that is to be executed after another function has finished executing — hence the name 'call back'. More complexly put: In JavaScript, functions are objects. Because of this, functions can take functions as arguments, and can be returned by other functions. Functions that do this are called higher-order functions. Any function that is passed as an argument is called a callback function.

What is 2+true

The plus operator between a number and a boolean or two boolean will convert boolean to number. Hence, true converts to 1 and you get result of 2+1

How does event delegation improve code on sites with lots of interactive elements?

Websites often have lots of dynamic content regularly changing on the page. If these elements need to be interactive, these would need some kind of event listener picking up those interactions. If each element required its own listener, this would clutter up code and increase what the browser needs to keep track of. Event delegation is a technique that uses event bubbling to its advantage. By adding a listener to a parent element, developers are alerted to events for any of its children.

3 instanceof Number

false

What is the value of !'bang'

false. ! is NOT. If you put ! in front of truthy values, it will return false. Using !! (double bang) is a tricky way to check anything truthy or falsy by avoiding implicit type conversion of == comparison.

What is the value of !!function(){};

true

null == undefined

true

Promises vs Async/Await?

in a promise, only the promise chain is asynchronous — doesn't block the execution; with async/await the entire wrapper function is asynchronous

What is the value of -'34'+10

-24. minus(-) in front of a string is an unary operator that will convert the string to a number and will make it negative. Hence, -'34' becomes, -34 and then plus (+) will perform simple addition as both the operands are number.

for var a = (2, 3, 5); what is the value of a?

5. The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand. ref: MDN

What is '6'+9

69. If one of the operands of the plus (+) operator is string it will convert other number or boolean to string and perform a concatenation. For the same reason, "2"+true will return "2true"

for var a = (1, 5 - 1) * 2 what is the value of a?

8

What is the value of 4+3+2+"1"

91 . The addition starts from the left, 4+3 results 7 and 7+2 is 9. So far, the plus operator is performing addition as both the operands are number. After that 9 + "1" where one of the operands is string and plus operator will perform concatenation.

What is a closure?

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

What is a Closure?

A closure is where a function is defined inside another function, and the inner function can access local variables (and parameters) defined in the local scope of the outer function. Closures are significant because the inner function will have access to the outer function's variables as long as it needs them, even if the outer function has finished executing

How can JavaScript be used to improve accessibility on the web?

A common way to assist users is to provide useful focus management. A calendar, for example, should be able to cycle through days using the arrow keys, with up and down keys skipping a week at a time. It is just a case of listening for keyboard events while focus is within that component. Important data changing as a result of JavaScript, for example form feedback, should also be announced for screen readers. Often this is achieved by marking up a container as a live region.

What is an Anonymous Function?

A function that was declared without any function named identifier to refer to it — it is usually not accessible after its initial creation. These functions are created at run time

What is a Higher Order function?

A higher order function is a function that takes a function as an argument, or returns a function. Higher order function is in contrast to first order functions, which don't take a function as an argument or return a function as output.

What are the pros and cons of monolithic vs microservice architectures?

A monolithic architecture means that your app is written as one cohesive unit of code whose components are designed to work together, sharing the same memory space and resources. A microservice architecture means that your app is made up of lots of smaller, independent applications capable of running in their own memory space and scaling independently from each other across potentially many separate machines. Monolithic Pros: The major advantage of the monolithic architecture is that most apps typically have a large number of cross-cutting concerns, such as logging, rate limiting, and security features such audit trails and DOS protection. When everything is running through the same app, it's easy to hook up components to those cross-cutting concerns. Monolithic cons: Monolithic app services tend to get tightly coupled and entangled as the application evolves, making it difficult to isolate services for purposes such as independent scaling or code maintainability. Microservice pros: Microservice architectures are typically better organized, since each microservice has a very specific job, and is not concerned with the jobs of other components. Decoupled services are also easier to recompose and reconfigure to serve the purposes of different apps (for example, serving both the web clients and public API). Microservice cons: As you're building a new microservice architecture, you're likely to discover lots of cross-cutting concerns that you did not anticipate at design time. A monolithic app could establish shared magic helpers or middleware to handle such cross-cutting concerns without much effort.

What is a promise?

A promise is an object that may produce a single value some time in the future: either a resolved value, or a reason that it's not resolved (e.g., a network error occurred). A promise may be in one of 3 possible states: fulfilled, rejected, or pending. Promise users can attach callbacks to handle the fulfilled value or the reason for rejection.

What is Event Delegation

A simple technique by which you add a single event handler to a parent element in order to avoid having to add event handlers to multiple child elements

Where should I use the 'let' and 'const' keywords instead of 'var'?

Another fundamental change with ES2015 was the introduction of 'let' and 'const' as alternative ways to define variables. Variables declared in this way are limited to the block they were defined in. This provides more certainty that values created inside different blocks won't interfere with code outside. Both 'let' and 'const' do not get hoisted like 'var', so cannot be referenced before they are initialised. Between the start of the block and the initialisation is known as the 'temporal dead zone' and can often be a source of confusion.

As [] is true, []==true should also be true. right?

Answer: You are right about first part, [], empty array is an object and object is always truthy. Hence, if you use if([]){console.log('its true')} you will see the log. However, special case about == (double equal) is that it will do some implicit coercion. Since left and right side of the equality are two different types, JavaScript can't compare them directly . Hence, under the hood, JavaScript will convert them to compare. first right side of the equality will be cooereced to a number and number of true would be 1. After that, JavaScript implementation will try to convert [] by usingtoPrimitive (of JavaScript implementation). since [].valueOf is not primitive will use toString and will get "" Now you are comparing "" == 1 and still left and right is not same type. Hence left side will be converted again to a number and empty string will be 0. Finally, they are of same type, you are comparing 0 === 1 which will be false.

What the heck is this in JavaScript?

At the time of execution of every function, JavaScript engine sets a property to the function called this which refer to the current execution context. this is always refer to an object and depends on how function is called. There are 7 different cases where the value of this varies:: - In the global context or inside a function this refers to the window object. - Inside IIFE (immediate invoking function) if you use "use strict", value of this is undefined. To pass access window inside IIFE with "use strict", you have to pass this. - While executing a function in the context of an object, the object becomes the value of this Inside a setTimeout function, the value of this is the window object. - If you use a constructor (by using new keyword) to create an object, the value of this will refer to the newly created object. - You can set the value of this to any arbitrary object by passing the object as the first parameter of bind, call or apply - For dom event handler, value of this would be the element that fired the event

How can I future-proof my JavaScript code?

Avoid spaghetti code When first creating a project, it can be tempting to write everything together. While that makes it explicit what each block of code is doing, it also means all behaviour is coupled together as well. If another area of the project needs that functionality, it will either be copied or rewritten. If bugs are found or a new feature is added, each version will need updating individually, which can be a time-consuming process. Be framework agnostic Many modern frameworks, like React or Polymer, encourage developers to keep things modular through the creation of components. Each has its own way of communicating between other parts of the project. What happens when the next best framework arrives? Switching - or even just updating - frameworks can be a laborious task. Finding new ways for these old components to work together can eat up precious time. Clean up Once modules are written, keep them clean. Anybody reading through them should understand its functionality to speed up debugging. Work at scale Being readable also extends to project structure. Without one, things can get overwhelming very quickly.

What is event bubbling and how is it different to event capturing?

Both event capturing and bubbling are both part of a process called 'event propagation', where browsers respond to events happening on the page. Older browsers used to do one or the other, but nowadays they all do both. The first phase - the capturing phase - occurs as soon as an event happens. It starts at the topmost level, which is either 'document' or 'window' depending on the event. From there it goes through <html> and whatever lives inside it until it reaches the element the event occurred within. The second phase - the bubbling phase - then happens. It repeats the process but in reverse, beginning with the element the event was triggered by and 'bubbling' to the topmost <html> element. When adding event listeners, this is the default.

What is the difference between classical inheritance and prototypal inheritance?

Class Inheritance: instances inherit from classes (like a blueprint — a description of the class), and create sub-class relationships: hierarchical class taxonomies. Instances are typically instantiated via constructor functions with the `new` keyword. Class inheritance may or may not use the `class` keyword from ES6. Prototypal Inheritance: instances inherit directly from other objects. Instances are typically instantiated via factory functions or `Object.create()`. Instances may be composed from many different objects, allowing for easy selective inheritance.

What is Content Security Policy (CSP)?

Content Security Policy (CSP) is an HTTP header that allows site operators fine-grained control over where resources on their site can be loaded from. The use of this header is the best method to prevent cross-site scripting (XSS) vulnerabilities. Due to the difficulty in retrofitting CSP into existing websites, CSP is mandatory for all new websites and is strongly recommended for all existing high-risk sites.

What is CORS (Cross-Origin Resource Sharing)?

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own

What is Cross-Site Scripting (XSS)?

Cross-Site Scripting (XSS) is an attack that occurs when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user The page provided by the server when someone requests it is unaltered; instead, an XSS attack exploits a weakness in a page that include a variable submitted in a request to show up in raw form in the response

What is a curry function?

Currying is a process in functional programming in which we can transform a function with multiple arguments into a sequence of nesting functions — it returns a new function that expects the next argument inline

What does 'use strict' mean at the top of a block of code?

ES5 introduced an optional variant of JavaScript called 'strict mode'. In strict mode, quirks of earlier versions would throw errors rather than result in unintended behaviour.

What are closures and how can they be useful in organising code?

Functions in JavaScript use what is called the 'lexical environment', meaning it has access to variables defined outside, but those defined inside can only be accessed within. These are useful when creating multiple components, as anything declared inside will not affect others. They can be used to create private functions and variables in a similar way to other object-oriented languages like Python. The module pattern uses closures extensively to provide structured ways for modules to interact.

What are Higher-Order Functions?

Functions that receive a function as an argument or return a function as output

Can you name two programming paradigms important for JavaScript app developers?

JavaScript is a multi-paradigm language, supporting imperative/procedural programming along with OOP (Object-Oriented Programming) and functional programming. JavaScript supports OOP with prototypal inheritance.

What is prototypical inheritance and how useful is it?

In JavaScript, almost everything is an object. Every object has a prototype, from which it inherits values and behaviours. If an object doesn't include a property that's being requested, JS will look for it inside its prototype instead. It carries on up the chain of prototypes until it finds a match, or returns an error. This is useful when making objects that share the same values and operations. By having these live on a prototype, only one copy of them needs to exist, making projects memory efficient.

What is the Event loop?

In most browsers there is an event loop for every browser tab, to make every process isolated and avoid a web page with infinite loops or heavy processing to block your entire browser

What is functional programming and how is it different?

It is an alternative way of creating programs by passing application state exclusively through functions. By avoiding side effects, it's possible to develop code that's easy to understand. Traditionally, JavaScript projects are built with an object-oriented structure. Information about the current state of the program is held within objects, which get updated as the page changes. All work must be done inside 'pure' functions. These are functions that are not affected by any data outside the scope of that function. In other words, if the same values are supplied to the function, the same result will always be returned.

What does the term 'hoisting' mean in reference to JavaScript?

JavaScript is unique in that it does not need compiling before being distributed. A browser will compile scripts as it finds them and make notes of any functions and variables that are declared within. The browser then makes a second pass to execute the code, knowing where these functions and variables apply. As a block is executed, its function and variable declarations are 'hoisted' to the top of the block.

What is the value of +'dude'

NaN. The plus (+) operator in front of a string is an unary operator that will try to convert the string to number. Here, JavaScript will fail to convert the "dude" to a number and will produce NaN.

What are the pros and cons of functional programming vs object-oriented programming?

OOP Pros: It's easy to understand the basic concept of objects and easy to interpret the meaning of method calls. OOP tends to use an imperative style rather than a declarative style, which reads like a straight-forward set of instructions for the computer to follow. OOP Cons: OOP Typically depends on shared state. Objects and behaviors are typically tacked together on the same entity, which may be accessed at random by any number of functions with non-deterministic order, which may lead to undesirable behavior such as race conditions. FP Pros: Using the functional paradigm, programmers avoid any shared state or side-effects, which eliminates bugs caused by multiple functions competing for the same resources. With features such as the availability of point-free style (aka tacit programming), functions tend to be radically simplified and easily recomposed for more generally reusable code compared to OOP. FP Cons: Over exploitation of FP features such as point-free style and large compositions can potentially reduce readability because the resulting code is often more abstractly specified, more terse, and less concrete.

What is typeof arguments

Object. arguments are array like but not array. it has length, can access by index but can't push pop, etc.

What is asynchronous programming, and why is it important in JavaScript?

Synchronous programming means that, barring conditionals and function calls, code is executed sequentially from top-to-bottom, blocking on long-running tasks such as network requests and disk I/O. Asynchronous programming means that the engine runs in an event loop. When a blocking operation is needed, the request is started, and the code keeps running without blocking for the result. When the response is ready, an interrupt is fired, which causes an event handler to be run, where the control flow continues. In this way, a single program thread can handle many concurrent operations. User interfaces are asynchronous by nature, and spend most of their time waiting for user input to interrupt the event loop and trigger event handlers. Node is asynchronous by default, meaning that the server works in much the same way, waiting in a loop for a network request, and accepting more incoming requests while the first one is being handled.

When is classical inheritance an appropriate choice?

The answer is never, or almost never. Certainly never more than one level. Multi-level class hierarchies are an anti-pattern. I've been issuing this challenge for years, and the only answers I've ever heard fall into one of several common misconceptions. More frequently, the challenge is met with silence.

What is the difference between an arrow function and a regular function?

The key difference, despite being shorter to write, is that arrow functions do not create their own value for 'this'. They will instead use the value of the enclosing block. In the above example, this would log out 1, 2, 3, etc once every second. With a regular function, this.x would be undefined, so it would log NaN

What are the differences between == and ===?

The simplest way of saying that, == will not check types and === will check whether both sides are of same type. So, == is tolerant. But under the hood it converts to its convenient type to have both in same type and then do the comparison. === compares the types and values. Hence, if both sides are not same type, answer is always false. For example, if you are comparing two strings, they must have identical character sets. For other primitives (number, boolean) must share the same value

When is prototypal inheritance an appropriate choice?

There is more than one type of prototypal inheritance: -Delegation (i.e., the prototype chain). -Concatenative (i.e. mixins, `Object.assign()`). -Functional (Not to be confused with functional programming. A function used to create a closure for private state/encapsulation). Each type of prototypal inheritance has its own set of use-cases, but all of them are equally useful in their ability to enable composition, which creates has-a or uses-a or can-do relationships as opposed to the is-a relationship created with class inheritance.

How can I use JS to improve the performance of my site?

Throttling events Events like scrolling and resizing fire as quickly as they can to make sure whatever is listening can stay up to date. If something resource intensive is happening on each event, this can quickly grind a page to a halt. Focus on the viewport A common use of the scroll event is to detect when an element comes into view on the page. Even with debouncing, calling getBoundingClientRect() requires the browser to reanalyse the layout of the entire page. There is a new browser API called IntersectionObserver, which reports on the visibility of observed elements by calling a function whenever they enter or exit the viewport. For infinite scrolling sites, this can be used as a flag to remove or recycle older views. Separate expensive work When working with large datasets or processing big files such as images, JavaScript can quickly lock up the browser window. All the work is getting performed on a single thread, so if that thread is busy the interface cannot update. If you know a process is going to take a long time to run, it is a good idea to put it inside a web worker. These are scripts that run on a separate thread, which leaves the user interface running smoothly. Scripts can talk to each other through a special message method. Web workers don't have access to the DOM and some properties on the window object, so these messages can be used to pass the necessary information.

What are two-way data binding and one-way data flow, and how are they different?

Two way data binding means that UI fields are bound to model data dynamically such that when a UI field changes, the model data changes with it and vice-versa. One way data flow means that the model is the single source of truth. Changes in the UI trigger messages that signal user intent to the model (or "store" in React). Only the model has the access to change the app's state. The effect is that data always flows in a single direction, which makes it easier to understand. One way data flows are deterministic, whereas two-way binding can cause side-effects which are harder to follow and understand.

What are the differences between null and undefined?

undefined undefined means, value of the variable is not defined. JavaScript has a global variable undefined whose value is "undefined" and typeof undefined is also "undefined". Remember, undefined is not a constant or a keyword. undefined is a type with exactly one value: undefined. Assigning a new value to it does not change the value of the type undefined. 8 Ways to get Undefined:A declared variable without assigning any value to it.Implicit returns of functions due to missing return statements.return statements that do not explicitly return anything.Lookups of non-existent properties in an object.Function parameters that have not passed.Anything that has been set to the value of undefined.Any expression in the form of void(expression)The value of the global variable undefined null null means empty or non-existent value which is used by programmers to indicate "no value". null is a primitive value and you can assign null to any variable. null is not an object, it is a primitive value. For example, you cannot add properties to it. Sometimes people wrongly assume that it is an object, because typeof null returns "object". Btw, null == undefined ref: history of typeof null


संबंधित स्टडी सेट्स

Current Issues 4: What is RAID 0, 1, 5, and 10

View Set

Lab 13: Glaciers and Periglacial Landscapes

View Set

AP Euro Chapter 16 - Toward a New World View, Scientific Revolution and Enlightenment

View Set

Accounting Chapter 15 TRUE/FALSE

View Set