What is “use strict”;? what are the advantages and disadvantages to using it?
Strict mode makes several changes to normal JavaScript semantics.
First, strict mode eliminates some JavaScript silent errors by changing them to throw errors.
Second, strict mode fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that’s not strict mode.
Third, strict mode prohibits some syntax likely to be defined in future versions of ECMAScript.
‘function block’
JQuery
*find and hide spans
*hide last spane without Id or class
*insert textbox under last span
*set style of element js
TCP/IP - The “Three-Way Handshake”
js 数据类型以及判断
原型和继承
基于闭包实现唯一生成id
跨域
jsonp 具体实现代码
dom 事件和自定义事件系统
前端路由
具体组件api设计和开发
css 常用布局属性
盒模型相关
position
sticky 效果
flex 布局
http://www.code123.cc/406.html
https://github.com/hawx1993/Front-end-Interview-questions
https://github.com/markyun/My-blog/tree/master/Front-end-Developer-Questions/Questions-and-Answers
http://flowerszhong.github.io/
Front-end Job Interview Questions
This file contains a number of front-end interview questions that can be used when vetting potential candidates. It is by no means recommended to use every single question here on the same candidate (that would take hours). Choosing a few items from this list should help you vet the intended skills you require.
Note: Keep in mind that many of these questions are open-ended and could lead to interesting discussions that tell you more about the person’s capabilities than a straight answer would.
Table of Contents
- General Questions
- HTML Questions
- CSS Questions
- JS Questions
- Testing Questions
- Performance Questions
- Network Questions
- Coding Questions
- Fun Questions
Getting Involved
General Questions:
- What did you learn yesterday/this week?
- What excites or interests you about coding?
- What is a recent technical challenge you experienced and how did you solve it?
- What UI, Security, Performance, SEO, Maintainability or Technology considerations do you make while building a web application or site?
- Talk about your preferred development environment.
- Which version control systems are you familiar with?
- Can you describe your workflow when you create a web page?
- If you have 5 different stylesheets, how would you best integrate them into the site?
- Can you describe the difference between progressive enhancement and graceful degradation?
- How would you optimize a website’s assets/resources?
- How many resources will a browser download from a given domain at a time?
- What are the exceptions?
- Name 3 ways to decrease page load (perceived or actual load time).
- If you jumped on a project and they used tabs and you used spaces, what would you do?
- Describe how you would create a simple slideshow page.
- If you could master one technology this year, what would it be?
- Explain the importance of standards and standards bodies.
- What is Flash of Unstyled Content? How do you avoid FOUC?
- Explain what ARIA and screenreaders are, and how to make a website accessible.
- Explain some of the pros and cons for CSS animations versus JavaScript animations.
- What does CORS stand for and what issue does it address?
HTML Questions:
What does a doctype
do?
It’s an integral part of HTML as defined in the specification:
A DOCTYPE is a required preamble.
DOCTYPEs are required for legacy reasons. When omitted, browsers tend to use a different rendering mode that is incompatible with some specifications. Including the DOCTYPE in a document ensures that the browser makes a best-effort attempt at following the relevant specifications.
What does this seatbelt do?
What I can see is that, with this seatbelt on, my car behaves the same way as without. How do I know if I need this seatbelt?
What’s the difference between standards mode and quirks mode?
https://developer.mozilla.org/en-US/docs/Quirks_Mode_and_Standards_Mode
http://www.quirksmode.org/css/quirksmode.html
The two ’modes’ modern browsers can use to interpret your CSS.
In the old days of the web, pages were typically written in two versions: One for Netscape Navigator, and one for Microsoft Internet Explorer. When the web standards were made at W3C, browsers could not just start using them, as doing so would break most existing sites on the web. Browsers therefore introduced two modes to treat new standards compliant sites differently from old legacy sites.
There are now three modes used by the layout engines in web browsers: quirks mode, almost standards mode, and full standards mode. In quirks mode, layout emulates nonstandard behavior in Navigator 4 and Internet Explorer 5. This is essential in order to support websites that were built before the widespread adoption of web standards. In full standards mode, the behavior is (hopefully) the behavior described by the HTML and CSS specifications. In almost standards mode, there are only a very small number of quirks implemented.
How do browsers determine which mode to use?
For HTML documents, browsers use a DOCTYPE in the beginning of the document to decide whether to handle it in quirks mode or standards mode. To ensure that your page uses full standards mode, make sure that your page has a DOCTYPE
The DOCTYPE shown in the example, <!DOCTYPE html>
, is the simplest possible, and the one recommended by HTML5. Earlier versions of the HTML standard recommended other variants, but all existing browsers today will use full standards mode for this DOCTYPE, even the dated Internet Explorer 6. There are no valid reasons to use a more complicated DOCTYPE. If you do use another DOCTYPE, you may risk choosing one which triggers almost standards mode or quirks mode.
Make sure you put the DOCTYPE right at the beginning of your HTML document. Anything before the DOCTYPE, like a comment or an XML declaration will trigger quirks mode in Internet Explorer 9 and older.
In HTML5, the only purpose of the DOCTYPE is to activate full standards mode. Older versions of the HTML standard gave additional meaning to the DOCTYPE, but no browser has ever used the DOCTYPE for anything other than switching between quirks mode and standards mode.
XHTML
If you serve your page as XHTML using the application/xhtml+xml MIME type in the Content-Type HTTP header, you do not need a DOCTYPE to enable standards mode, as such documents always use full standards mode. Note however that serving your pages as application/xhtml+xml will cause Internet Explorer 8 to show a download dialog box for an unknown format instead of displaying your page, as the first version of Internet Explorer with support for XHTML is Internet Explorer 9.
If you serve XHTML-like content using the text/html MIME type, browsers will read it as HTML, and you will need the DOCTYPE to use standards mode.
How do I see which mode is used?
In Firefox, select View Page Info from the context menu, and look for Render Mode.
In Internet Explorer, press F12, and look for Document Mode.
What’s the difference between HTML and XHTML?
XHTML is the XML version of HTML.
To understand this answer you have to know what XML is : it’s a markup language designed to format data in a way that’s easy to understand for a human, and also easy to parse for a machine.
XML is also a meta-language. This means that a lot of languages are based on XML, with rules and grammar defined to make a language with specific purpose from XML. Some well-known examples are OpenMath, MML, XPath, XQuery, …
Now at the beginning of the web, the markup language that was used for web pages was HTML. It looks a lot like XML but it’s not an XML language because it does not respect the XML standard.
Later, XHTML was invented with respect to the XML standard. It is more strict than html because you have to respect all the xml rules (Closing tag for each opening tag, attributes have to have a value etc.)
So the short answer is : xHTML is XML, HTML is not.
XHTML is not so much different from HTML 4.01 standard. The major differences are:
Document Structure
XHTML DOCTYPE is mandatory
The xmlns attribute in is mandatory
, ,
XHTML Elements
XHTML elements must be properly nested
XHTML elements must always be closed
XHTML elements must be in lowercase
XHTML documents must have one root element
XHTML Attributes
Attribute names must be in lower case
Attribute values must be quoted
Attribute minimization is forbidden
Basically, XHTML is HTML (all the html tags are found in XHTML) that follows the rules of XML (because it is a family of XML).
Are there any problems with serving pages as application/xhtml+xml
?
When you’re coding XHTML, you should deliver it as application/xhtml+xml. The problem is however, that once you do that, IE 6 & 7 break horribly… For your pages to render properly in those browsers, you’d need to set the mime type to text/html. Some very bright people have thought this problem in the past and came up with a real good solution in PHP, which you can find here: serving up XHTML with the correct MIME type.
WordPress though is always served as XHTML, so if possible, it should send the proper MIME type. I wrote a small plugin that does that: XHTML MIME type plugin. It doesn’t work on this blog yet because of some modifications I’ve done, but I’ll try to get it working.
I use content negotiation to switch between application/xhtml+xml and text/html just like you describe, without noticing any problems with search bots. Strictly though, you should take into account the q values in the accept header that indicates the preference of the user agent to each content type. If a user agent prefers to accept text/html but will accept application/xhtml+xml as an alternate, then for greatest safety you should have the page served as text/html.
One problem with content negotiation (and with serving different content/headers to different user-agents) is proxy servers. Considering the following; I ran into this back in the Netscape 4 days and have been shy of server side sniffing ever since.
User A downloads your page with Firefox, and gets a XHTML/XML Content-Type. The user’s ISP has a proxy server between the user and your site, so this page is now cached.
User B, same ISP, requests your page using Internet Explorer. The request hits the proxy first, the proxy says “hey, I have that page, here it is; as application/xhtml+xml”. User B is prompted to download the file (as IE will download anything sent as application/xhtml+xml.
You can get around this particular issue by using the Vary Header, as described in this 456 Berea Street article. I also assume that proxy servers have gotten a bit smarter about auto detecting these things.
Here’s where the CF that is HTML/XHTML starts to creep in. When you use content negotiation to serve application/xhtml+xml to one set of user-agents, and text/html to another set of user agents, you’re relying on all the proxies between your server and your users to be well behaved.
Even if all the proxy servers in the world were smart enough to recognize the Vary header (they aren’t) you still have to contend with the computer janitors of the world. There are a lot of smart, talented, and dedicated IT professionals in the world. There are more not so smart people who spend their days double clicking installer applications and thinking “The Internet” is that blue E in their menu. A mis-configured proxy could still improperly cache pages and headers, leaving you out of luck.
How do you serve a page with content in multiple languages?
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
What kind of things must you be wary of when design or developing for multilingual sites?
1.Language Codes
- Setting the primary language
- Using the wrong language code
2.Multiple Languages<blockquote lang="fr">
<a href="" hreflang="fr">French</a>
<a href="" lang="fr" hreflang="fr">Francais</a>
3.Google and language recognition
4.Language direction<html dir="rtl">
5.Character encoding<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
For HTML 5 use:<meta charset="UTF-8">
6.Font sizes
<html lang="en"> |
:lang(en) { |
7.Length of words
What are data-
attributes good for?
https://developer.mozilla.org/en/docs/Web/Guide/HTML/Using_data_attributes
HTML5 is designed with extensibility in mind for data that should be associated with a particular element but need not have any defined meaning. data-* attributes allow us to store extra information on standard, semantic HTML elements without other hacks such as classList, non-standard attributes, extra properties on DOM, or setUserData.
HTML Syntax
The syntax is simple. Any attribute on any element whose attribute name starts with data- is a data attribute. Say you have an article and you want to store some extra information that doesn’t have any visual representation. Just use data attributes for that:
<article |
JavaScript Access
Reading the values of these attributes out in JavaScript is also very simple. You could use getAttribute() with their full HTML name to read them, but the standard defines a simpler way: a DOMStringMap you can read out via a dataset property.
To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase).
var article = document.getElementById('electriccars'); |
Each property is a string and can be read and written. In the above case setting article.dataset.columns = 5 would change that attribute to “5”.
CSS Access
Note that, as data attributes are plain HTML attributes, you can even access them from CSS. For example to show the parent data on the article you can use generated content in CSS with the attr() function:
article::before { |
You can see all this working together.
Data attributes can also be stored to contain information that is constantly changing, like scores in a game. Using the CSS selectors and JavaScript access here this allows you to build some nifty effects without having to write your own display routines. See this screencast for an example using generated content and CSS transitions (JSBin example).
Since data values are strings, all values must have quotes or else the styling won’t have any effect.
Consider HTML5 as an open web platform. What are the building blocks of HTML5?
more semantic text markup
new form elements
vedio and audio
new javascript API
canvas and SVG
new communication API
geolocation API
web worker API
new data storage
Describe the difference between a cookie
, sessionStorage
and localStorage
.
localStorage and sessionStorage are both so-called WebStorages and features of HTML5.
localStorage stores information as long as the user does not delete them.
sessionStorage stores information as long as the session goes. Usually until the user closes the tab/browser.
cookies are simply cookies, which are supported by older browsers and usually are a fallback for frameworks that use the above mentioned WebStorages.
In contrast cookies can store way less information then WebStorages and the information in WebStorages is never transferred to the server.
This is an extremely broad scope question, and a lot of the pros/cons will be contextual to the situation.
In all cases these storage mechanisms will be specific to an individual browser on an individual computer/device. Any requirement to store data on an ongoing basis across sessions will need to involve your application server side - most likely using a database, but possibly XML or a text/CSV file.
localStorage, sessionStorage and cookies are all client storage solutions. Session data is held on the server where it remains under your direct control.
localStorage and sessionStorage
localStorage and sessionStorage are relatively new APIs (meaning not all legacy browsers will support them) and are near identical (both in APIs and capabilities) with the sole exception of persistence. sessionStorage (as the name persists) is only available for the duration of the browser session (and is deleted when the window is closed) - it does however survive page reloads (source DOM Storage guide - Mozilla Developer Network).
Clearly, if the data you are storing needs to be available on an ongoing basis then localStorage is preferable to sessionStorage - although you should note both can be cleared by the user so you should not rely on the continuing existence of data in either case.
localStorage and sessionStorage are perfect for persisting non-sensitive data needed within client scripts between pages (for example: preferences, scores in games). The data stored in localStorage and sessionStorage can easily be read or changed from within the client/browser so should not be relied upon for storage of sensitive or security related data within applications.
Cookies
This is also true for cookies, these can be trivially tampered with by the user, and data can also be read from them in plain text - so if you are wanting to store sensitive data then session is really your only option. If you are not using SSL, cookie information can also be intercepted in transit, especially on an open wifi.
On the positive side cookies can have a degree of protection applied from security risks like Cross-Site Scripting (XSS)/Script injection by setting an HTTP only flag which means modern (supporting) browsers will prevent access to the cookies and values from JavaScript (this will also prevent your own, legitimate, JavaScript from accessing them). This is especially important with authentication cookies, which are used to store a token containing details of the user who is logged on - if you have a copy of that cookie then for all intents and purposes you become that user as far as the web application is concerned, and have the same access to data and functionality the user has.
As cookies are used for authentication purposes and persistence of user data, all cookies valid for a page are sent from the browser to the server for every request to the same domain - this includes the original page request, any subsequent Ajax requests, all images, stylesheets, scripts and fonts. For this reason cookies should not be used to store large amounts of information. Browser may also impose limits on the size of information that can be stored in cookies. Typically cookies are used to store identifying tokens for authentication, session and advertising tracking. The tokens are typically not human readable information in and of themselves, but encrypted identifiers linked to your application or database.
localStorage vs. sessionStorage vs. Cookies
In terms of capabilities, cookies only allow you to store strings. sessionStorage and localStorage allow you to store JavaScript primitives but not Objects or Arrays (it is possible to JSON serialise them to store them using the APIs). Session storage will generally allow you to store any primitives or objects supported by your Server Side language/framework.
Client-side vs. Server-side
As HTTP is a stateless protocol - web applications have no way of identifying a user from previous visits on returning to the web site - session data usually relies on a cookie token to identify the user for repeat visits (although rarely URL parameters may be used for the same purpose). Data will usually have a sliding expiry time (renewed each time the user visits), and depending on your server/framework data will either be stored in-process (meaning data will be lost if the web server crashes or is restarted) or externally in a state server or database. This is also necessary when using a web-farm (more than one server for a given website).
As session data is completely controlled by your application (server side) it is the best place for anything sensitive or secure in nature.
The obvious disadvantage with server side data is scalability - server resources are required for each user for the duration of the session, and that any data needed client side must be sent with each request. As the server has no way of knowing if a user navigates to another site or closes their browser, session data must expire after a given time to avoid all server resources being taken up by abandoned sessions. When using session data you should therefore be aware of the possibility that data will have expired and been lost, especially on pages with long forms. It will also be lost if the user deletes their cookies or switches browsers/devices.
Some web frameworks/developers use hidden HTML inputs to persist data from one page of a form to another to avoid session expiration.
localStorage, sessionStorage and cookies are all subject to “same-origin” rules which means browsers should prevent access to the data except from the domain that set the information to start with.
Describe the difference between
<script> |
http://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html
<script> |
Let’s start by defining what script tag without any attributes does. The HTML file will be parsed until the script file is hit, at that point parsing will stop and a request will be made to fetch the file (if it’s external). The script will then be executed before parsing is resumed.
<script async=""> |
async downloads the file during HTML parsing and will pause the HTML parser to execute it when it has finished downloading.
<script defer> |
defer downloads the file during HTML parsing and will only execute it after the parser has completed. defer scripts are also guarenteed to execute in the order that they appear in the document.
When should I use what? Typically you want to use async where possible, then defer then no attribute. Here are some general rules to follow:
- If the script is modular and does not rely on any scripts then use async.
- If the script relies upon or is relied upon by another script then use defer.
- If the script is small and is relied upon by an async script then use an inline script with no attributes placed above the async scripts.
Why is it generally a good idea to position CSS <link>
s between <head></head>
and JS script tags just before </body>
? Do you know any exceptions?
The reasoning for <link>
at the top is browsers have to reflow the layout as CSS files load (if they’re not in the <head>
tag) moving elements around while the user is trying to interact with the page. For script tag files at the end, browsers have to (in most cases) block processing the HTML while a JavaScript file is loaded and run in case it makes in Write() calls (which you’re not supposed to do anymore these days); if the script tag is at the end, the browser can still display all of the HTML above the script tags while it is processing the JavaScript.
Just to add on to what jdelStrother has mentioned about w3 specs and ARTstudio about browser rendering.
It is recommended because when you have the CSS declared before <body>
starts, your styles has actually loaded already. So very quickly users see something appear on their screen (e.g. background colors). If not, users see blank screen for some time before the CSS reaches the user.
Also, if you leave the the styles somewhere in the <body>
, the browser has to re-render the page (new and old when loading) when the styles declared has been parsed.
What is progressive rendering?
Why you would use a srcset attribute in an image tag? Explain the process the browser uses when evaluating the content of this attribute.
Have you used different HTML templating languages before?
CSS Questions:
What is the difference between visibility:hidden and display:none?
display:none means that the tag in question will not appear on the page at all (although you can still interact with it through the dom). There will be no space allocated for it between the other tags.
visibility:hidden means that unlike display:none, the tag is not visible, but space is allocated for it on the page. The tag is rendered, it just isn’t seen on the page.For example:
test | Appropriate style in this tag | test
Replacing [style-tag-value] with display:none results in:test | | test
Replacing [style-tag-value] with visibility:hidden results in:test | | test
CSS selector
http://www.w3schools.com/cssref/css_selectors.asp
Selector | Example | Example description | CSS | ||
---|---|---|---|---|---|
element,element | div, p | Selects all elements and all elements |
1 | ||
element element | div p | Selects all elements inside elements |
1 | ||
element>element | div > p | Selects all elements where the parent is a element |
2 | ||
element+element | div + p | Selects all elements that are placed immediately after elements |
2 | ||
element1~element2 | div ~ p | Selects every element that are preceded by a element |
3 | ||
[attribute] | [target] | Selects all elements with a target attribute | 2 | ||
[attribute=value] | [target=_blank] | Selects all elements with target=”_blank” | 2 | ||
[attribute~=value] | [title~=flower] | Selects all elements with a title attribute containing the word “flower” | 2 | ||
[attribute | =value] | [lang | =en] | Selects all elements with a lang attribute value starting with “en” | 2 |
[attribute^=value] | a[href^=”https”] | Selects every element whose href attribute value begins with “https” | 3 | ||
[attribute$=value] | a[href$=”.pdf”] | Selects every element whose href attribute value ends with “.pdf” | 3 | ||
[attribute*=value] | a[href*=”w3schools”] | Selects every element whose href attribute value contains the substring “w3schools” | 3 | ||
:first-child | p:first-child Selects every element that is the first child of its parent |
2 | |||
:hover | a:hover Selects links on mouse over | 1 | |||
:last-child | p:last-child Selects every element that is the last child of its parent |
3 | |||
:nth-child(n) | p:nth-child(2) Selects every element that is the second child of its parent |
3 | |||
:nth-last-child(n) | p:nth-last-child(2) Selects every element that is the second child of its parent, counting from the last child |
3 |
What is the difference between classes and ID’s in CSS?
What is CSS selector specificity and how does it work?
What’s the difference between “resetting” and “normalizing” CSS? Which would you choose, and why?
Describe Floats and how they work.
http://www.w3schools.com/cssref/pr_class_float.asp
http://www.w3schools.com/css/css_float.aspDescribe z-index and how stacking context is formed.
- Describe BFC(Block Formatting Context) and how it works.
- What are the various clearing techniques and which is appropriate for what context?
- Explain CSS sprites, and how you would implement them on a page or site.
- What are your favourite image replacement techniques and which do you use when?
- How would you approach fixing browser-specific styling issues?
How do you serve your pages for feature-constrained browsers?
- What techniques/processes do you use?
What are the different ways to visually hide content (and make it available only for screen readers)?
- Have you ever used a grid system, and if so, what do you prefer?
Have you used or implemented media queries or mobile specific layouts/CSS?
https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries<!-- CSS media query on a link element -->
<link rel="stylesheet" media="(max-width: 800px)" href="example.css" />
<!-- CSS media query within a stylesheet -->
<style>
@media (max-width: 600px) {
.facet_sidebar {
display: none;
}
}
@media tv and (min-width: 700px) and (orientation: landscape) { ... }
</style>Are you familiar with styling SVG?
- Can you give an example of an @media property other than screen ?
- How do you optimize your webpages for print?
- What are some of the “gotchas” for writing efficient CSS?
What are the advantages/disadvantages of using CSS preprocessors?
- Describe what you like and dislike about the CSS preprocessors you have used.
SASS and LESS
- Describe what you like and dislike about the CSS preprocessors you have used.
How would you implement a web design comp that uses non-standard fonts?
- Explain how a browser determines what elements match a CSS selector.
!important > id > class > element - Describe pseudo-elements and discuss what they are used for.
- Explain your understanding of the box model and how you would tell the browser in CSS to render your layout in different box models.
- What does
{ box-sizing: border-box; }
do? What are its advantages? - What is the CSS display property and can you give a few examples of its use?
List as many values for the display property that you can remember.
What’s the difference between inline and inline-block?
What’s the difference between the “nth-of-type()” and “nth-child()” selectors?
What’s the difference between a relative, fixed, absolute and statically positioned element?
The ‘C’ in CSS stands for Cascading. How is priority determined in assigning styles (a few examples)? How can you use this system to your advantage?
What existing CSS frameworks have you used locally, or in production? How would you change/improve them?
Have you played around with the new CSS Flexbox or Grid specs?
How is responsive design different from adaptive design?
- Can you explain the difference between coding a web site to be responsive versus using a mobile-first strategy?
- Have you ever worked with retina graphics? If so, when and what techniques did you use?
- Is there any reason you’d want to use
translate()
instead ofabsolute positioning
, or vice-versa? And why?
JS Questions:
Explain event delegation
DOM event delegation is a mechanism of responding to ui-events via a single common parent rather than each child, through the magic of event “bubbling” (aka event propagation).
When an event is triggered on an element, the following occurs:
The event is dispatched to its target EventTarget and any event listeners found there are triggered. Bubbling events will then trigger any additional event listeners found by following the EventTarget’s parent chain upward, checking for any event listeners registered on each successive EventTarget. This upward propagation will continue up to and including the Document.
Event bubbling provides the foundation for event delegation in browsers. Now you can bind an event handler to a single parent element, and that handler will get executed whenever the event occurs on any of its child nodes (and any of their children in turn). This is event delegation. Here’s an example of it in practice:
<ul onclick="alert(event.type + '!')"> |
With that example if you were to click on any of the child
So what’s the benefit?
Imagine you now have a need to dynamically add new
var newLi = document.createElement('li'); |
Without using event delegation you would have to “rebind” the “onclick” event handler to the new
This is absolutely fantastic for web apps with event handlers bound to many elements, where new elements are dynamically created and/or removed in the DOM. With event delegation the number of event bindings can be drastically decreased by moving them to a common parent element, and code that dynamically creates new elements on the fly can be decoupled from the logic of binding their event handlers.
Another benefit to event delegation is that the total memory footprint used by event listeners goes down (since the number of event bindings go down). It may not make much of a difference to small pages that unload often (i.e. user’s navigate to different pages often). But for long-lived applications it can be significant. There are some really difficult-to-track-down situations when elements removed from the DOM still claim memory (i.e. they leak), and often this leaked memory is tied to an event binding. With event delegation you’re free to destroy child elements without risk of forgetting to “unbind” their event listeners (since the listener is on the ancestor). These types of memory leaks can then be contained (if not eliminated, which is freaking hard to do sometimes. IE I’m looking at you).
Here are some better concrete code examples of event delegation:
How JavaScript Event Delegation Works
https://davidwalsh.name/event-delegate
Event Delegation versus Event Handling
jQuery.delegate is event delegation + selector specification
jQuery.on uses event delegation when passed a selector as the 2nd parameter
Event delegation without a JavaScript library
Closures vs Event delegation: takes a look at the pros of not converting code to use event delegation
Interesting approach PPK uncovered for delegating the focus and blur events (which do not bubble)
Explain how this
works in JavaScript
http://davidshariff.com/blog/JavaScript-this-keyword/
JavaScript’s this
Keyword
A commonly used feature of JavaScript is the “this” keyword, but it is often also one of the most confused and misinterpreted features of the language. What does “this” actually mean and how is it decided?
This article tries to clear up the confusion and explain the answer in a clear fashion.
The this
keyword is not new to those who have programmed in other languages, and more often than not it refers to the new object created when instantiating a class via it’s constructor. For example, if I have a class Boat(), which has a method moveBoat(), when refering to “this” inside of the moveBoat() method, we are actually accessing the newly created object of Boat().
In JavaScript, we also have this concept inside a Function constructor when it is invoked using the “new” keyword, however it is not the only rule and “this” can often refer to a different object from a different execution context. If you are not familiar with JavaScript’s execution context, I recommend you read my other post on the topic here. Enough talking, let’s see some JavaScript examples:
// global scope |
Whenever you use the keyword this
in the global context (not inside a function), it always refers to the global object. Now let’s look at the value of “this” inside a function:
http://www.cnblogs.com/isaboy/p/javascript_this.html
http://bjorn.tipling.com/all-this
2.Explain how prototypal inheritance works
var oldObject = { |
What do you think of AMD vs CommonJS?
Module System | Common Syntax |
---|---|
CommonJS | require,module.exports |
AMD | require,define |
ES2015 | import,export |
Explain why the following doesn’t work as an IIFE: function foo(){ }();
.
What needs to be changed to properly make it an IIFE?
(function foo(){})() |
It’s an Immediately-Invoked Function Expression, or IIFE for short. It executes immediately after it’s created.
It has nothing to do with any event-handler for any events (such as document.onload).
The first pair of parentheses (function(){…}) turns the code within (in this case, a function) into an expression, and the second pair of parentheses (function(){…})() calls the function that results from that evaluated expression.
This pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE (like in any other normal function) are not visible outside its scope.
This is why, maybe, you confused this construction with an event-handler for window.onload, because it’s often used as this:
(function(){
// all your code here
var foo = function() {};
window.onload = foo;
// …
})();
// foo is unreachable here (it’s undefined)
Correction suggested by Guffa:
The function is executed right after it’s created, not after it is parsed. The entire script block is parsed before any code in it is executed. Also, parsing code doesn’t automatically mean that it’s executed, if for example the IIFE is inside a function then it won’t be executed until the function is called.
https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
http://benalman.com/news/2010/11/immediately-invoked-function-expression/
3.What’s the difference between a variable that is: null
, undefined
or undeclared?
First up is undeclared.
A variable is undeclared when it does not use the var keyword.
It gets created on the global object (that is, the window), thus it operates in a different space as the declared variables.
var declaredVariable = 1; |
Note: this will not work in strict mode.
It will throw an error when it gets to the undeclaredVariable.
Something is undefined when it hasn’t been defined yet.
If you call a variable or function without having actually created it yet the parser will give you an not defined error.
var undefinedVariable; // undefined |
Note that the typeof returns “undefined”, therefore undefined is a primitive type.
The fix for an undefined variable or function is easy, simply define it:
var definedVariable = 'test'; |
You can know if a variable is undefined with the following:
if (typeof(variable) !== "undefined") { |
null is a variable that is defined to have a null value.
var nullVariable = null; // null |
You probably don’t often purposefully define a variable to null, but it may be the return value of a function. Often you’ll need to gaurd against null values in your code.
You can know if a variable is null with the following:
if( variable === null ) { |
if(!variable) |
I think the order “undeclared, undefined, and null” makes sense since it’s increasing order of certainty.
undeclared variables don’t even exist
undefined
variables exist, but don’t have anything assigned to them using “typeof” to check.
*null
variables exist and have null
assigned to them using “!” mark to check.
How would you go about checking for any of these states?
if (variable === null) {} |
4.What is a closure, and how/why would you use one?
http://stackoverflow.com/questions/111102/how-do-javascript-closures-work
http://javascriptissexy.com/understand-javascript-closures-with-ease/
https://developer.mozilla.org/en/docs/Web/JavaScript/Closures
function makeFunc() { |
how to handle exception?
http://eloquentjavascript.net/08_error.html
Can you describe the main difference between a forEach loop and a .map() loop and why you would pick one versus the other?
What’s a typical use case for anonymous functions?
How do you organize your code? (module pattern, classical inheritance?)
What’s the difference between host objects and native objects?
6.Difference between: function Person(){}
, var person = Person()
, and var person = new Person()
?
7.What’s the difference between .call
and .apply
?
The difference is that
apply lets you invoke the function with arguments as an array call requires the parameters be listed explicitly.
A useful mnemonic is “A for array and C for comma.”
See MDN’s documentation on apply and call.
Pseudo syntax:
theFunction.apply(valueForThis, arrayOfArgs) |
8.Explain Function.prototype.bind
.
this.x = 9; |
When would you use document.write()
?
A few of the more serious problems:
document.write (henceforth DW) does not work in XHTML
DW does not directly modify the DOM, preventing further manipulation (trying to find evidence of this, but it’s at best situational)
DW executed after the page has finished loading will overwrite the page, or write a new page, or not work
DW executes where encountered: it cannot inject at a given node point
DW is effectively writing serialised text which is not the way the DOM works conceptually, and is an easy way to create bugs (.innerHTML has the same problem)
What’s the difference between feature detection, feature inference, and using the UA string?
Explain AJAX in as much detail as possible.
Explain how JSONP works (and how it’s not really AJAX).
JSONP (JSON with Padding) is a technique used by web developers to overcome the cross-domain restrictions imposed by browsers to allow data to be retrieved from systems other than the one the page was served by.
JSONP (as in “JSON with Padding”) is a method commonly used to bypass the cross-domain policies in web browsers (you are not allowed to make AJAX requests to a webpage perceived to be on a different server by the browser).
JSON and JSONP behave differently on both the client and the server. JSONP requests are not dispatched using the XMLHTTPRequest (and the associated browser methods), instead a <script>
tag is created, whose source is set to the target URL. This script tag is then added to the DOM (normally the
JSON Request:
var xhr = new XMLHttpRequest(); |
JSONP Request:
var tag = document.createElement("script"); |
The difference between a JSON response and a JSONP response, is that the JSONP response is formulated such that the response object is passed as an argument to a callback function.
JSON:{
"bar": "baz"
}
JSONP:foo({
"bar": "baz"
});
This is why you see JSONP requests containing the “callback” parameter; so the server knows the name of the function to wrap the response around.
This function must exist in the global scope at the time the \
Another difference to be aware of between the handling of a JSON response and a JSONP response, is that any parse errors in a JSON response can potentially be caught (by wrapping the attempt to evaluate the responseText in a try/catch statement). Because of the nature of a JSONP response however, parse errors in the response will yield an uncatchable JS Parse error. Both formats however, can implement timeout errors (by setting a timeout before initiating the request, and clearing the timeout in the response handler.
The usefulness of using jQuery to make JSONP requests, is that jQuery does alllllllll of the work for you in the background.
jQuery requires (by default), for you to include &callback=? in the URL of your AJAX request. jQuery will take the success function you specify, assign it a unique name and publish it in the global scope. It will then replace the ? in &callback=? with the name it’s just assigned the function.
Comparable JSON/ JSONP Implementations (assuming response object is {“bar”:”baz”}:
JSONvar xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("output").innerHTML = eval('(' + this.responseText + ')').bar;
};
};
xhr.open("GET", "somewhere.php", true);
xhr.send();
JSONP:function foo(response) {
document.getElementById("output").innerHTML = response.bar;
};
var tag = document.createElement("script");
tag.src = 'somewhere_else.php?callback=foo';
document.getElementsByTagName("head")[0].appendChild(tag);
Have you ever used JavaScript templating? If so, what libraries have you used ?
handlerbar
Explain “hoisting”.
https://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/
Describe event bubbling.
Describe event capturing.
What’s the difference between an “attribute” and a “property”?
*html element it can be “class” anb “id” which you can see in the html markups
*property is the dom property for the html element such ask firstChild lastChild.
Why is extending built-in JavaScript objects not a good idea?
Difference between window load event and document DOMContentLoaded event?
$(document).ready(function() { |
9.What is the difference between ==
and ===
?
“==” “equal to”
make certain converion
“===” strict equal to
same type and same value
JavaScript has both strict and type-converting equality comparison. For strict equality the objects being compared must have the same type and:
Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another.
Two Boolean operands are strictly equal if both are true or both are false.
Two objects are strictly equal if they refer to the same Object.
*Null and Undefined types are == (but not ===). [I.e. (Null==Undefined) is true but (Null===Undefined) is false]
10.Explain the same-origin policy with regards to JavaScript.
In computing, the same-origin policy is an important concept in the web application security model.
Under the policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin.
Make this work:
duplicate([1,2,3,4,5]); // [1,2,3,4,5,1,2,3,4,5] |
Why is it called a Ternary expression, what does the word “Ternary” indicate?
Create a for loop that iterates up to 100
while outputting “fizz” at multiples of 3
, “buzz” at multiples of 5
and
“fizzbuzz” at multiples of 3
and 5
Why is it, in general, a good idea to leave the global scope of a website as-is and never touch it?
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?
Explain what a single page app is and how to make one SEO-friendly.
*SiteMap + Robots.txt
*Friendly Url + Lower case
*Canonical URL
*Minificatioin+bundling
*JS CSS Files at bottom of page
*W3C standard
*Unique H1
*Server Side Rending!!
What is the extent of your experience with Promises and/or their polyfills?
12.What are the pros and cons of using Promises instead of callbacks?
follow the flow.
What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?
Normalize your javascript.
Syntax learning for typescript or coffeescript.
Typescript compile type checking.
OOP
Why ‘Typescript’ ?
A superset of ECMAscript that including all ecmascript feature (class, class inheritance, static) + some proposal feature (Decroator)
You get the type, which also provides with compile time check, intellise.
define ‘type’
You get oop feature such interface, abstract (abstraction), access modifiers(Encapsulation), function overloads(Polymorphism), generic for type checking.
Some another feature like Union Type, readonly
test: String|Number
interface extends interface
class extends class
class implements interface
interface extends class
What tools and techniques do you use debugging JavaScript code?
Chrome dev tool and node command prompt.
What language constructions do you use for iterating over object properties and array items?
For (var I = 0;I < array.length; I += 1) { |
forEach |
Iterate through all of the members of an object:
for (var name in object) { |
for of |
Difference between for…of and for…in
Both for…in and for…of statements iterate over something. The main difference between them is in what they iterate over.
The for…in statement iterates over the enumerable properties of an object, in an arbitrary order.
The for…of statement iterates over data that iterable object defines to be iterated over.
The following example shows the difference between a for…of loop and a for…in loop when used with an Array.
Object.prototyp
Explain the difference between mutable and immutable objects.
- What is an example of an immutable object in JavaScript?
- What are the pros and cons of immutability?
- How can you achieve immutability in your own code?
Explain the difference between synchronous and asynchronous functions.
13.What is event loop?
What is the difference between call stack and task queue?
Explain the differences on the usage of foo between function foo() {} and var foo = function() {}
What are the differences between variables created using let, var or const?
What are the differences between ES6 class and ES5 function constructors?
Can you offer a use case for the new arrow => function syntax? How does this new syntax differ from other functions?
What advantage is there for using the arrow syntax for a method in a constructor?
What is the definition of a higher-order function?
Can you give an example for destructuring an object or an array?
ES6 Template Literals offer a lot of flexibility in generating strings, can you give an example?
Can you give an example of a curry function and why this syntax offers an advantage?
What are the benefits of using spread syntax and how is it different from rest syntax?
How can you share code between files?
Why you might want to create static class members?
Testing Questions:
- What are some advantages/disadvantages to testing your code?
- What tools would you use to test your code’s functionality?
- What is the difference between a unit test and a functional/integration test?
- What is the purpose of a code style linting tool?
Performance Questions:
- What tools would you use to find a performance bug in your code?
- What are some ways you may improve your website’s scrolling performance?
- Explain the difference between layout, painting and compositing.
Network Questions:
- Traditionally, why has it been better to serve site assets from multiple domains?
- Do your best to describe the process from the time you type in a website’s URL to it finishing loading on your screen.
- What are the differences between Long-Polling, Websockets and Server-Sent Events?
- Explain the following request and response headers:
- Diff. between Expires, Date, Age and If-Modified-…
- Do Not Track
- Cache-Control
- Transfer-Encoding
- ETag
- X-Frame-Options
- What are HTTP actions? List all HTTP actions that you know, and explain them.
Coding Questions:
Question: What is the value of foo
?
var foo = 10 + '20'; |
Question: How would you make this work?
function add(a,b){ |
Question: What value is returned from the following statement?"i'm a lasagna hog".split("").reverse().join("");
Question: What is the value of window.foo
?( window.foo || ( window.foo = "bar" ) );
Question: What is the outcome of the two alerts below?var foo = "Hello";
(function() {
var bar = " World";
alert(foo + bar);
})();
alert(foo + bar);
Question: What is the value of foo.length
?var foo = [];
foo.push(1);
foo.push(2);
Question: What is the value of foo.x
?var foo = {n: 1};
var bar = foo;
foo.x = foo = {n: 2};
Question: What does the following code print?console.log('one');
setTimeout(function() {
console.log('two');
}, 0);
console.log('three');
Fun Questions:
- What’s a cool project that you’ve recently worked on?
- What are some things you like about the developer tools you use?
- Do you have any pet projects? What kind?
- What’s your favorite feature of Internet Explorer?
- How do you like your coffee?