JavaScript interview questions

Ace your homework & exams now with Quizwiz!

ways of creating an object in JS

-Using object initializers (aka literal notation) var obj = { property_1: value_1, 2: value_2, "property n": value_n }; // or a string - Using a constructor function function Car(make, model, year) { this.make = make; this.model = model; this.year = year; } var mycar = new Car("Eagle", "Talon TSi", 1993); - Using the Object.create method var Animal = { type: "Invertebrates", // Default value of properties displayType : function(){ // Method which will display type of Animal console.log(this.type); } } // Create new animal type called animal1 var animal1 = Object.create(Animal); animal1.displayType(); // Output:Invertebrates http://stackoverflow.com/questions/6843951/which-way-is-best-for-creating-an-object-in-javascript-is-var-necessary-befor

What is IIFE?

Immediately-Invoking Function Expression (function(){})(); //executes function immediately

What's the difference between a variable that is: null, undefined or undeclared? How would you go about checking for any of these states?

In JavaScript, undefined means a variable has been declared but has not yet been assigned a value. null is an assignment value. It can be assigned to a variable as a representation of no value. undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object. Undeclared variables are those that are not declared at all. The falsy values null and undefined are not equivalent to anything except themselves

What's a hash table?

It's a data structure that can map keys to values. A hash table is made up of two parts: an array (the actual table where the data to be searched is stored) and a mapping function, known as a hash function. The hash function is a mapping from the input space to the integer space that defines the indices of the array. In other words, the hash function provides a way for assigning numbers to the input data such that the data can then be stored at the array index corresponding to the assigned number.

How do you go about testing your Javascript?

Jasmine?

What is "lexical" scoping?

JavaScript has lexical scoping with function scope. In other words, even though JavaScript looks like it should have block scope because it uses curly braces { }, a new scope is created only when you create a new function. To resolve variables, JavaScript starts at the innermost scope and searches outwards until it finds the variable it is looking for. Child has access to parent's variables, but not vice versa.

Explain AJAX in as much detail as possible

Make http requests (use of the XMLHttpRequest object to communicate with server-side scripts). It can send as well as receive information in a variety of formats, including JSON, XML, HTML, and even text files. AJAX's most appealing characteristic, however, is its "asynchronous" nature, which means it can do all of this without having to refresh the page. This lets you update portions of a page based upon user events. Asynchronous JavaScript and XML

How do you organize your code?

Module pattern: meyer, config, base, layout, theme

conversion

String.parseInt() returns int String.toUpperCase() ret string String.toLowerCase() ret string String.split() returns array

Explain how "this" works

The "this" keyword acts as a reference to the context object. The value of "this" changes, depending on what context you're executing in. Cases: - so you can access its properties through dot notation. - When you use call and apply, you get to decide what 'this' is bound to - When you use the keyword 'new' to create an instance, the keyword 'this' is bound to the instance not the function.

array manipulation

http://overapi.com/javascript/ concat() indexOf() join() lastIndexOf() pop() push() reverse() shift() slice() sort() splice() toString() unshift() valueOf()

string manipulation

http://www.sitepoint.com/15-javascript-string-functions/ http://overapi.com/javascript/ charAt() charCodeAt() concat() fromCharCode() indexOf() lastIndexOf() match() replace() search() slice() split() substr() substring() toLowerCase() toUpperCase() valueOf()

Big O notation

https://rob-bell.net/2009/06/a-beginners-guide-to-big-o-notation/ http://bigocheatsheet.com/ For an algorithm to have logarithmic efficiency, written O(log n), it must, for each element acted on, eliminate some fraction of the remaining inputs.

Explain how prototypal inheritance works

objects inherit from objects search up prototype chain until it finds a match A prototype is an internal object from which other objects inherit properties. Its main purpose is to allow multiple instances of an object to share a common property. Thus, object properties which are defined using the prototype object are inherited by all instances which reference it. http://www.htmlgoodies.com/html5/tutorials/javascript-prototypical-inheritance-explained.html#fbid=RraRpHf2mNM http://stackoverflow.com/questions/2064731/good-example-of-javascripts-prototype-based-inheritance Since javascript doesn't have a concept of a class, we implement inheritance by creating an object which can act as a prototype for other objects. You can do so by adding the 'parent' or 'blueprint' object to the prototype property of your child object. Or create an 'object' function that takes in the parent (and overriding supplements) and returns the child with parent in prototype. Can be a performance boost since all child instances will point to the prototype properties and methods as references instead of making their own copies. src: http://adventuresincoding.com/2010/07/prototypal-inheritance-in-javascript-explained also good: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

What's the difference between .call and .apply?

Apply lets you invoke the function with arguments as an array; call requires the parameters be listed explicitly. function.apply(valueForThis, [arg1, arg2, ...]) function.call(valueForThis, arg1, arg2, ...) http://stackoverflow.com/questions/1986896/what-is-the-difference-between-call-and-apply A useful mnemonic is "A for array and C for comma."

Truthy and Falsy

Falsy values: false 0 (zero) "" (empty string) null undefined NaN (a special Number value meaning Not-a-Number) The falsy values null and undefined are not equivalent to anything except themselves

function expression

A function expression is very similar to and has almost the same syntax as a function statement (see function statement for details). The main difference between a function expression and a function statement is the function name, which can be omitted in function expressions to create anonymous functions. var x = function(y) { return y * y; };

What is a closure and how/why would you use it?

A function within a function, a closure is an inner function that has access to the outer function's variables. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function's variables, and it has access to the global variables. Properties - Closures have access to the outer function's variable even after the outer function returns. - Closures store references to the outer function's variables Uses: - call a function that generates another function or group of functions but hides all the state in private variables within the closure - closures for events and callbacks - enforce public/private methods http://javascriptissexy.com/understand-javascript-closures-with-ease/

What's a typical use case for anonymous functions?

Anonymous functions are functions that are dynamically declared at runtime. They're called anonymous functions because they aren't given a name. callbacks and closures http://stackoverflow.com/questions/10273185/what-are-the-benefits-to-using-anonymous-functions-instead-of-named-functions-fo - If no name is needed, why add a name to whatever namespace you're in. - Anonymous functions are declared inline and inline functions have advantages in that they can access variables in the parent scopes. Yes, you can put a name on an anonymous function, but that's usually pointless if it's declared inline. So inline has a significant advantage and if you're doing inline, there's little reason to put a name on it. - The code seems more self-contained and readable when handlers are defined right inside the code that's calling them. You can read the code in almost sequential fashion rather than having to go find the function with that name.

what is an array?

Array data structure, an arrangement of items at equally spaced addresses in computer memory. Array data type, used in a programming language to specify a variable that can be indexed. Associative array, an abstract data structure model that generalizes arrays to arbitrary indices individually. Traditionally an array reserves a continuous allocation of memory of predefined length. In JavaScript this is not the case. A JavaScript array is simply a glorified object with a unique constructor and literal syntax and an additional set of properties and methods inherited from Array.prototype. If this means we make a small sacrifice in performance, it is more than compensated for by its ease of use and the power of its utilities. Unlike its counterparts in certain other languages, JavaScript arrays are a joy to use - this is something they definitely got right.

Function constructor

As all other objects, Function objects can be created using the new operator: new Function (arg1, arg2, ... argN, functionBody)

What are promises? What are the pros and cons of using Promises instead of callbacks?

At their most basic, promises are a bit like event listeners except: -A promise can only succeed or fail once. It cannot succeed or fail twice, neither can it switch from success to failure or vice versa -If a promise has succeeded or failed and you later add a success/failure callback, the correct callback will be called, even though the event took place earlier

Difference between document load event and document ready event?

Document ready: executes when HTML-Document is loaded and DOM is ready Document load: executes when complete page is fully loaded, including all frames, objects and images

Describe event bubbling and event capture.

Event bubbling and capturing are two methods of event delegation in JavaScript. In bubbling the event is first captured and handled by the innermost child element and then propagated to outer parent elements. In capturing the event is first captured by the outermost parent element and propagated to the innermost child element.

Event Delegation

Event delegation makes use of two features of JavaScript events: event bubbling and the target element. When an event is triggered on an element, for example a mouse click on a button, the same event is also triggered on all of that element's ancestors. This process is known as event bubbling; the event bubbles up from the originating element to the top of the DOM tree. The target element of any event is the originating element, the button in our example, and is stored in a property of the event object. Using event delegation it's possible to add an event handler to an element, wait for an event to bubble up from a child element and easily determine from which element the event originated. A process of using event propagation to handle events at a higher level in the DOM. Allows us to put a single event listener on the parent element instead multiple on all the children. The parent then simply checks the event target property to get the reference to the actual clicked node.

function declaration

The function declaration defines a function with the specified parameters. function name([param,[, param,[..., param]]]) { [statements] } https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions

AMD vs. CommonJS?

What? AMD Asynchronous Module Definition - less tooling involved - easier to debug - less edge cases that break in browsers src: http://requirejs.org/docs/whyamd.html

Explain why the following doesn't work as an IIFE: function foo(){ }();

When the parser encounters the 'function' keyword in the global scope or inside a function, it treats it as a function declaration (statement), and not as a function expression, by default. You can fix it by wrapping function in parenthesis so parser knows to parse it as a function expression instead of function declaration.

What is a linked list?

a linked list is a data structure consisting of a group of nodes which together represent a sequence. Under the simplest form, each node is composed of data and a reference (in other words, a link) to the next node in the sequence; more complex variants add additional links.

What language constructions do you use for iterating over object properties and array items?

for loop vs. foreach vs. for in http://stackoverflow.com/questions/23614054/javascript-nuances-of-myarray-foreach-vs-for-loop https://gist.github.com/matix/4399652


Related study sets

Module 3.04: Protective & predictive health factors

View Set

Chapter 12: Gender, Sex & Sexuality Quiz & Terms

View Set

Chapter 3- Types of Policies and Riders

View Set

Block 1 (HSFS) Introduction to clinical anatomy Dr. Suji

View Set

Theatre Appreciation Final ch 12

View Set

Chapter 4: Taxes, Retirement, and Other Insurance Concepts

View Set

OA Module 1 Healthy aging, Successful aging, Trends in aging

View Set

Chapter 11: Testing and Laboratory Procedures

View Set

Chapter 36: Patient Interview and History

View Set

2. how did the 1980s arms race contribute to the collapse of the Soviet Union?

View Set

Chapter 2-Evaluting nutrition info assignment

View Set