Category Archives: JS

Must-Watch JavaScript

This is a collection of well-received talks about JavaScript, covering topics such as ES6, JavaScript frameworks, client-side apps, mobile integration, JavaScript performance, tooling, leveling up, and more.

Like CSS? Check out Must-Watch CSS! For other great lists check out @sindresorhus‘s curated list of awesome lists.

2018

  1. In the Loop: Jake Archibald, JSConf.Asia 35:11
  2. 10 Things I Regret About Node.js: Ryan Dahl, JSConf.EU 26:41
  3. Deep Learning in JS: Ashi Krishnan, JSConf.EU 31:30

2017

  1. Immutable Data Structures for Functional JS: Anjana Vakil, JSConf.EU 26:32
  2. JavaScript Engines – How Do They Even?: Franziska Hinkelmann, JSConf.EU 25:13
  3. Async + Await: Wes Bos, dotJS 15:51
  4. Advanced Async and Concurrency Patterns in JavaScript: Kyle Simpson, js.la Meetup 39:42
  5. The Browser Hackers Guide to Instantly Loading Everything: Addy Osmani, JSConf.EU 28:09

2016

  1. The Rise of Async JavaScript: Jeremy Fairbank, FluentConf 28:58
  2. Reasonable JavaScript: Preethi Kasireddy, Nodevember 50:12
  3. Learning Functional Programming with JavaScript: Anjana Vakil, JSUnconf 29:56
  4. Choosing a JavaScript Framework: Rob Eisenberg, NDC Oslo 1:01:13
  5. The Myth of The “Real JavaScript Developer”: Brenna O’Brien, Front-Trends 27:05
  6. An Angular 2 Force Awakens: John Papa, ng-conf 20:39
  7. React.js for TV UIs: Steve McGuire, Netflix JavaScript Talks 35:02
  8. The Hitchhiker’s Guide to All Things Memory in JavaScript: Safia Abdalla, JSConf Budapest 26:16
  9. SVG and GreenSock for Complex Animation: Sarah Drasner, ForwardJS Summit 40:16

2015

  1. JavaScript in 2015: Glen Maddern, (screencast) 10:32
  2. Angular + React = Speed: Dave Smith, ng-conf 19:26
  3. Parallelism Experiments in JavaScript: Naveed Ihsanullah, JSConf.US 32:39
  4. Eliminate JavaScript Code Smells: Elijah Manor, FluentConf 29:15
  5. Pocket-Sized JS: Henrik Joreteg, dotJS 18:44
  6. What the… JavaScript?: Kyle Simpson, ForwardJS 38:16
  7. Real World jQuery: Ben Foxall, jQuery UK 26:45
  8. JavaScript State of the Union: Geoff Schmidt, Meteor Devshop SF 48:47
  9. Dirty Performance Secrets of HTML5: Andreas Gal, FluentConf 14:15
  10. You Should Use <Insert Library/Framework>, It’s the Bestestest!: Paul Lewis, ffconf 33:31
  11. Async Programming in ES7: Jafar Husain, JSConf.US 35:56
  12. Live React: Hot Reloading with Time Travel: Dan Abramov, ReactEurope 30:40
  13. JavaScript Transformation: Sebastian McKenzie, JSConf.US 20:23
  14. Node.js at Netflix: Kim Trott, Node.js Interactive 25:17
  15. If You Wish to Learn ES6/2015 From Scratch, You Must First Invent the Universe: Ashley Williams, JSConf.US 25:48

2014

  1. Enemy of the State: Amy Palamountain,Forward JS 32:40
  2. Mary Live-Codes a JavaScript Game from Scratch: Mary Rose Cook, Front-Trends 32:16
  3. Unorthodox Performance: John-David Dalton, ForwardJS 43:39
  4. What the Heck Is the Event Loop Anyway?: Philip Roberts, JSConf.EU 26:53
  5. Building Isomorphic Apps: Spike Brehm, JSConf.Asia 45:01
  6. JavaScript for Everybody: Marcy Sutton, JSConf.EU 28:59
  7. JavaScript ♥ Unicode: Mathias Bynens, JSConf.EU 25:41
  8. Using AngularJS to Create iPhone & Android Applications with PhoneGap: Daniel Zen, ng-conf 21:34
  9. Virtual Machines, JavaScript and Assembler: Scott Hanselman, FluentConf 25:56
  10. User Interface Algorithms: Mark DiMarco, JSConf.US 27:41
  11. End to End Angular Testing with Protractor: Julie Ralph, ng-conf 18:46
  12. Async JavaScript at Netflix: Jafar Husain, Netflix JavaScript Talks 28:38
  13. Building Realtime Apps with Firebase and Angular: Anant Narayanan, ng-conf 21:08

2013

  1. A JavaScript Web App Deconstructed: Alex MacCaw, JSConf.Asia 36:24
  2. JavaScript in Your Native Mobile Apps: Allen Pike, JSConf.EU 25:47
  3. JavaScript Masterclass: Angelina Fabbro, JSConf.US 22:33
  4. A Comparison of the Two-Way Binding in AngularJS, EmberJS and KnockoutJS: Marius Gundersen, JSConf.EU 19:16
  5. Hacker Way: Rethinking Web App Development at Facebook: Tom Occhino, Jing Chen, and Pete Hunt, F8 44:35
  6. Promises and Generators: Control Flow Utopia: Forbes Lindesay, JSConf.EU 31:26
  7. How to Rewrite Your JS App (at Least) 10 Times: Garann Means, Fronteers 47:45
  8. Front-End Development in Node.js: Raquel Vélez, jQuery Conference Portland 34:01
  9. Front-End Tools for the Young Developer: Christian Vuerings, SF HTML5 User Group 14:16
  10. Rethinking Best Practices: Pete Hunt, JSConf.Asia 40:57
  11. Righteous Javascript, Dude!: Zach Bruggerman, Cascadia JS 18:15
  12. Transitioning Groupon to NodeJS: Sean McCullough, EmpireJS 28:23
  13. Building Modular Web Applications: How To Build a Good Component: Angelina Fabbro, jQuery Conference Portland 35:02
  14. Making JS More Learnable: Pamela Fox, dotJS 28:46
  15. The Web Experience in the Autistic Spectrum: Natalia Berdys, JSConf.EU 30:37
  16. Return of Inspector Web: Web Components a Year Later: Angelina Fabbro, Fronteers 49:44
  17. Develop High Performance Sites and Apps with JavaScript and HTML5: Dr. Doris Chen, HTML5DevConf Meetup 1:01:39
  18. Building Reflow: Kristofer Joseph, BackboneConf 45:41
  19. Levelling Up in AngularJS: Alicia Liu, HTML5DevConf 40:31

2012

  1. A Novel, Efficient Approach to JavaScript Loading: Malte Ubl and John Hjelmstad, JSConf.EU 26:36
  2. To Hell with jQuery: Karolina Szczur, JSConf.EU 20:00
  3. Is Node.js Better?: Brian Ford, JSConf.US 41:42
  4. Inspector Web and the Mystery of the Shadow DOM: Angelina Fabbro, JSConfEU 28:42
  5. Maintainable JavaScript: Nicholas Zakas, FluentConf 47:04
  6. Client Side Internationalization: Alex Sexton, JSConf.EU 24:08

from:https://github.com/AllThingsSmitty/must-watch-javascript

深度解析JavaScript的this关键字

这篇文章通过简单的术语和一个真实的例子解释了 this 是什么以及为什么说它很有用。

你的 this

我发现,很多教程在解释 JavaScript 的 this 时,通常会假设你拥有 Java、C++ 或 Python 等面向对象编程语言的背景。这篇文章主要面向那些对 this 没有先入之见的人。我将尝试解释什么是 this 以及为什么它很有用。

或许你迟迟不肯深入探究 this,因为它看起来很奇怪,让你心生畏惧。你之所以使用它,有可能仅仅是因为 StackOverflow 说你需要在 React 用它来完成一些事情。

在我们深入了解它的真正含义以及为什么要使用它之前,我们首先需要了解函数式编程和面向对象编程之间的区别。

函数式编程与面向对象编程

你可能知道也可能不知道,JavaScript 具有函数和面向对象的构造,你可以选择关注其中一个或两者兼而有之。

在我的 JavaScript 之旅的早期,我一方面拥抱函数式编程,一方面像避免瘟疫一样排斥面向对象编程。我对面向对象关键字 this 不甚了解。其中的一个原因是我不明白它存在的必要性。在我看来,完全可以不依赖 this 就可以完成所有的事情。

在某种程度上,我的看法是对的。

你可能只关注其中一种范式而从来不去了解另外一种,作为一名 JavaScript 开发者,你的局限性就体现在这里。为了说明函数式编程和面向对象编程之间的差别,我将使用一组 Facebook 好友数据作为示例。

假设你正在构建一个用户登录 Facebook 的 Web 应用,在登录后显示一些 Facebook 好友的数据。你需要访问 Facebook 端点来获取好友的数据,可能包含一些信息,例如 firstName、lastName、username、numFriends、friendData、birthday 和 lastTenPosts。

const data = [
  {
    firstName: 'Bob',
    lastName: 'Ross',
    username: 'bob.ross',    
    numFriends: 125,
    birthday: '2/23/1985',
    lastTenPosts: ['What a nice day', 'I love Kanye West', ...],
  },
  ...
]

你从(臆造的)Facebook API 获得上面的数据。现在,你需要转换它们,让它们符合项目需要的格式。假设你要为每个用户的朋友显示以下内容:

  • 它们的名字,格式为$ {firstName} $ {lastName}
  • 三篇随机的帖子;
  • 从他们生日起到现在的天数。
函数式方法

如果使用函数式方法,就是将整个数组或数组的每个元素传给一个返回所需操作数据的函数:

const fullNames = getFullNames(data)
// ['Ross, Bob', 'Smith, Joanna', ...]

你从原始数据开始(来自 Facebook API),为了将它们转换为对你有用的数据,你将数据传给一个函数,这个函数将输出你可以在应用程序中显示给用户的数据。

你也可以通过类似的方式获取三个随机帖子并计算朋友生日至今的天数。

函数式方法就是指接受原始数据,将数据传给一个或多个函数,并输出对你有用的数据。

面向对象方法

对于那些刚接触编程和学习 JavaScript 的人来说,面向对象方法可能会更难掌握。面向对象是指你将每个朋友转换为对象,对象包含了用于生成你所需内容的一切。

你可以创建包含 fullName 属性的对象,以及 getThreeRandomPosts 和 getDaysUntilBirthday 函数。

function initializeFriend(data) {
  return {
    fullName: `${data.firstName} ${data.lastName}`,
    getThreeRandomPosts: function() {
      // get three random posts from data.lastTenPosts
    },
    getDaysUntilBirthday: function() {
      // use data.birthday to get the num days until birthday
    }
  };
}
const objectFriends = data.map(initializeFriend)
objectFriends[0].getThreeRandomPosts() 
// Gets three of Bob Ross's posts

面向对象方法是为你的数据创建对象,这些对象包含了状态和用于生成对你和你的项目有用的数据的信息。

这与 this 有什么关系?

你可能没有想过会写出类似 initializeFriend 这样的东西,你可能会认为它很有用。你可能还会注意到,它其实并非真正的面向对象。

getThreeRandomPosts 或 getDaysUntilBirthday 方法之所以有用,主要是因为闭包。因为使用了闭包,所以在 initializeFriend 返回之后,它们仍然可以访问 data。

假设你写了另一个方法,叫 greeting。请注意,在 JavaScript 中,方法只是对象的一个属性,这个属性的值是一个函数。我们希望 greeting 可以做这些事情:

function initializeFriend(data) {
  return {
    fullName: `${data.firstName} ${data.lastName}`,
    getThreeRandomPosts: function() {
      // get three random posts from data.lastTenPosts
    },
    getDaysUntilBirthday: function() {
      // use data.birthday to get the num days until birthday
    },
    greeting: function() {
      return `Hello, this is ${fullName}'s data!`
    }
  };
}

这样可以吗?

不行!

新创建对象的所有东西都可以访问 initializeFriend 的变量,但对象本身的属性或方法不行。当然,你可能会问:

难道你不能用 data.firstName 和 data.lastName 来返回 greeting 吗?

当然可以。但如果我们还想在 greeting 中包含朋友生日至今的天数,该怎么办?我们必须以某种方式从 greeting 中调用 getDaysUntilBirthday 方法。

是时候让 this 上场了!

那么,this 是什么

在不同的情况下,this 代表的东西也不一样。默认情况下,this 指向全局对象(在浏览器中,就是 window 对象)。但光知道这点对我们并没有太大帮助,对我来说有用的是 this 的这条规则:

如果 this 被用在一个对象的方法中,并且这个方法在对象的上下文中调用,那么 this 就指向这个对象本身。

你会问:“在对象的上下文中调用……这又是什么意思”?

别担心,稍后我们会解释这个。

因此,如果我们想在 greeting 中调用 getDaysUntilBirthday,可以直接调用 this.getDaysUntilBirthday,因为在这种情况下,this 指向对象本身。

注意:不要在全局作用域或在另一个函数作用域内的常规 ole 函数中使用 this!this 是一个面向对象的构造。因此,它只在对象(或类)的上下文中有意义!

让我们重构 initializeFriend,让它使用 this:

function initializeFriend(data) {
  return {
    lastTenPosts: data.lastTenPosts,
    birthday: data.birthday,    
    fullName: `${data.firstName} ${data.lastName}`,
    getThreeRandomPosts: function() {
      // get three random posts from this.lastTenPosts
    },
    getDaysUntilBirthday: function() {
      // use this.birthday to get the num days until birthday
    },
    greeting: function() {
      const numDays = this.getDaysUntilBirthday()      
      return `Hello, this is ${this.fullName}'s data! It is ${numDays} until ${this.fullName}'s birthday!`
    }
  };
}

现在,在执行完 intializeFriend 后,这个对象的所有东西都限定在对象本身。我们的方法不再依赖于闭包,它们将使用对象本身包含的信息。

这是 this 的一种使用方式,现在回到之前的问题:为什么说 this 因上下文不同而不同?

有时候,你希望 this 可以指向不一样的东西,比如事件处理程序就是一个很好的例子。假设我们想在用户点击链接时打开朋友的 Facebook 页面。我们可能会在对象中添加一个 onClick 方法:

function initializeFriend(data) {
  return {
    lastTenPosts: data.lastTenPosts,
    birthday: data.birthday,
    username: data.username,    
    fullName: `${data.firstName} ${data.lastName}`,
    getThreeRandomPosts: function() {
      // get three random posts from this.lastTenPosts
    },
    getDaysUntilBirthday: function() {
      // use this.birthday to get the num days until birthday
    },
    greeting: function() {
      const numDays = this.getDaysUntilBirthday()      
      return `Hello, this is ${this.fullName}'s data! It is ${numDays} until ${this.fullName}'s birthday!`
    },
    onFriendClick: function() {
      window.open(`https://facebook.com/${this.username}`)
    }
  };
}

请注意,我们向对象添加了 username,让 onFriendClick 可以访问它,这样我们就可以在新窗口中打开朋友的 Facebook 页面。现在编写 HTML:

<button id="Bob_Ross">
  <!-- A bunch of info associated with Bob Ross -->
</button> 

然后是 JavaScript:

const bobRossObj = initializeFriend(data[0])
const bobRossDOMEl = document.getElementById('Bob_Ross')
bobRossDOMEl.addEventListener("onclick", bobRossObj.onFriendClick)

在上面的代码中,我们为 Bob Ross 创建了一个对象。我们获得与 Bob Ross 相关的 DOM 元素。现在我们想要调用 onFriendClick 方法来打开 Bob 的 Facebook 页面。应该没问题吧?

不行!

什么地方出了问题?

请注意,我们为 onclick 处理程序选择的函数是 bobRossObj.onFriendClick。看到问题所在了吗?如果我们像这样重写它:

bobRossDOMEl.addEventListener("onclick", function() {
  window.open(`https://facebook.com/${this.username}`)
})

现在你看到问题所在了吗?当我们将 onclick 处理程序指定为 bobRossObj.onFriendClick 时,我们实际上是将 bobRossObj.onFriendClick 的函数作为参数传给了处理程序。它不再“属于”bobRossObj,也就是说 this 不再指向 bobRossObj。这个时候 this 实际上指向的是全局对象,所以 this.username 是 undefined 的。

是时候让 bind 上场了!

显式绑定 this

我们需要做的是将 this 显式绑定到 bobRossObj。我们可以使用 bind 来实现:

const bobRossObj = initializeFriend(data[0])
const bobRossDOMEl = document.getElementById('Bob_Ross')
bobRossObj.onFriendClick = bobRossObj.onFriendClick.bind(bobRossObj)
bobRossDOMEl.addEventListener("onclick", bobRossObj.onFriendClick)

之前,this 是基于默认规则设置的。通过使用 bind,我们在 bobRossObj.onFriendClick 中将 this 的值显式设置为对象本身,也就是 bobRossObj。

到目前为止,我们已经知道为什么 this 很有用以及为什么有时候需要显式绑定 this。接下来我们要讨论的最后一个主题是箭头函数。

箭头函数

你可能已经注意到,箭头函数像是一个时髦的新事物。人们似乎很喜欢它们,因为它们简洁而优雅。你可能已经知道它们与一般函数略有不同,但不一定非常清楚这些区别究竟是什么。

或许箭头函数的不同之处在于:

在箭头函数内部,无论 this 处于什么位置,它指的都是相同的东西。

让我们用 initializeFriend 示例解释一下。假设我们想在 greeting 中添加一个辅助函数:

function initializeFriend(data) {
  return {
    lastTenPosts: data.lastTenPosts,
    birthday: data.birthday,
    username: data.username,    
    fullName: `${data.firstName} ${data.lastName}`,
    getThreeRandomPosts: function() {
      // get three random posts from this.lastTenPosts
    },
    getDaysUntilBirthday: function() {
      // use this.birthday to get the num days until birthday
    },
    greeting: function() {
      function getLastPost() {
        return this.lastTenPosts[0]
      }
      const lastPost = getLastPost()           
      return `Hello, this is ${this.fullName}'s data!
             ${this.fullName}'s last post was ${lastPost}.`
    },
    onFriendClick: function() {
      window.open(`https://facebook.com/${this.username}`)
    }
  };
}

这样可以吗?如果不行,要怎样修改才行?

这样当然是不行的。因为 getLastPost 不是在对象的上下文中调用的,所以 getLastPost 中的 this 会回退到默认规则,即指向全局对象。

“在对象的上下文中调用”可能是一个比较含糊的概念。要确定一个函数是否是在“对象的上下文中”被调用,最好的办法是看一下函数是如何被调用的,以及是否有对象“附加”在函数上。

让我们来看看执行 bobRossObj.onFriendClick() 时会发生什么:“找到 bobRossObj 对象的 onFriendClick 属性,调用分配给这个属性的函数”。

再让我们来看看执行 getLastPost() 时会发生什么:”调用一个叫作 getLastPost 的函数”。有没有注意到,这里并没有提及任何对象?

现在来测试一下。假设有一个叫作 functionCaller 的函数,它所做的事情就是调用其他函数:

functionCaller(fn) {
  fn()
}

如果我们这样做会怎样:functionCaller(bobRossObj.onFriendClick)?可不可以说 onFriendClick 是“在对象的上下文中”被调用的?this.username 的定义存在吗?

让我们来看一下:“找到 bobRossObj 对象的 onFriendClick 属性。找到这个属性的值(恰好是一个函数),将它传给 functionCaller,并命名为 fn。现在,执行名为 fn 的函数”。请注意,函数在被调用之前已经从 bobRossObj 对象中“分离”,因此不是“在对象 bobRossObj 的上下文中”调用,所以 this.username 是 undefined 的。

让箭头函数来救场:

function initializeFriend(data) {
  return {
    lastTenPosts: data.lastTenPosts,
    birthday: data.birthday,
    username: data.username,    
    fullName: `${data.firstName} ${data.lastName}`,
    getThreeRandomPosts: function() {
      // get three random posts from this.lastTenPosts
    },
    getDaysUntilBirthday: function() {
      // use this.birthday to get the num days until birthday
    },
    greeting: function() {
      const getLastPost = () => {
        return this.lastTenPosts[0]
      }
      const lastPost = getLastPost()           
      return `Hello, this is ${this.fullName}'s data!
             ${this.fullName}'s last post was ${lastPost}.`
    },
    onFriendClick: function() {
      window.open(`https://facebook.com/${this.username}`)
    }
  };
}

箭头函数是在 greeting 中声明的。我们知道,当我们在 greeting 中使用 this 时,它指向对象本身。因此,箭头函数中的 this 指向的对象就是我们想要的。

英文原文:

https://medium.freecodecamp.org/a-deep-dive-into-this-in-javascript-why-its-critical-to-writing-good-code-7dca7eb489e7

Overview of ECMAScript 6 features

Introduction

ECMAScript 6, also known as ECMAScript 2015, is the latest version of the ECMAScript standard. ES6 is a significant update to the language, and the first update to the language since ES5 was standardized in 2009. Implementation of these features in major JavaScript engines is underway now.

See the ES6 standard for full specification of the ECMAScript 6 language.

ES6 includes the following new features:

ECMAScript 6 Features

Arrows

Arrows are a function shorthand using the => syntax. They are syntactically similar to the related feature in C#, Java 8 and CoffeeScript. They support both statement block bodies as well as expression bodies which return the value of the expression. Unlike functions, arrows share the same lexical this as their surrounding code.

// Expression bodies
var odds = evens.map(v => v + 1);
var nums = evens.map((v, i) => v + i);
var pairs = evens.map(v => ({even: v, odd: v + 1}));

// Statement bodies
nums.forEach(v => {
  if (v % 5 === 0)
    fives.push(v);
});

// Lexical this
var bob = {
  _name: "Bob",
  _friends: [],
  printFriends() {
    this._friends.forEach(f =>
      console.log(this._name + " knows " + f));
  }
}

More info: MDN Arrow Functions

Classes

ES6 classes are a simple sugar over the prototype-based OO pattern. Having a single convenient declarative form makes class patterns easier to use, and encourages interoperability. Classes support prototype-based inheritance, super calls, instance and static methods and constructors.

class SkinnedMesh extends THREE.Mesh {
  constructor(geometry, materials) {
    super(geometry, materials);

    this.idMatrix = SkinnedMesh.defaultMatrix();
    this.bones = [];
    this.boneMatrices = [];
    //...
  }
  update(camera) {
    //...
    super.update();
  }
  get boneCount() {
    return this.bones.length;
  }
  set matrixType(matrixType) {
    this.idMatrix = SkinnedMesh[matrixType]();
  }
  static defaultMatrix() {
    return new THREE.Matrix4();
  }
}

More info: MDN Classes

Enhanced Object Literals

Object literals are extended to support setting the prototype at construction, shorthand for foo: foo assignments, defining methods, making super calls, and computing property names with expressions. Together, these also bring object literals and class declarations closer together, and let object-based design benefit from some of the same conveniences.

var obj = {
    // __proto__
    __proto__: theProtoObj,
    // Shorthand for ‘handler: handler’
    handler,
    // Methods
    toString() {
     // Super calls
     return "d " + super.toString();
    },
    // Computed (dynamic) property names
    [ 'prop_' + (() => 42)() ]: 42
};

More info: MDN Grammar and types: Object literals

Template Strings

Template strings provide syntactic sugar for constructing strings. This is similar to string interpolation features in Perl, Python and more. Optionally, a tag can be added to allow the string construction to be customized, avoiding injection attacks or constructing higher level data structures from string contents.

// Basic literal string creation
`In JavaScript '\n' is a line-feed.`

// Multiline strings
`In JavaScript this is
 not legal.`

// String interpolation
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`

// Construct an HTTP request prefix is used to interpret the replacements and construction
POST`http://foo.org/bar?a=${a}&b=${b}
     Content-Type: application/json
     X-Credentials: ${credentials}
     { "foo": ${foo},
       "bar": ${bar}}`(myOnReadyStateChangeHandler);

More info: MDN Template Strings

Destructuring

Destructuring allows binding using pattern matching, with support for matching arrays and objects. Destructuring is fail-soft, similar to standard object lookup foo["bar"], producing undefined values when not found.

// list matching
var [a, , b] = [1,2,3];

// object matching
var { op: a, lhs: { op: b }, rhs: c }
       = getASTNode()

// object matching shorthand
// binds `op`, `lhs` and `rhs` in scope
var {op, lhs, rhs} = getASTNode()

// Can be used in parameter position
function g({name: x}) {
  console.log(x);
}
g({name: 5})

// Fail-soft destructuring
var [a] = [];
a === undefined;

// Fail-soft destructuring with defaults
var [a = 1] = [];
a === 1;

More info: MDN Destructuring assignment

Default + Rest + Spread

Callee-evaluated default parameter values. Turn an array into consecutive arguments in a function call. Bind trailing parameters to an array. Rest replaces the need for arguments and addresses common cases more directly.

function f(x, y=12) {
  // y is 12 if not passed (or passed as undefined)
  return x + y;
}
f(3) == 15
function f(x, ...y) {
  // y is an Array
  return x * y.length;
}
f(3, "hello", true) == 6
function f(x, y, z) {
  return x + y + z;
}
// Pass each elem of array as argument
f(...[1,2,3]) == 6

More MDN info: Default parameters, Rest parameters, Spread Operator

Let + Const

Block-scoped binding constructs. let is the new var. const is single-assignment. Static restrictions prevent use before assignment.

function f() {
  {
    let x;
    {
      // okay, block scoped name
      const x = "sneaky";
      // error, const
      x = "foo";
    }
    // error, already declared in block
    let x = "inner";
  }
}

More MDN info: let statement, const statement

Iterators + For..Of

Iterator objects enable custom iteration like CLR IEnumerable or Java Iterable. Generalize for..in to custom iterator-based iteration with for..of. Don’t require realizing an array, enabling lazy design patterns like LINQ.

let fibonacci = {
  [Symbol.iterator]() {
    let pre = 0, cur = 1;
    return {
      next() {
        [pre, cur] = [cur, pre + cur];
        return { done: false, value: cur }
      }
    }
  }
}

for (var n of fibonacci) {
  // truncate the sequence at 1000
  if (n > 1000)
    break;
  console.log(n);
}

Iteration is based on these duck-typed interfaces (using TypeScript type syntax for exposition only):

interface IteratorResult {
  done: boolean;
  value: any;
}
interface Iterator {
  next(): IteratorResult;
}
interface Iterable {
  [Symbol.iterator](): Iterator
}

More info: MDN for…of

Generators

Generators simplify iterator-authoring using function* and yield. A function declared as function* returns a Generator instance. Generators are subtypes of iterators which include additional next and throw. These enable values to flow back into the generator, so yield is an expression form which returns a value (or throws).

Note: Can also be used to enable ‘await’-like async programming, see also ES7 await proposal.

var fibonacci = {
  [Symbol.iterator]: function*() {
    var pre = 0, cur = 1;
    for (;;) {
      var temp = pre;
      pre = cur;
      cur += temp;
      yield cur;
    }
  }
}

for (var n of fibonacci) {
  // truncate the sequence at 1000
  if (n > 1000)
    break;
  console.log(n);
}

The generator interface is (using TypeScript type syntax for exposition only):

interface Generator extends Iterator {
    next(value?: any): IteratorResult;
    throw(exception: any);
}

More info: MDN Iteration protocols

Unicode

Non-breaking additions to support full Unicode, including new Unicode literal form in strings and new RegExp u mode to handle code points, as well as new APIs to process strings at the 21bit code points level. These additions support building global apps in JavaScript.

// same as ES5.1
"

Modern Web Development

A list of technologies for modern web development.

Introduction

With this article I want to share a compilation of some well known top technologies that can be used today to develop a modern web application. The web development world has changed a lot because of its adaptation to the mobile and social media context, and a lot of new technologies, including servers, databases, development frameworks, and libraries have emerged to help us to  resolve several new problems and challenges.

Background

If you are a project manager, an architect, or a developer, you must choose the appropriate server, database,  language, framework or library for the design and implementation of the entire architecture or for some modules of your modern web application. This article references some of the principal and more used technologies that can help you to achieve this.

Servers

Nginx

Ngin is a free, open-source, high-performance HTTP server and reverse proxy, as well as an IMAP/POP3 proxy server. Unlike traditional servers, Nginx doesn’t rely on threads to handle requests. Instead it uses a much more scalable event-driven (asynchronous) architecture. This architecture uses small, but more importantly, predictable amounts of memory under load.

http://wiki.nginx.org/Main

NodeJs  

Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

http://nodejs.org 

Databases

MongoDb

MongoDB (from “humongous”) is an open-source  document database, and the leading NoSQL database, designed for ease of development and scaling. Instead of storing data in tables as is done in a “classical” relational database, MongoDB stores structured data as JSON-like documents with dynamic schemas (MongoDB calls the format BSON), making the integration of data in certain types of applications easier and faster.

http://www.mongodb.org 

Redis

Redis is an open source, BSD licensed, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets. In its outer layer, the Redis data model is a dictionary where keys are mapped to values. One of the main differences between Redis and other structured storage systems is that values are not limited to strings.

http://redis.io 

General purpose Frameworks / Libraries

Backbone.JS

Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.

http://backbonejs.org 

Underscore.Js

Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support that you would expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects. It’s the tie to go along with jQuery’s tux, and Backbone.js’s suspenders.

 http://documentcloud.github.com/underscore 

Sencha frameworks

Sencha creates development frameworks and tools that help you design,  develop, and deploy applications for desktop and mobile devices. Their  goal is to enhance your development experience and final results by  providing well-structured, Web standards-based frameworks and tools that make drafting functional UI and CSS3 animations a breeze, and cloud  services for supporting your application available anytime, anywhere.

http://www.sencha.com/

Zepto.Js

Zepto is a minimalist JavaScript library for modern browsers with a largely jQuery-compatible API. If you use jQuery, you already know how to use Zepto.

http://zeptojs.com

Angular JS

HTML enhanced for web apps! HTML is great for declaring static documents, but it falters when we try to use it for declaring dynamic views in web-applications. AngularJS lets you extend HTML vocabulary for your  application. The resulting environment is extraordinarily expressive, readable, and quick to develop.

http://angularjs.org

Bootstrap

Sleek, intuitive, and powerful front-end framework for faster and easier web development. Bootstrap utilizes LESS CSS, is compiled via Node, and is managed through GitHub to help nerds do awesome stuff on the web. Bootstrap was made to not  only look and behave great in the  latest desktop browsers (as well as IE7!), but in tablet and smartphone browsers via responsive CSS as well.

http://twitter.github.io/bootstrap

Specific Libraries

Modernizr

Modernizr is a small JavaScript library that detects the availability of native implementations for next-generation web technologies, i.e. features that stem from the HTML5 and CSS3 specifications. Many of these features are already implemented in at least one major browser (most of them in two or more), and what Modernizr does is, very simply, tell you whether the current browser has this feature natively implemented or  not.

http://modernizr.com

Knockout

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically  (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and  maintainably.

http://knockoutjs.com 

Require.Js

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments,  like Rhino and Node. Using a modular script loader like RequireJS will  improve the speed and quality of your code.

http://requirejs.org 

Amplify Js

AmplifyJS solves the following problems:

  • AJAX Request Management: amplify.request provides a clean and elegant request abstraction for all types of data, even allowing for transformation prior to consumption.
  • Client Side Component Communication : amplify.publish/subscribe provides a clean, performant API for component to component communication.
  • Client Side Browser & Mobile Device Storage : amplify.store takes the  confusion out of HTML5 localStorage. It doesn’t get simpler than using amplify.store(key, data)! It even works flawlessly on mobile devices.
http://amplifyjs.com 

Moment.Js

A 4.8k JavaScript date library for parsing, validating, manipulating, and formatting dates.

http://momentjs.com 

D3 JS

D3.js is a JavaScript library for manipulating documents based on data. D3 helps you bring data to life using HTML, SVG and CSS. D3’s emphasis on web standards gives you the full capabilities of modern browsers without tying yourself to a proprietary framework, combining powerful  visualization components and a data-driven approach to DOM manipulation. http://d3js.org 

Breezze 

Breeze is a JavaScript library that helps you manage data in rich client applications. If you store data in a relational database, query and save those data as complex object graphs, and share these graphs across multiple screens of your JavaScript client, Breeze is for you.

http://www.breezejs.com/home 

Mongoose JS

Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment.  Woks fine with Node JS.

http://mongoosejs.com 

Meta -Languages

CoffeScript   

CoffeeScript is a little language that compiles into JavaScript. Underneath all those awkward braces and semicolons, JavaScript has always had a gorgeous object model at its heart. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way.

 http://coffeescript.org 

TypeScript

TypeScript is a language for application-scale JavaScript development. TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. Any browser. Any host. Any OS. Open Source.

http://www.typescriptlang.org

Less

The dynamic stylesheet language. LESS extends CSS with dynamic behavior such as variables, mixins, operations and functions.LESS runs on both the server-side (with Node.js and Rhino) or client-side (modern browsers only).

http://lesscss.org 

Application containers

PhoneGap (Apache Cordova)  

Is an HTML5 app platform that allows you to author native applications with web technologies and get access to APIs and app stores. PhoneGap leverages web technologies developers already know best… HTML and JavaScript.

http://www.phonegap.com 

AppCelerator

Create rich native iOS, Android, hybrid, and mobile web apps from a single JavaScript-based SDK. Titanium empowers you to choose the right way to reach your end users on any device.

http://www.appcelerator.com 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

from:http://www.codeproject.com/Reference/597538/Modern-Web-Development