Javascript Interview Questions

Ace your homework & exams now with Quizwiz!

Why is it, in general, a good idea to leave the global scope of a website as-is and never touch it?

Every script has access to the global scope, and if everyone uses the global namespace to define their variables, collisions will likely occur. Use the module pattern (IIFEs) to encapsulate your variables within a local namespace.

What is functional programming?

Functional programming produces programs by composing mathematical functions and avoids shared state & mutable data. It consists of pure functions, avoids side effects, and supports features like first class functions, higher order functions, and functions as arguments/values.

How would you iterate over object properties and array items?

Iterating over objects - for-in loops: for(var property in obj) - Object.keys(): Object.keys(obj).forEach(function(property) { } ) Iterating over arrays - for loops - forEach: arr.forEach(function(el, index) { } ) - for-of: for(let elem of arr) { }

What is the difference between Java and Javascript?

Java: - OOP Programming Language - Creates applications that run on a virtual machine or browser - Needs to be compiled Javascript - OOP Scripting Language - Runs on browser only

Explain value and types in Javascript

JavaScript has typed values, not typed variables. The following built-in types are available: string number boolean null and undefined object symbol (new to ES6)

Explain equality in Javascript

Javascript has both strict and type-converting comparisons. Strict comparison (===) checks for value equality without allowing coercion, meaning it is type strict. Abstract comparison (==) checks for value equality with coercion allowed, meaning it is not type strict

Explain the difference between the document load event and DOMContentLoaded event?

- DOMContentLoaded - fired when the initial HTML document has been completely loaded and parsed without waiting for styles and resources to finish loading - load - only fired after the DOM and all of its dependent resources have loaded

What is the difference between feature detection, feature inference, and using the UA string?

- Feature detection involves figuring out whether a browser supports a certain block of code and running different code depending on if it does or doesn't so that the browser can always provide a working experience. - Feature inference checks for a feature similar to feature detection, but uses another function because it assumes it will also exist, - UA String - a browser reported string that allows the network protocol peers to identify the application type, operating system, software vendor, or software version. Accessed through "navigator.userAgent".

What are the features of Javascript?

- It is lightweight and interpreted - Designed for creating network-centric applications - Complementary to and integrated with Java - Open and cross platform scripting language

Monolithic vs Microservice

- Monolithic - App is written as one cohesive unit of code whose components are designed to work together, sharing same memory space and resources - Microservice - App is made up of lots of smaller, independent applications capable of running in their own memory space and scaling independently from each other

What are some differences between ES5 and ES6?

- New symbol data type - let and const to define variables - Arrow functions - Destructuring and spread operators - Template literals

What is the difference between function Person(){}, var person = Person(), and var person = new Person()?

- The first one is just a normal function declaration that might serve as a constructor - The second one invokes the Person() function as just a normal function, and not a constructor, as there was no "new" keyword used - The last one creates an instance of the Person object using the "new" operator, which inherits from Person.prototype

Two-way data binding vs one-way data flow

- Two-way data binding - UI fields are bound to model data dynamically such that when a UI field changes, the model data changes with it and vice versa. In Angular two way data binding is used, as data can flow from parent to child components, and from child to parent parents. - One-way data flow - The model is the single source of truth. Only the model has access to change the app's state. In React, one way data flow is used, where data is passed from the parent component to child component through props.

What are some HTML element accessors?

- getElementById() - getElementsByClass() - getElementsByTagName() - querySelector()

How does this work?

1. If the new keyword is used when calling the function, this inside the function is a brand new object. 2. If apply, call, or bind are used to call/create a function, this inside the function is the object that is passed in as the argument. 3. If a function is called as a method, such as obj.method() — this is the object that the function is a property of. 4. If a function is invoked as a free function invocation, meaning it was invoked without any of the conditions present above, this is the global object. In a browser, it is the window object. If in strict mode ('use strict'), this will be undefined instead of the global object. 5. If multiple of the above rules apply, the rule that is higher wins and will set the this value. 6. If the function is an ES2015 arrow function, it ignores all the rules above and receives the this value of its surrounding scope at the time it is created.

What is the difference between == and ===?

== tests for loose equality with coercion allowed, so both values are compared only after attempting to convert them into a common type === is testing for strict equality without coercion, meaning that both the type and the value that is being compared have to be the same value and type.

What is a closure?

A closure is the combination of a function and the lexical environment with which that function was declared. The word "lexical" refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Closures are functions that have access to the outer (enclosing) function's variables—scope chain even after the outer function has returned.

What is a Polyfill?

A polyfill is essentially the specific code (or plugin) that would allow you to have some specific functionality that you expect in current or "modern" browsers to also work in other browsers that do not have the support for that functionality built in. - Polyfills are not part of the HTML5 standard - Polyfilling is not limited to Javascript

What are the advantages and disadvantages of using Ajax?

Advantages - Better interactivity, updates without need to reload - Reduce connections to server - State can be maintained on a page, as variables will persist because main container pages won't need to reload Disadvantages - Does not work if JS has been disabled in browser - Some webcrawlers do not execute JS and would not see content that has been loaded by JS

Explain Ajax in detail

Ajax (asynchronous JavaScript and XML) is a set of web development techniques using many web technologies on the client side to create asynchronous web applications. With Ajax, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. By decoupling the data interchange layer from the presentation layer, Ajax allows for web pages, and by extension web applications, to change content dynamically without the need to reload the entire page. In practice, modern implementations commonly use JSON instead of XML, due to the advantages of JSON being native to JavaScript. The XMLHttpRequest and the fetch API are frequently used for asynchronous communication

Explain prototypal inheritance

All JavaScript objects have a prototype property, that is a reference to another object. When a property is accessed on an object and if the property is not found on that object, the JavaScript engine looks at the object's prototype, and the prototype's prototype and so on, until it finds the property defined on one of the prototypes or until it reaches the end of the prototype chain. This behavior simulates classical inheritance

What is the "typeof" operator?

An operator used to examine a value and return a string representation of what type it is.

Apply vs Bind vs Call

Apply - Method sets the "this" keyword inside the function and automatically executes the function and accepts a "single array of arguments" (Ex. greeting.call(jane) - binds "jane" object to greeting function) Call - Same as apply in that "this" keyword is set inside function and function is automatically executed, but arguments are passed as comma separated values in the form of an argument list. Bind - Creates a new copy of the function and sets the "this" keyword to the specific object. Format: "function.bind(thisArgument, optionalArguments) (Ex. greeting.bind(john) - creates a new copy of function and sets "this" keyword to "john" object)

Explain arrays in JavaScript

Arrays are objects that hold values of any type in numerically indexed positions.

Explain the difference between attributes and properties

Attributes - Defined on HTML elements - Set to initial values passed to them at time of element creation Properties - Contained on DOM node objects, which are created the the HTML elements after the browser creates the DOM tldr - things like "type", "id", "class", etc are considered attributes up until the browser creates the DOM, which is when they go from being attributes to properties

Attributes vs Properties

Attributes - Provides details on an element (id, type, value) Properties - The values assigned to the attribute (type="text", value="Username")

What's the difference between throw Error('msg') vs throw new Error('msg')?

Both versions work, as the function call "Error('msg') is equivalent to the object creation expression "new Error(...)"

What are callbacks?

Callbacks are plain JavaScript functions passed to some method as an argument to be executed later.

Classical Inheritance vs Prototypal Inheritance

Classical Inheritance - Inherits from classes and creates sub-class relationships (hierarchical class taxonomies). Instances are created through constructors with new keyword. (TIGHT COUPLING) Prototypal Inheritance - Inherits directly from other objects. Instances are created through factory functions or "object.create()". It has features like concatenative inheritance (copying properties from one object to another), prototype delegation

What is currying?

Currying is a transformation of functions that translates a function from callable as f(a, b, c) into callable as f(a)(b)(c)

What is asynchronous programming?

Engine runs in event loop. When blocking operation is needed, request is started and code runs without block for result. When response is ready, an interrupt is fired, which causes an event handler to be run where the control flow continues.

How does event delegation work?

Event delegation is a technique involving adding event listeners to a parent element instead of adding them to the descendant elements. The listener will fire whenever the event is triggered on the descendant elements due to event bubbling up the DOM. Example - In a table with many rows, instead of adding an event listener for each row, we can just add an event listener for any click within the table, and check if the click was on a row.

What is hoisting?

Hoisting is a term used to explain the behavior of variable declarations in your code. Variables declared or initialized with the var keyword will have their declaration "moved" up to the top of the current scope, which we refer to as hoisting. However, only the declaration is hoisted, the assignment (if there is one), will stay where it is. Note that the declaration is not actually moved - the JavaScript engine parses the declarations during compilation and becomes aware of declarations and their scopes. It is just easier to understand this behavior by visualizing the declarations as being hoisted to the top of their scope. Let's explain with a few examples.

What is an IIFE?

IIFE (Immediately Invoked Function Expression) is a JS function that runs as soon as it is defined. It contains 2 major parts: 1. An anonymous function with lexical scope enclosed within the Grouping Operator (), preventing access to variables within the IIFE idiom. 2. An immediately invoked function expression. Use Cases 1. Avoid polluting the global namespace Example (function () { var userName = "Steve"; function display(name) { alert("MyScript2.js: " + name); } display(userName); })();

Explain the different between mutable and immutable objects

Immutable objects - Some built in types (numbers, strings) are immutable, but custom objects are generally mutable - Some built in immutable objects are Math and Data - Combining the "writable: false" and "configurable: false" properties can create a constant, immutable object - If you want to prevent an object from having new properties added to it, but leave the rest of the object properties alone, use Object.preventExtensions(obj) - If you want to prevent the addition and deletion of properties, use Object.seal(obj) - If you want to prevent the addition, deletion, and modification of properties on an object, use Object.freeze(obj)

What is scope in Javascript?

In Javascript, each function gets its own scope. Scope is basically a collection of variables and rules for how these variables are accessed by name. Only the code inside the function can access that function's scoped variables. A variable name has to be unique within the same scope. A scope can be nested inside another scope. If one scope is nested inside another, code inside the innermost scope can access variables from either scope.

What is a SPA and how can you make it SEO friendly?

In SPAs, client side rendering is used. When a user navigates to other pages, a page refresh is not triggered. Rather, the URL of the page is updated via the HTML5 History API. New data may be required for the new page (usually in JSON format), which is retrieved by the browser through HTTP requests to the server. The SPA is then dynamically updated using the data via JavaScript. Benefits - App feels more responsive - Fewer HTTP requests are made - Able to modify client and server separately Downsides - Initial page load is heavier - Need to route all requests from server to a single entry point and allow client side routing to take over - SPAs are reliant on JS to render content, but not all search engines use JS during crawling, so they might not see any content on your page, which is not good for SEO. To fix this, you can either use server side rendering or use services like "Prerender" to render JS in a browser, save the static HTML, and return that to the crawlers

What does "favor object composition over class inheritance" mean?

It means that code reuse should be achieved by assembling smaller units of functionality into new objects instead of inheriting from classes. (Avoids class hierarchies and tight coupling)

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

Javascript is a multi-paradigm language, supporting imperative and declarative programming. Non Abstract - Imperative/Procedural Abstract - Declarative/Functional Imperative Programming - Focuses on the HOW. Step by step tasks to achieve a certain goal or get to a final product, and writing a list of instructions to tell the computer what to do, and relies on procedures and routines. (Procedural Programming, OOP) OOP - encapsulating data and behavior into objects Declarative Programming - Focuses on the WHAT, and what needs to get done. (Logical Programming, Functional Programming) Functional Programming (opposite of OOP) - passing data from function to function to function to get a result. In FP, functions are treated as data, meaning you can use them as parameters, return them, build functions from other functions, and build custom functions. Functions in FP have to be pure functions, they should avoid shared state, and side effects and data should be immutable.

Local Storage vs Session Storage

Local Storage - Data is not sent back to the server for every HTTP request, reducing the amount of traffic between the client and server and stays until manually cleared through settings or programs Session Storage - Similar to local storage but data will have an expiration time which is when the page session ends

What's the difference between Host objects and Native objects?

Native objects are objects that are part of the JavaScript language defined by the ECMAScript specification, such as String, Math, RegExp, Object, Function, etc. Host objects are provided by the runtime environment (browser or Node), such as window, XMLHTTPRequest, etc.

When is classical inheritance an appropriate choice?

Never, or almost never. Multi-level class heirarchies are an anti-pattern.

Functional Programming vs Object Oriented Programming

OOP - Uses imperative style, reads like a straight forward set of instructions for the computer to follow FP - Avoids shared state or side effects, simplified functions that are more reusable compared to OOP, uses declarative style which do not spell step-by-step instructions but concentrate on what to do, not how.

How does the new arrow => function syntax differ from other functions

One obvious benefit of arrow functions is to simplify the syntax needed to create functions, without a need for the function keyword. The this within arrow functions is also bound to the enclosing scope which is different compared to regular functions where the this is determined by the object calling it. Lexically-scoped this is useful when invoking callbacks especially in React components.

What is REST?

REpresentational State Transfer (REST) is an architectural style that handles the client-server relationship, with the purpose of aiming for speed and performance by using re-usable components. A REST API is a way of easily accessing web services without having excess processing. Whenever a RESTful API is called, the server will transfer to the client a representation of the state of the requested resource.

Why is it a good idea to leave the global scope as is and never touch it?

Since every script has access to the global scope, if everyone uses the global namespace to define their variables, collisions will likely occur. We should use the module pattern and use IIFEs to encapsulate our variables within a local namespace.

Describe the main difference between a .forEach loop and a .map() loop

forEach - iterates through the elements in an array - executes a callback for each function - does not return a value map - iterates through the elements in an array - "maps" each element to a new element by calling the function on each element, creating a new array as a result The main difference between forEach and map is that map returns a new array.

What is strict mode?

Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a "strict" operating context. This strict context prevents certain actions from being taken and throws more exceptions. Strict mode can be used by placing "use strict" in a program or function. Advantages: - Impossible to accidentally create global variables - Makes assignments that would typically fail throw an exception - Makes attempts to delete undeletable properties - Requires function parameter names to be unique - "this" undefined in global context Disadvantages: - Missing features - No more access to function.caller and function.arguments

What is the "arguments object" in Javascript?

The "arguments object" is a local variable within all non-arrow functions. You can refer to a function's arguments inside of that function by using its "arguments" object. It is basically an array-like object accessible within functions that contains the values of the arguments passed to that function.

Why would you use something like the load event?

The "load" event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and everything has finished loading.

What is the "object" type?

The "object" type refers to a compound value where you can set properties that each have their values of any type. var obj = { a: "hello world" }

Explain event bubbling and how one may prevent it

The concept in which an event triggers at the deepest possible element, and triggers on parent elements in nesting order. One way of preventing event bubbling is to use "event.stopPropagation()" Example Lets say we have a box "c" within a box "b" within a box "a". Let's say each of these boxes have event handlers attached to them, that print out the boxes' label. If we click the most inner box "c", c's event handler goes off first, then it bubbles up to b's event handler, then a's event handler

Why would you use something like the load event? Does this event have disadvantages? Do you know any alternatives, and why would you use those?

The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading. The DOM event DOMContentLoaded will fire after the DOM for the page has been constructed, but do not wait for other resources to finish loading. This is preferred in certain cases when you do not need the full page to be loaded before initializing.

Explain the same-origin policy with regards to JavaScript.

The same-origin policy prevents JavaScript from making requests across domain boundaries. An origin is defined as a combination of URI scheme, hostname, and port number. This policy prevents a malicious script on one page from obtaining access to sensitive data on another web page through that page's Document Object Model.

What does "use strict" do?

The use strict literal is entered at the top of a JavaScript program or at the top of a function and it helps you write safer JavaScript code by throwing an error if a global variable is created by mistake.

When is prototypal inheritance an appropriate choice?

There is more than one type of prototypal inheritance: - Delegation - Objects with a link to a prototype can be used for delegation. If there is no property on object, lookup is delegated to the delegate prototype, which may have a link to its own delegate prototype and moves up until it arrives at an "Object.prototype", which is the root delegate. - Concatenative - Inheriting features directly from one object to another by copying the source objects properties. "Object.assign()" - Functional - Any non constructor function that create objects are known as factory function. Functional inheritance produces objects from a factory and extends the produced object by assigning properties to it directly through concatenative inhertiance.

What is the typical use case for anonymous functions?

They can be used in IIFEs to encapsulate some code within a local scope so that variables declared in it do not leak to the global scope.

Undeclared vs Undefined vs Null

Undeclared variables are created when you assign a value to an identifier that is not previously created Undefined variables are variables that have been declared, but not assigned a value A variable that is null will have been explicitly assigned to the null value. It represents no value and is different from undefined in the sense that it has been explicitly assigned.

undeclared vs undefined

Undeclared variables represent those that do not exist in a program

null vs undefined

Undefined - a variable has been declared but has no assigned value Null - an assignment value assigned to a variable to represent no value

How does event bubbling work?

When an event triggers on a DOM element, it will attempt to handle the event if there is a listener attached, then the event is bubbled up to its parent and the same thing happens. This bubbling occurs up the element's ancestors all the way to the document. Event bubbling is the mechanism behind event delegation. One way to prevent event bubbling is using event.stopPropagation() or event.cancelBubble on IE < 9.

Window vs Document

Window - a global object which holds variables, functions, history, and location. It can be treated as the root of the DOM. Document - under the window and can be considered a property of the window. It is the main object of the visible DOM

How do you create a cookie in Javascript?

You can assign a string value to document.cookie Ex. document.cookie = "username=a"

When would you use document.write()?

document.write() writes a string of text to a document stream opened by document.open(). When document.write() is executed after the page has loaded, it will call document.open which clears the whole document (<head> and <body> removed!) and replaces the contents with the given parameter value. Hence it is usually considered dangerous and prone to misuse. There are some answers online that explain document.write() is being used in analytics code or when you want to include styles that should only work if JavaScript is enabled. It is even being used in HTML5 boilerplate to load scripts in parallel and preserve execution order!

"typeof" vs "instance of"

typeof is an operator that will return the type of a variable passed to it instanceof checks whether or not the prototype property of a constructor exists on an object's prototype chain, which would indicate that the object is an instance of that object

var vs let vs const

var - can be hoisted, can be accessed outside local scope. It is scoped to either the function it is defined in or the global scope if not define within a function. let - cannot be hoisted, block scope to immediate block const - cannot be hoisted, scope limited to block (curly braces - if else statements) https://github.com/yangshun/front-end-interview-handbook/blob/master/questions/javascript-questions.md#what-are-the-differences-between-variables-created-using-let-var-or-const


Related study sets

Electronics Fundamentals, Ch. 8 Introduction to Alternating Current and Voltage Part II AC Circuits

View Set

Types of Individual Life Insurance 1

View Set

EMT - Chapter 34: Pediatric Emergencies

View Set

New words start with the letter A + B

View Set

PSY McGraw-Hill CH.13: Social Psychology

View Set