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/DavidKk/david-dev-backup/blob/master/%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91%20-%20%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md

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

  1. General Questions
  2. HTML Questions
  3. CSS Questions
  4. JS Questions
  5. Testing Questions
  6. Performance Questions
  7. Network Questions
  8. Coding Questions
  9. Fun Questions

Getting Involved

  1. Contributors
  2. How to Contribute
  3. License

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
, , , and <body> are mandatory<br><strong>XHTML Elements</strong> </body>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">
<html lang="zh">
:lang(en) {

font-size: 85%;

font-family: arial, verdana, sans-serif;

}


:lang(zh) {

font-size: 125%;

font-family: helvetica, verdana, sans-serif;

}

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
id="electriccars"
data-columns="3"
data-index-number="12314"
data-parent="cars">

...
</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');

article.dataset.columns // "3"
article.dataset.indexNumber // "12314"
article.dataset.parent // "cars"

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 {
content: attr(data-parent)
;

}
You can also use the attribute selectors in CSS to change styles according to the data:

article[data-columns='3'] {
width: 400px
;

}
article[data-columns='4'] {
width: 600px;
}

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>
<script async="">
<script defer>

http://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html

legend

<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

<script async="">

async downloads the file during HTML parsing and will pause the HTML parser to execute it when it has finished downloading.

script

<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.

script

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.asp

  • Describe 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
  • 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 of absolute 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 + '!')">
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>

With that example if you were to click on any of the child

  • nodes, you would see an alert of “click!”, even though there is no click handler bound to the
  • you clicked on. If we bound onclick=”…” to each
  • you would get the same effect.
  • So what’s the benefit?

    Imagine you now have a need to dynamically add new

  • items to the above list via DOM manipulation:
  • var newLi = document.createElement('li');
    newLi.innerHTML = 'Four';
    myUL.appendChild(newLi);

    Without using event delegation you would have to “rebind” the “onclick” event handler to the new

  • element, in order for it to act the same way as its siblings. With event delegation you don’t need to do anything. Just add the new
  • to the list and you’re done.
  • 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

    foo = 'abc';
    alert(foo); // abc

    this.foo = 'def';
    alert(foo); // def

    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 = {
    firstMethod: function () { ... },
    secondMethod: function () { ... }
    };

    var newObject = Object.create(oldObject);

    newObject.thirdMethod = function () { ... };

    var myDoppelganger = Object.create(newObject);

    myDoppelganger.firstMethod();

    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(){})()
    (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;

    function scoppedVariables() {
    undeclaredVariable = 1;
    var declaredVariable = 2;
    }

    scoppedVariables();

    undeclaredVariable; // 1
    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
    typeof undefinedVariable; // "undefined"

    undefinedFunction(); // undefined
    typeof undefinedFunction; // "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';
    typeof definedVariable; // "string"

    function definedFunction(){
    return "I'm defined!"
    }
    typeof definedFunction // "function"

    You can know if a variable is undefined with the following:

    if (typeof(variable) !== "undefined") {
    console.log('variable is not undefined');
    } else {
    console.log('variable is undefined');
    }
    null is a variable that is defined to have a null value.
    var nullVariable = null; // null
    typeof nullVariable // "object"

    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 ) {
    console.log('variable is null');
    } else {
    console.log('variable is not 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) {}

    if (typeof(variable) !== "undefined") {}

    if(!variable)

    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() {
    var name = "Mozilla";
    function displayName() {
    alert(name);
    }
    return displayName;
    }

    var myFunc = makeFunc();
    myFunc();

    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)

    theFunction.call(valueForThis, arg1, arg2, ...)

    8.Explain Function.prototype.bind.

    this.x = 9; 
    var module = {
    x: 81,
    getX: function() { return this.x; }
    };

    module.getX(); // 81

    var retrieveX = module.getX;
    retrieveX();
    // returns 9 - The function gets invoked at the global scope

    // Create a new function with 'this' bound to module
    // New programmers might confuse the
    // global var x with module's property x
    var boundGetX = retrieveX.bind(module);
    boundGetX(); // 81

    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();

    xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
    // success
    };
    };

    xhr.open("GET", "somewhere.php", true);
    xhr.send();

    JSONP Request:

    var tag = document.createElement("script");
    tag.src = 'somewhere_else.php?callback=foo';

    document.getElementsByTagName("head")[0].appendChild(tag);

    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 \ tag is evaluated by the browser (once the request has completed).

    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”}:

    JSON

    var 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() {
    // executes when HTML-Document is loaded and DOM is ready
    alert("document is ready");
    });


    $(window).load(function() {
    // executes when complete page is fully loaded, including all frames, objects and images
    alert("window is loaded");
    });

    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]

    http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-JavaScript-comparisons

    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) {
    // within the loop,
    // I is the index of the current member
    // array[i] is the current element
    }
    forEach

    Iterate through all of the members of an object:

    for (var name in object) {
    If (object.hasOwnPropert(name)) {

    // within the loop,
    // name is the key of current member
    // object[name] is the current value

    }
    }
    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){ 
    return !b ? a + b : function(b){ return a + b; }
    }

    add(2, 5); // 7
    add(2)(5); // 7

    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?

    *Exercises

    The sum of a range

    function range(start, end, step) {
    // If no optional step, set step to 1.
    if (step == null) step = 1;

    // Initialize the array that will eventually be returned.
    var array = [];

    // If the range is increasing, continue pushing i to the
    // array and incrementing i by step until i is greater than
    // end, then stop.
    if (step > 0) {
    for (var i = start; i <= end; i += step)
    array.push(i);
    // If the range is decreasing, continue pushing i to the
    // array until i is less than end, then stop.
    // Remember i will get smaller because step is negative.
    } else {
    for (var i = start; i >= end; i += step)
    array.push(i);
    }
    // Return the result
    return array;
    }

    function sum(array) {
    // Set total to start at 0.
    var total = 0;
    // Go through each item in the array and add it to result.
    for (var i = 0; i < array.length; i++)
    total += array[i];
    // Return result.
    return total;
    }

    console.log(sum(range(1, 10)));
    // → 55
    console.log(range(5, 2, -1));
    // → [5, 4, 3, 2]

    ×Reversing an array

    /*
    function reverseArrayInPlace(array) {
    for (var i = 0; i < Math.floor(array.length / 2); i++) {
    var old = array[i];
    array[i] = array[array.length - 1 - i];
    array[array.length - 1 - i] = old;
    }
    return array;
    }
    */


    function reverseArrayInPlace(array) {
    var b = array.length;
    for (var i = 0; i < --b; i++) {
    var swap = array[i];
    array[i] = array[b];
    array[b] = swap;
    }
    return array;
    }

    function reverseArray(array) {
    var output = [];

    for (i = array.length - 1; i >= 0 ; i--)
    {
    output.push(array[i]);
    }

    return output;
    }

    console.log(reverseArray(["A", "B", "C"]));
    // → ["C", "B", "A"];
    var arrayValue = [1, 2, 3, 4, 5];
    reverseArrayInPlace(arrayValue);
    console.log(arrayValue);
    // → [5, 4, 3, 2, 1]

    1. Baseline
      Image optimisation, Minification, Concatenation. Compression(GZip, Zopfli), Async scripts, Leverage caching, WOFF2 for fonts, Spriting.
      Avoid redirects.

    2. Get fast, stay fast.

      Inlining critical CSS, deferring non-critical assets to avoid render blocking, removing unused CSS, visual regression testing to verify changes.
      Service Worker for offline caching. Performance budgets.

    3. Nice to haves
      Reduce unused code, remove duplicate colours, selectors, font-families, sizes.

    Nullable modifier ? when decaring a value type variable

    Drawbacks of Non-Generics

    Lack of type checking

    e.g. System.Collections.Stack

    • Lack of validation check for which type pushed into stack.

    • No safe check for explicitly casting for the pop item into type.

    Boxing and Unboxing with heave performance impact

    Boxing
    

    Value Type ========> Reference Type +++++ more overhead performance impact (allocate memory -> copy the value -> garbage-collect that memory)

    Unboxing
    

    Reference Type ==========> Value Type + negligible performance impact

    Benefits of Generics

    There are several advantages to using a generic class over a nongeneric version

    (such as the System.Collections.Generic.Stack class used earlier instead of the original System.Collections.Stack type.

    No longer need to cast the return of path.Pop() or ensure that only Cell type objects are added to path in the Push() method.)

    1. Generics allow you to author algorithms and patterns, and reuse the code for differernt datat types.

    2. Generics facilitate increased type safety , preventing data types other than those explicitly intended by the members within the parameterized class.
      In Listing 11.7, the parameterized stack class restricts you to the Cell data type when using Stack. (For example, the statement path.Push(“garbage”) produces a compile-time error indicating that there is no overloaded method for System.Collections.Generic.Stack.Push(T) that can work with the string, because it cannot be converted to a Cell.)

    public void Sketch()
    {
    Stack<Cell> path; // Generic variable declaration
    path = new Stack<Cell>(); // Generic object instantiation

    ...
    }

    public class Stack<T>
    {
    private T[] _Items;

    public void Push(T data)
    {
    ...
    }

    public T Pop()
    {
    ...
    }
    }
    1. Compile-time type checking reduces the likelihood of InvalidCastException type errors at runtime.

    2. Using value types with generic class members no longer causes a boxing conversion to object. (For example, path.Pop() and path.Push() do not require an item to be boxed when added or unboxed when removed.)

    3. Performance improves because casting from an object is no longer required, thus eliminating a type check operation. Also, performance improves because boxing is no longer necessary for value types.

    4. Generics reduce memory consumption by avoiding boxing and thus consuming less memory on the heap.

    5. Generics in C# reduce code bloat. Generic types retain the benefits of specific class versions, without the overhead. (For example, it is no longer necessary to define a class such as CellStack.)

    6. Code becomes more readable because of fewer casting checks and because of the need for fewer type-specific implementations.

    7. Editors that assist coding via some type of IntelliSense® work directly with return parameters from generic classes. There is no need to cast the return data for IntelliSense to work.

    At their core, generics offer the ability to code pattern implementations and then reuse those implementations wherever the patterns appear. Patterns describe problems that occur repeatedly within code, and templates provide a single implementation for these repeating patterns.

    Type Parameter Naming Guidelines

    DO choose meaningful names for type parameters and prefix the name with “T”.

    CONSIDER indicating a constraint in the name of a type parameter.

    Generic Interfaces and Structs

    interface IPair<T>
    {
    T First { get; set; }
    T Second { get; set; }
    }

    public struct Pair<T>: IPair<T>
    {
    public T First
    {
    get
    {
    return _First;
    }
    set
    {
    _First = value;
    }
    }
    private T _First;

    public T Second
    {
    get
    {
    return _Second;
    }
    set
    {
    _Second = value;
    }
    }
    private T _Second;
    }

    AVOID implementing multiple constructions of the same generic interface in one type.

    Defining a Constructor and a Finalizer

    Perhaps surprisingly, the constructors (and finalizer) of a generic class or struct do not require type parameters.

    public struct Pair<T>: IPair<T>
    {
    public Pair(T first, T second)
    {

    _First = first;
    _Second = second;
    }


    public T First
    {
    get{ return _First; }
    set{ _First = value; }
    }
    private T _First;

    public T Second
    {
    get{ return _Second; }
    set{ _Second = value; }
    }
    private T _Second;

    Specifying a Default Value

    public struct Pair<T>: IPair<T>
    {
    public Pair(T first)
    {

    _First = first;
    _Second = default(T);

    }

    // ...
    }

    Multiple Type Parameters

    interface IPair<TFirst, TSecond>
    {
    TFirst First { get; set; }
    TSecond Second { get; set; }
    }

    public struct Pair<TFirst, TSecond>: IPair<TFirst, TSecond>
    {
    public Pair(TFirst first, TSecond second)
    {
    _First = first;
    _Second = second;
    }

    public TFirst First
    {
    get{ return _First; }
    set{ _First = value; }
    }
    private TFirst _First;

    public TSecond Second
    {
    get{ return _Second; }
    set{ _Second = value; }
    }
    private TSecond _Second;
    }

    Pair<int, string> historicalEvent = new Pair<int, string>(1914, "Shackleton leaves for South Pole on ship Endurance");
    Console.WriteLine("{0}: {1}", historicalEvent.First, historicalEvent.Second);

    The number of type parameters, the arity, uniquely distinguishes the class from others of the same name.

    Therefore, it is possible to define both Pair and Pair within the same namespace because of the arity variation.

    DO place multiple generic classes into a single file if they only differ by the number of generic parameters.

    Nested Generic Types

    Type parameters on a containing generic type will “cascade” down to any nested types automatically.

    If the containing type declares a type parameter T, for example, all nested types will also be generic and type parameter T will be available on the nested type as well.

    If the nested type includes its own type parameter named T, this will hide the type parameter within the containing type and any reference to T in the nested type will refer to the nested T type parameter.

    class Container<T, U>
    {
    // Nested classes inherit type parameters.
    // Reusing a type parameter name will cause
    // a warning.
    class Nested<U>
    {
    void Method(T param0, U param1)

    {
    }
    }
    }

    The rule is simply that a type parameter is available anywhere within the body of the type that declares it.

    AVOID shadowing a type parameter of an outer type with an identically named type parameter of a nested type.

    Generics with constraints

    A constraint declares the characteristics that the generic type requires of the type argument supplied for each type parameter.

    You declare a constraint using the where keyword, followed by a parameter-requirements pair, where the parameter must be one of those declared in the generic type and the requirements describe the class or interfaces to which the type argument must be convertible, the presence of a default constructor, or a reference/value type restriction.

    where T : iInterface, new()

    Interface Constraints

    public class BinaryTree<T>
    where T: System.IComparable<T>
    public class BinaryTree<T>
    where T: System.IComparable<T>

    {
    ...
    public Pair<BinaryTree<T>> SubItems
    {
    get{ return _SubItems; }
    set
    {
    IComparable<T> first;
    // Notice that the cast can now be eliminated.
    first = value.First.Item;

    if (first.CompareTo(value.Second.Item) < 0)

    {
    // first is less than second
    ...
    }
    else
    {
    // second is less than or equal to first.
    ...
    }
    _SubItems = value;
    }
    }
    private Pair<BinaryTree<T>> _SubItems;
    }

    Class Type Constraints

    public class EntityDictionary<TKey, TValue>
    : System.Collections.Generic.Dictionary<TKey, TValue>
    where TValue : EntityBase
    {
    ...
    }

    Class type constraints must appear before any interface type constraints (just as the base class must appear before implemented interfaces in a class declaration).

    Multiple base class constraints are not allowed since it is not possible to derive from multiple unrelated classes.

    Similarly, base class constraints cannot specify sealed classes or nonclass types.

    Certain “special” types are not legal as class type constraints.

    Struct/Class Constraints

    class constraint restricts it to reference types. e.g. any class, interface, delegate, or array type. struct constraint - Nullable value types do not satisfy the constraint.

    Why?

    Nullable value types are implemented as the generic type Nullable, which itself applies the struct constraint to T. If nullable value types satisfied that constraint, it would be possible to define the nonsense type Nullable>. A doubly nullable integer is confusing to the point of being meaningless. (As expected, the shorthand syntax int?? is also disallowed.)

    Multiple Constraints

    public class EntityDictionary<TKey, TValue>
    : Dictionary<TKey, TValue>
    where TKey : IComparable<TKey>, IFormattable
    where TValue : EntityBase
    {
    ...
    }

    When specifying multiple constraints on one type parameter, an AND relationship is assumed.

    If a type C is supplied as the type argument for TKey, C must implement IComparable and IFormattable, for example.

    Constructor Constraints

    public class EntityBase<TKey>
    {
    public TKey Key
    {
    get{ return _Key; }
    set{ _Key = value; }
    }
    private TKey _Key;
    }

    public class EntityDictionary<TKey, TValue> :
    Dictionary<TKey, TValue>
    where TKey: IComparable<TKey>, IFormattable
    where TValue : EntityBase<TKey>, new()

    {
    // ...

    public TValue MakeValue(TKey key)
    {
    TValue newEntity = new TValue();

    newEntity.Key = key;
    Add(newEntity.Key, newEntity);
    return newEntity;
    }

    // ...
    }

    Constructor constraint, and it requires the type argument corresponding to the constrained type parameter to have a public default constructor.

    Only the default constructor constraint is available.

    You cannot specify a constraint that ensures that the type argument supplied provides a constructor that takes formal parameters.

    Constraint Inheritance

    Neither generic type parameters nor their constraints are inherited by a derived class, because generic type parameters are not members.

    (Remember, class inheritance is the property that the derived class has all of the members of the base class.)

    It is a common practice to make new generic types that inherit from other generic types.

    Since the type parameters of the derived generic type are now the type arguments of the generic base class, the type parameters must have equal (or stronger) constraints as those on the base class.

    Confused? Consider Listing 11.27.

    Listing 11.27. Inherited Constraints Specified Explicitly

    class EntityBase<T> where T : IComparable<T>
    {
    // ...
    }

    class EntityBase
    {
    // ...
    public virtual void Method<U>(U u) where U : IComparable<U>
    {
    // ...
    }
    }

    class Order : EntityBase
    {
    public override void Method<T>(T t) // where T : IComparable<T>
    // Constraints may not be repeated on overriding
    // members

    {
    // ...
    }
    }
    // ERROR:
    // The type 'U' must be convertible to
    // 'System.IComparable<U>' in order to use it as parameter
    // 'T' in the generic type or method.
    class Entity<U> : EntityBase<U> where U : IComparable<U>
    {
    //...
    }

    But briefly, methods may also be generic and may also place constraints on the type arguments supplied for their type parameters.

    How, then, are constraints handled when a virtual generic method is inherited and overridden?

    In contrast to the situation with type parameters declared on a generic class, constraints on overriding virtual generic methods (or explicit interface) methods are inherited implicitly and may not be restated.

    Repeating Inherited Constraints on Virtual Members Is Prohibited

    In the generic class inheritance case, the type parameter on the derived class can be additionally constrained by adding not only the constraints on the base class (required), but also additional constraints as well.

    However, overriding virtual generic methods need to conform exactly to the constraints defined by the base class method.

    Additional constraints could break polymorphism, so they are not allowed and the type parameter constraints on the overriding method are implied.In

    Advanced Topic: Constraint Limitations

    Constraints are appropriately limited to avoid nonsensical code.

    1. Cannot combine a class type constraint with a struct or class constraint.

    2. Cannot specify constraints to restrict inheritance to special types such as object, arrays, System.ValueType, System.Enum (enum), System.Delegate, and System.MulticastDelegate.

    3. Operator Constraints Are Not Allowed

    You cannot constrain a type parameter to a type that implements a particular method or operator, except via interface type constraints (for methods) or class type constraints (for methods and operators).

    public abstract class MathEx<T>
    {
    public static T Add(T first, T second)
    {
    // Error: Operator '+' cannot be applied to
    // operands of type 'T' and 'T'.
    return first + second;
    }
    }

    More generally, there is no way to constrain a type to have a static method.

    1. OR Criteria Are Not Supported

    If you supply multiple interfaces or class constraints for a type parameter, the compiler always assumes an AND relationship between constraints.If

    There is no way to specify an OR relationship between constraints.

    Supporting this would prevent the compiler from resolving which method to call at compile time.

    1. Constraints of Type Delegate and Enum Are Not Valid

    Delegate types, array types, and enumerated types may not be used as class type constraints, because they are all effectively “sealed” types.

    Their base types, System.Delegate, System.MultiCastDelegate, System.Array, and System.Enum, may also not be used as constraints.

    public class Publisher<T>
    where T : System.Delegate
    {
    public event T Event;
    public void Publish()
    {
    if (Event != null)
    {
    Event(this, new EventArgs());
    }
    }
    }

    All delegate types are considered special classes that cannot be specified as type parameters.

    Doing so would prevent compile-time validation on the call to Event() because the signature of the event firing is unknown with the data types System.Delegate and System.MulticastDelegate.

    The same restriction occurs for any enum type.

    6.Constructor Constraints Are Allowed Only for Default Constructors

    There is no constraint to force the type argument to provide a constructor that takes other formal parameters.

    One way to circumvent this restriction is to supply a factory interface that includes a method for instantiating the type.

    The factory implementing the interface takes responsibility for instantiating the entity rather than the EntityDictionary itself

    public class EntityBase<TKey>
    {
    public EntityBase(TKey key)
    {
    Key = key;
    }

    public TKey Key
    {
    get { return _key; }
    set { _key = value; }
    }
    private TKey _key;
    }

    public class EntityDictionary<TKey, TValue, TFactory> :
    Dictionary<TKey, TValue>
    where TKey : IComparable<TKey>, IFormattable
    where TValue : EntityBase<TKey>
    where TFactory : IEntityFactory<TKey, TValue>, new()
    {
    ...
    public TValue New(TKey key)
    {
    TFactory factory = new TFactory();
    TValue newEntity = factory.CreateNew(key);

    Add(newEntity.Key, newEntity);
    return newEntity;
    }
    ...
    }

    public interface IEntityFactory<TKey, TValue>
    {
    TValue CreateNew(TKey key);
    }

    public class Order : EntityBase<Guid>
    {
    public Order(Guid key) :
    base(key)
    {
    // ...
    }
    }

    public class OrderFactory : IEntityFactory<Guid, Order>
    {
    public Order CreateNew(Guid key)
    {
    return new Order(key);
    }
    }

    Generic Methods

    public static class MathEx
    {
    public static T Max<T>(T first, params T[] values)
    where T : IComparable<T>
    {
    T maximum = first;
    foreach (T item in values)
    {
    if (item.CompareTo(maximum) > 0)
    {
    maximum = item;
    }
    }
    return maximum;
    }



    public static T Min<T>(T first, params T[] values)
    where T : IComparable<T>
    {
    T minimum = first;

    foreach (T item in values)
    {
    if (item.CompareTo(minimum) < 0)
    {
    minimum = item;
    }
    }
    return minimum;
    }
    }

    Generic Method Type Inference

    In cases where method type inference is still not sophisticated enough to deduce the type arguments, you can resolve the error by either inserting casts on the arguments that clarify to the compiler the argument types that should be used in the inferences, or giving up on type inferencing and including the type arguments explicitly.

    Also note that when making its inferences, the method type inference algorithm considers only the arguments, the arguments’ types, and the formal parameter types of the generic method.

    Other factors that could in practice be used in the analysis—such as the return type of the generic method, the type of the variable that the method’s returned value is being assigned to, or the constraints on the method’s generic type parameters—are not considered at all by the method type inference algorithm.

    public static class MathEx
    {
    public static T Max<T>(T first, params T[] values)
    where T : IComparable<T>
    {
    T maximum = first;
    foreach (T item in values)
    {
    if (item.CompareTo(maximum) > 0)
    {
    maximum = item;
    }
    }
    return maximum;
    }

    public static T Max<T, V>(T first, V second, V[] seconds, params T[] values)
    where T : IComparable<T>
    where V : IComparable<V>
    {
    T maximum = first;
    foreach (T item in values)
    {
    if (item.CompareTo(maximum) > 0)
    {
    maximum = item;
    }
    }
    return maximum;
    }

    public static T Min<T>(T first, params T[] values)
    where T : IComparable<T>
    {
    T minimum = first;

    foreach (T item in values)
    {
    if (item.CompareTo(minimum) < 0)
    {
    minimum = item;
    }
    }
    return minimum;
    }

    static void Main()
    {

    Console.WriteLine(MathEx.Max<int>(7, 490));

    Console.WriteLine(MathEx.Min<string>("R.O.U.S.", "Fireswamp"));

    Console.WriteLine(MathEx.Max(7, 490)); // No type arguments!

    Console.WriteLine(MathEx.Min("R.O.U.S'", "Fireswamp"));
    }
    }

    Specifying Constraints

    Type parameters of generic methods may be constrained in exactly the same way that type parameters of generic types are constrained.Constraints

    public static void Show<T>(BinaryTree<T> tree, int indent) where T :  IComparable<T>
    {
    ...
    }

    Notice that the Show implementation itself does not directly use any member of the IComparable interface, so you might wonder why the constraint is required. Recall, however, that the BinaryTree class did require this

    public class BinaryTree<T>
    where T: System.IComparable<T>

    {
    ...
    }

    Because the BinaryTree class requires this constraint on its T, and because Show uses its T as a type argument corresponding to a constrained type parameter, Show needs to ensure that the class’s type parameter’s constraint is met on its method type argument.

    Advanced Topic: Casting insdie a Generic Method

    Sometimes you should be wary of using generics

    Advanced Topic: Casting inside a Generic Method

    Sometimes you should be wary of using generics—for instance, when using them specifically to bury a cast operation. Consider the following method, which converts a stream into an object of a given type:

    public static T Deserialize<T>(
    Stream stream, IFormatter formatter)
    {
    return (T)formatter.Deserialize(stream);
    }

    The formatter is responsible for removing data from the stream and converting it to an object. The Deserialize() call on the formatter returns data of type object. A call to use the generic version of Deserialize() looks something like this:

    string greeting =
    Deserialization.Deserialize<string>(stream, formatter);

    The problem with this code is that to the caller of the method, Deserialize() appears to be type-safe. However, a cast operation is still performed on behalf of the caller, as in the case of the nongeneric equivalent shown here:

    string greeting =
    (string)Deserialization.Deserialize(stream, formatter);

    The cast could fail at runtime; the method might not be as type-safe as it appears. The Deserialize method is generic solely so that it can hide the existence of the cast from the caller, which seems dangerously deceptive. It might be better for the method to be nongeneric and return object, making the caller aware that it is not type-safe. Developers should use care when casting in generic methods if there are no constraints to verify cast validity.

    Guidelines

    AVOID misleading the caller with generic methods that are not as type-safe as they appear.

    Covariance and Contravariance

    A common question asked by new users of generic types is why an expression of type List may not be assigned to a variable of type List—if a string may be converted to type object, surely a list of strings is similarly compatible with a list of objects. But this is not, generally speaking, either type-safe or legal.

    If you declare two variables with different type parameters using the same generic class, the variables are not type-compatible even if they are assigning from a more specific type to a more generic type—in other words, they are not covariant.

    Covariant is a technical term from category theory, but the idea is straightforward: Suppose two types X and Y have a special relationship, namely that every value of the type X may be converted to the type Y. If the types I and I always also have that same special relationship, we say, “I is covariant in T.” When dealing with simple generic types with only one type parameter, the type parameter can be understood and we simply say, “I is covariant.” The conversion from I to I is called a covariant conversion.

    For example, instances of a generic class, Pair and Pair, are not type-compatible even when the type arguments are themselves compatible. In other words, the compiler prevents converting (implicitly or explicitly) Pair to Pair, even though Contact derives from PdaItem. Similarly, converting Pair to the interface type IPair will also fail.For

    // ...
    // Error: Cannot convert type ...
    Pair<PdaItem> pair = (Pair<PdaItem>) new Pair<Contact>();
    IPair<PdaItem> duple = (IPair<PdaItem>) new Pair<Contact>();
    //...
    Contact contact1 = new Contact("Princess Buttercup"),
    Contact contact2 = new Contact("Inigo Montoya");
    Pair<Contact> contacts = new Pair<Contact>(contact1, contact2);

    // This gives an error: Cannot convert type ...
    // But suppose it did not.
    // IPair<PdaItem> pdaPair = (IPair<PdaItem>) contacts;
    // This is perfectly legal, but not type safe.
    // pdaPair.First = new Address("123 Sesame Street");
    ...

    An IPair can contain an address, but the object is really a Pair that can only contain contacts, not addresses.

    Type safety is completely violated if unrestricted generic covariance is allowed

    Now it should also be clear why a list of strings may not be used as a list of objects; you cannot insert an integer into a list of strings, but you can insert an integer into a list of objects, so it must be illegal to cast a list of strings to a list of objects so that this error can be prevented by the compiler.Contact

    out

    Support for safe covariance was added to C# 4. To indicate that a generic interface is intended to be covariant in one of its type parameters, declare the type parameter with the out type parameter modifier.

    interface IReadOnlyPair<out T>
    {
    T First { get; }
    T Second { get; }
    }

    There are a number of important restrictions on covariant conversions.

    *Only generic interfaces and generic delegates (described in Chapter 12) may be covariant. Generic classes and structs are never covariant.

    *The varying type arguments of both the “source” and “target” generic types must be reference types, not value types. That is, an IReadOnlyPair may be converted covariantly to IReadOnlyPair because both string and IReadOnlyPair are reference types. An IReadOnlyPair may not be converted to IReadOnlyPair because int is not a reference type.

    *The interface or delegate must be declared as supporting covariance, and the compiler must be able to verify that the annotated type parameters are in fact used in only “output” positions.IReadOnlyPair

    Generic Internals

    Given the discussions in earlier chapters about the prevalence of objects within the CLI type system, it is no surprise that generics are also objects.

    In fact, the type parameter on a generic class becomes metadata that the runtime uses to build appropriate classes when needed. Generics, therefore, support inheritance, polymorphism, and encapsulation.

    With generics, you can define methods, properties, fields, classes, interfaces, and delegates.

    To achieve this, generics require support from the underlying runtime.

    So, the addition of generics to the C# language is a feature of both the compiler and the platform.

    To avoid boxing, for example, the implementation of generics is different for value-based type parameters than for generics with reference type parameters.

    .class private auto ansi beforefieldinit
        Stack'1<([mscorlib]System.IComparable)T>
        extends [mscorlib]System.Object
    {
        field private !0[ ] items
    }

    The first notable item is the ‘1 that appears following Stack on the second line. That number is the arity. It declares the number of type parameters that the generic class will require type arguments for. A declaration such as EntityDictionary would have an arity of 2.

    The second line of the generated CIL shows the constraints imposed upon the class. The T type parameter is decorated with an interface declaration for the IComparable constraint.

    If you continue looking through the CIL, you will find that the item’s array declaration of type T is altered to contain a type parameter using “exclamation point notation,” used in the generics-capable version of the CIL.

    The exclamation point denotes the presence of the first type parameter specified for the class.

    Beyond the inclusion of the arity and type parameter in the class header and the type parameter denoted with exclamation points in code, there is little difference between the CIL generated for a generic class and the CIL generated for a nongeneric class.

    Instantiating Generics Based on Value Types

    When a generic type is first constructed with a value type as a type parameter, the runtime creates a specialized generic type with the supplied type parameter(s) placed appropriately in the CIL.

    Therefore, the runtime creates new specialized generic types for each new parameter value type.

    You declare two instances of a Stack, both using the code already generated by the runtime for a Stack.

    Stack<int> stackOne = new Stack<int>();
    Stack<int> stackTwo = new Stack<int>();

    If later in the code, you create another Stack with a different value type substituted for the type parameter (such as a long or a user-defined struct) the runtime generates another version of the generic type.

    The benefit of specialized value type classes is better performance. Furthermore, the code is able to avoid conversions and boxing because each specialized generic class “natively” contains the value type.

    Instantiating Generics Based on Reference Types

    The first time a generic type is constructed with a reference type, the runtime creates a specialized generic type with object references substituted for type parameters in the CIL, not a specialized generic type based on the type argument.

    Each subsequent time a constructed type is instantiated with a reference type parameter, the runtime reuses the previously generated version of the generic type, even if the reference type is different from the first reference type.

    This implementation of generics greatly reduces code bloat by reducing to one the number of specialized classes created by the compiler for generic classes of reference types.

    Even though the runtime uses the same internal generic type definition when the type parameter on a generic reference type varies, this behavior is superseded if the type parameter is a value type. Dictionary, Dictionary, and Dictionary will require new internal type definitions, for example.

    Static Class with Generics

    “This” and extension method

    nullable value

    Fakes – A Fake is an object that has some sort of actual working mechanism inside that returns a predictable result, but doesn’t implement the actual production logic.

    Stubs – A Stub is an object that will return a specific result based on a specific set of input. If I tell my stub to return “John Doe” whenever I ask it for the person with ID number 42, than that’s what it will do. However when I ask a stub for a person with an ID number 41, it doesn’t know what to do. Depending on which mocking framework I’m using the stub will either throw an exception or just return a null object. A stub may “remember” some information around how it was called, such as how many times it was called and with what data.

    Mocks – A Mock is a much more sophisticated version of a Stub. It will still return values like a stub, but it can also be programmed with expectations in terms of how many times each method should be called, in which order and with what data. Mocks provide features that ensure that our code under test is using it’s dependencies in a very specific way.

    Spy – A Spy is type of mock that takes an object and instead of creating a new mock object replaces the methods that the tester wants to mock. Spies are great for testing legacy (non TDD code) but you must be very careful as missing something that should have been mocked can have disastrous results

    Dummy – A Dummy is an object that can be passed as a replacement for another object, but is never used. Dummies are essentially placeholders.

    -Babeljs

    -gulp-babel https://github.com/babel/gulp-babel

    -Babelify - Browserify transform for Babelify
    https://github.com/babel/babelify

    -Browserify require(‘modules’) in the browser by bundling up all of your dependencies
    http://browserify.org/

    Lint and Style Check

    -Jshint
    -Jscs
    -ESLint a pluggable linting utility for JavaScript
    http://eslint.org/

    ES6 Modules
    http://www.2ality.com/2014/09/es6-modules-final.html

    ES6 Tools - an aggregation of tooling for using ES6 today

    Understanding ES6

    https://leanpub.com/understandinges6/read

    Exploring ES6

    http://exploringjs.com/es6/