SlideShare a Scribd company logo
Silicon Valley Code Camp
Amazing New Features
In JavaScript
Manoj Kumar
Agenda
•Scope of Variables
•Parameters: default/rest/spread
•Destructuring
•Object Literals
•Arrow functions
•Iterators & Generators
•Promises & Proxies
Scope of a Variable
(ES5)
var x = 1 // global variable, a property in
global obj
b = 2 // global variable, a property in
global obj
function f() {
a = b + 6 // “a” is a global variable, what
about b?
var b = 7; // b is local to this function
// declaration is hoisted but not the
assignment
}
Scope of a Variable
(ES 6)
function f() {
var a = 7; // local to function f
let c = 8; // local to function f
If ( a > 5) {
var b = 9 + c; // Visible anywhere in the
function
let x = 1; // local to this IF block
const pi = 3.14; // constant and local to
IF block
// redefining is not allowed
const obj = { x:9, y:10 }; // obj.x is still

Recommended for you

Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation

This document provides an introduction and overview of Node.js and MongoDB. It discusses that Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine that uses an event-driven, non-blocking I/O model. It can be used for real-time applications and is well-suited for I/O-intensive applications. MongoDB is also introduced as a popular JSON-based NoSQL database that can be easily used with Node.js applications. Examples are given for connecting to MongoDB from Node.js code.

Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database

This document discusses connecting to and interacting with MySQL databases from PHP. It covers connecting to a MySQL database server, selecting databases, executing SQL statements, working with query results, and inserting, updating and deleting records. Functions covered include mysql_connect(), mysql_query(), mysql_fetch_row(), mysql_affected_rows(), and mysql_info(). The document provides examples of connecting to MySQL, selecting databases, executing queries, and accessing and manipulating data.

vijay sharma
PHP MVC
PHP MVCPHP MVC
PHP MVC

The document discusses the Model-View-Controller (MVC) pattern, which separates an application into three main components: the model, the view, and the controller. The model manages the application's data logic and rules. The view displays the data to the user. The controller handles input and converts it to commands for the model and view. An example PHP MVC application is provided to illustrate how the components work together. Benefits of MVC include flexibility, testability, and separation of concerns between the three components.

modelphpmvc
const
const pi1; // error: Missing initialization
const pi2 = 3.14159 ; // works!
pi2 = 3.14 ; // error: can't change the value
for( let i = 5;....) {
const c = i * 9; // const can get a fresh
value inside loop in different iteration
Temporal Dead Zone
Let x = 6;
If ( true ) { // new block scope so TDZ starts
console.log(x) ; // reference error (outer x
not visible)
x = 5; // reference error
let x; // now x can be referenced
console.log(x); // undefined
x = 6;
console.log(x); // 6
}
Temporal => Time
If ( true ) { // new block scope so TDZ starts
const func1 = function () {
Console.log(x);
};
console.log(x) ; // still inside TDZ, so
reference error
let x = 8;
func1(); // inside this call “let x” is effective
}
Default Parameter
Value
function f(x = 0, y = 0) {
}
f(); // 0,0
f(5); // 5,0
f(5, someVarUndefined); // 5,0
f(undefined, 6); // 0, 6
f(5,6); // 5,6
Function(x, y=x) { } //OK
Function (x=y, y=5) { } // y is not available to
use (TDZ)

Recommended for you

JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming

The document provides an overview of JavaScript programming. It discusses the history and components of JavaScript, including ECMAScript, the DOM, and BOM. It also covers JavaScript basics like syntax, data types, operators, and functions. Finally, it introduces object-oriented concepts in JavaScript like prototype-based programming and early vs. late binding.

oopjavascript
炎炎夏日學 Android 課程 - Part1: Kotlin 語法介紹
炎炎夏日學 Android 課程 -  Part1: Kotlin 語法介紹炎炎夏日學 Android 課程 -  Part1: Kotlin 語法介紹
炎炎夏日學 Android 課程 - Part1: Kotlin 語法介紹

炎炎夏日學 Android 課程 - Part1: Kotlin 語法介紹 (Kotlin EveryWhere 活動)

kotlinandroiddevelopment
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial

JavaScript is a scripting language used to make web pages interactive. It was created in 1995 and standardized as ECMAScript. JavaScript can access and modify the content, structure, and style of documents. It is used to handle events, perform animations, and interact with forms on web pages. Common uses of JavaScript include form validation, navigation menus, lightboxes, and sliders on websites.

Rest of the Parameters
function func(x, y, ...others) {
//others[0..n] contains rest of the
parameters
}
func(5,6); // 5,6, others.length==0
func(5,6, 7); // 5,6, others.length==1,
others[0] === 7
Func(5,6, 7,8,9); // 5,6,
others.length==3,
others[0..2] are 7,8,9
Spread Operator
Math.max(2, 5, 6, 8);
Math.max( …[2, 5, 6, 8] )
Same as
Math.max.apply(null, [2,5,6,8])
[1, ...[2,3], 4]
=>
[1, 2, 3, 4]
Destructuring
let [x, y] = [5, 8]; // x === 5, y ===8
var [a, , [b], c] = [5, null, [6]];
// a === 5 && b === 6 && c === undefined
[a, b] = [b, a]
var [a, b, c] = "xy"; // think “xy” as [“x”, “y”]
// a === "x" && b === "y" && c === undefined
Destructuring
{ first: f, last: l } = { first: 'Manoj', last:
'Kumar' }
// f === 'Manoj' && l === 'Kumar'
let { x: x } = { x: 1, y: 2 }; // x = 1
let [ x, ...y ] = 'abc'; // x = 'a'; y = [ 'b', 'c' ]
let [ x, y ] = new Set( [ 'a', 'b' ] ); // x = 'a'; y
= 'b’;
[ ] = { }; // TypeError, empty objects are not
iterable
[ ] = undefined; // TypeError, not iterable
[ ] = null; // TypeError, not iterable
let [x] = [ ]; // x = undefined

Recommended for you

Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials

Things you should know about Javascript ES5. A programming language that enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else

javascriptes5web
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPM

NodeJS is an open source, cross platform run time environment for server side and networking application. NodeJS is popular in development because front & back end side both uses JavaScript Code.

nodenode.jsnpm
Express js
Express jsExpress js
Express js

This document provides an overview of ExpressJS, a web application framework for Node.js. It discusses using Connect as a middleware framework to build HTTP servers, and how Express builds on Connect by adding functionality like routing, views, and content negotiation. It then covers basic Express app architecture, creating routes, using views with different template engines like Jade, passing data to views, and some advanced topics like cookies, sessions, and authentication.

Object Literals
obj = {
red : 255, blue : 127, [ “green” ] : 255
};
red = 255;
blue = 127;
green = 255;
obj = {
red : red, blue : blue, green: green
};
obj = { red, blue, green } // ES 6
Computed Property
let prop = "red";
green = 255;
obj = {
[ prop ] : 255, // [“red”] : 255 or red
: 255
[ "b" + "lue" ] : 127,
green
};
<eot/>
Arrow Functions
●
New way of creating functions
●
function square( x ) { // ES 5 function
●
return x * x;
●
}
x => x * x ; // Arrow function
(x, y) => x + y ; ( ) => 5;
(x, y) => { f(x,y); return x + y; }
x => { a:x+1, b:x+2}; // wrong!
{ means block
x => ({ a:x+1, b:x+2 });
Arrow Functions vs
Normal Functions
1. Following constructs are lexical
●
Arguments
●
this
●
super
●
new.target (target object of
new, null in normal
functions)
2. Cannot be used as constructor
new ( () => { } ) throws an error

Recommended for you

Node js introduction
Node js introductionNode js introduction
Node js introduction

Node.js is a server-side JavaScript platform built on Google's V8 engine. It is non-blocking and asynchronous, making it suitable for data-intensive real-time applications. The document discusses how to install Node.js and its dependencies on Ubuntu, introduces key Node.js concepts like events and the event loop, and provides examples of popular Node.js packages and use cases.

setting up node with virtual appliancescaling the webnode
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js

Node.js and MongoDB are a good fit as MongoDB provides a high-fidelity data store for Node.js applications. To get started quickly, use Nave to manage Node.js versions, npm to manage packages, Express as a web framework, Mongoose as an ODM, and EJS for templating. Key steps include setting up Bootstrap, adding authentication with Mongoose-Auth, and defining schemas like a Link schema for data.

node.js node mongodb mongodc
JQuery UI
JQuery UIJQuery UI
JQuery UI

This document introduces jQuery, including its environment, implementation, and use with jQuery UI. jQuery is a JavaScript library that simplifies client-side scripting by providing methods for selecting elements, handling events, performing animations and AJAX requests, and manipulating the DOM. The document provides examples of using jQuery for these tasks and binding jQuery UI widgets like tabs.

jquery ui;jquery
Symbol
obj.red = 255;
obj[“red”] === 255; // ES5
const my_prop = Symbol(); // ES6
obj[my_prop] = 127; // ES6
Obj = {
[my_prop] : 127
};
const red = Symbol('my_red')
red.toString() === 'Symbol(my_red)'
Symbol() != Symbol()
Symbol( 'red' ) != Symbol( 'red' )
Symbol (Global
Registry)
const globalRedProp = Symbol.for( 'red');
globalRedProp.toString() === 'Symbol(red)';
Symbol.for ( 'red' ) === globalRedProp
Symbol.keyFor( globalRedProp ) === 'red'
Symbol.for( 'red' ) === Symbol.for( 'red' )
Symbol( 'red' ) != Symbol( 'red' )
Built-in symbols:
Symbol.iterator
Symbol.match (===
String.prototype.match )
Iterators
Iterable object makes its element accessible
in for-of loops and spread operators
for (let x of ['a', 'b', 'c']) { // arrays are
iterable
console.log(x);
}
Iterable Objects:
●
Arrays
●
Strings
●
Maps
●
Sets
●
Iterable
How to make any object iterable?
●
Implement a method Symbol.iterator
●
That returns Iterator object
IterableObject = {
[Symbol.iterator] ( ) {
// create an iterator object and
return
}
}

Recommended for you

Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction

Node.js is a JavaScript runtime built on Chrome's V8 engine that allows JavaScript to run on the server side. It uses asynchronous and event-driven programming to handle thousands of concurrent connections with minimal overhead. The presentation introduces Node.js and its architecture, explaining how it uses a single thread with non-blocking I/O and an event loop to handle asynchronous operations efficiently. Examples are provided to illustrate synchronous vs asynchronous code. Common use cases for Node.js include real-time applications, chat/messaging, and high concurrency applications, while it is less suitable for heavy computation or large web apps.

javascriptnode.jssinglepageapp
Node.js Express Framework
Node.js Express FrameworkNode.js Express Framework
Node.js Express Framework

Learn Node.js framework in simple and easy steps starting from basic to advanced concepts with examples including Introduction

nodejsexpressjsjavascript
Creating Single Page Applications with Oracle Apex
Creating Single Page Applications with Oracle ApexCreating Single Page Applications with Oracle Apex
Creating Single Page Applications with Oracle Apex

The presentation describes how SPA can be created with Oracle Apex. Furthermore it adresses some issues on alternative data entry on smartphones

oraclespaapex
Iterator
Iteartor = {
next () {
// keep returning IteratorResult in
successive calls
}
}
IteratorResult = {
value : // current value
done: // false, but at the end true
}
let iterable = {
[Symbol.iterator]() {
let step = 0;
let iterator = {
next() {
if (step <= 2) step++;
switch (step) {
case 1: return { value: 'hello', done:
false };
case 2: return { value: 'world', done:
false };
default: return { value: undefined,
done: true };
}
}
};
return iterator;
}
Iterable
Let iterator = iterable [ Symbol.iterator ] ( ) ;
Iterator.next() === { value : 'hello', done:
false }
Iterator.next() === { value : 'world', done:
false }
Iterator.next() === { value : undefined, done:
true }
While (true) {
let result = iterator.next();
if ( result.done ) break;
Iterable in for-of
for (let x of iterable) {
console.log(x);
}
for ( let [k,v] of map)
for ( let x of Array.from(arrayLike))
//length, 0:, 1:..
for ( let [k,v] of array.entries())

Recommended for you

Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners

PHP is a server-side scripting language that can be embedded into HTML. It is used to dynamically generate client-side code sent as the HTTP response. PHP code is executed on the web server and allows variables, conditional statements, loops, functions, and arrays to dynamically output content. Key features include PHP tags <?php ?> to delimit PHP code, the echo command to output to the client, and variables that can store different data types and change types throughout a program.

phpphp tutorialsphp for beginners
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.

This document provides an agenda for discussing JavaScript ES6 features such as promises, arrow functions, constants, modules, classes, transpilation, default parameters, and template strings. It also discusses how to use ES6 today via transpilation with tools like Babel and Traceur, and which companies are using ES6 and those transpilation tools.

javascript
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6

This document discusses new features coming to JavaScript in ECMAScript 6, including: 1) Block scope keywords "let" and "const" that allow for block-level scoping of variables. 2) Shorthand syntax for object literals and method definitions. 3) Destructuring assignments for extracting values from objects and arrays. 4) Default parameter values, rest parameters, and spread syntax for working with functions and arrays. 5) New features like modules, classes, and imports for better organizing code.

Generator
function * simpleGenFunc () {
yield 'hello';
yield 'world';
}
Iterator = simpleGenFunc ();
Iterator.next ( ) ; // { value: “hello”, done:
false }
Iterator.next ( ); // { value: “world”, done:
false }
Iterator.next ( ); // { value: undefined, done:
true }
for ( x of simpleGenFunc () ) {
Generator
let arr = [ ...simpleGenFunc ( ) ]; // [ 'hello',
'world']
let [ x, y ] = simpleGenFunc ( );
x === 'hello'
y === 'world'
Generator
Generators are
●
Data Producers (as iterator)
●
Data Consumer (Yield can get data
from next())
●
Communicating sequential tasks..
function * genFunc () {
try {
let hint = yield 'hello';
// do something with hint
yield 'world';
} finally {
// Do some cleanup here
}
}
Iterator = genFunc();
Iterator.next(); // gives hello
Iterator.next(“stop”); // gives 'world', hint ===
“stop”
Iterator.next(); // cleanup code executes,

Recommended for you

ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts

The next version of JavaScript, ES6, is starting to arrive. Many of its features are simple enhancements to the language we already have: things like arrow functions, class syntax, and destructuring. But other features will change the way we program JavaScript, fundamentally expanding the capabilities of the language and reshaping our future codebases. In this talk we'll focus on two of these, discovering the the myriad possibilities of generators and the many tricks you can pull of with template strings.

generatorsjavascriptes6
ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life

The document discusses using ES6 features in real-world applications. It provides examples of using arrow functions, classes, destructuring, template literals, and default parameters to write cleaner code. It also discusses tools for enabling ES6 features that are not yet fully supported, such as transpilers, and flags in Node.js and Chrome to enable more experimental features. Overall, the document advocates adopting ES6 features that make code more concise and readable.

javascriptes6traceur
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview

This document provides a history of ECMAScript (ES) and JavaScript standards. It discusses the origins of JavaScript in 1995 and its standardization by ECMA in 1997 as ECMAScript. New versions were released periodically, including ES5 in 2009 and ES6 in 2015. ES6 was also referred to as ES2015 since version names going forward would be based on the year of release.

es2015javacriptes6
Promise
setTimeout(
function() { console.log("timeout!");},
delay );
promise = timeout(delay) ;
promise.then(
function(result) { console.log("Result: " +
result);}
);
Promise
function timeout(delay) {
return new Promise(
function(resolve, reject) {
setTimeout(
function() {
resolve();
}, delay);
});
}
promise = timeout(delay) ;
promise.then( function(result) {….} );
Promise
let promise = someAsyncOp() ;
promise.then ( function (result) {
console.log(“Result: “ + result);
}, function (err) {
console.log(“Failed: “ + err);
}
)
Promise
promise.then ( null, function (err) {
console.log(“Failed: “ + err);
});
promise.catch(function (err) {
console.log(“Failed: “ + err);
} );

Recommended for you

Fat Arrow (ES6)
Fat Arrow (ES6)Fat Arrow (ES6)
Fat Arrow (ES6)

1. Arrow functions provide a concise syntax for defining anonymous functions and avoiding issues with binding 'this'. 2. They are best used for list processing and anonymous callback functions. 3. Arrow functions lexically bind 'this' from the enclosing context and cannot be used as constructors or contain yield expressions. 4. When a function requires a constructor, generator, changing 'this' binding, or needs arguments - a regular function expression is better.

functionarrowjavascript
Angular2
Angular2Angular2
Angular2

A fast-paced introduction to Angular 2, TypeScript, SVG graphics in Angular 2, Flux, Redux, Relay, GraphQL, and React Native

typescriptreduxsvg graphics2
ES6: The future is now
ES6: The future is nowES6: The future is now
ES6: The future is now

The document provides a history of the ECMAScript specification from 1995 to 2015. It outlines the major releases and additions to the language over time including ES3.1, ES5, ES6, and the ongoing development of future versions. Key changes include the introduction of classes, modules, arrow functions, promises, generators, and more robust collection types like Sets and Maps. The specification is developed by the TC39 committee group within Ecma International.

javascriptes6
Promise
• Life Cycle
– Unsettled Promise
• State: PENDING
– Settled Promise
• State: FULFILLED
• State: REJECTED
–
– promise.then ( fulfilledCaseCallback,
rejectedCaseCallBack);
– promise.then(fulfilledCaseCallback);
– promse.catch(rejectedCaseCallback);
Promise
Chaining
promise.then ( fulfillmentFunction1 )
.then ( fulfillmentFunction2 );
promise2 = promise.then
( fulfillmentFunction1 )
promise2.then ( fulfillmentFunction2 );
Promise
Promise.all([promise1, promise2])
.then(function(results) {
// Both resolved
})
.catch(function(error) {
// One rejected
});
Promise
Promise.race([promise1, promise2])
.then(function(results) {
// one got resolved
})
.catch(function(error) {
// First settlement was in rejection
});
<eot/>

Recommended for you

VueJs 簡介
VueJs 簡介VueJs 簡介
VueJs 簡介

This document contains links to articles announcing the release of Vue.js version 2.0, including new features like components and improved reactivity system. It also links to resources like the Vue.js documentation guide on the Chinese site, a Chrome extension for Vue development tools, and a GitHub list of awesome Vue.js projects.

f2e
Building a Great Engineering Culture
Building a Great Engineering CultureBuilding a Great Engineering Culture
Building a Great Engineering Culture

Building a Great Engineering Culture outlines five tenets of great engineering culture: work/life balance, community, personal development, communication, and team structure. It recommends embracing open source, giving back to the community, investing in continuous learning, being transparent and honest, supporting failure as long as teams learn from it, and measuring individuals based on their contribution to the team rather than heroics. Managers should still spend significant time coding.

culturesoftware developmentengineering
[朝陽科大] D3.js 資料視覺化入門
[朝陽科大] D3.js 資料視覺化入門 [朝陽科大] D3.js 資料視覺化入門
[朝陽科大] D3.js 資料視覺化入門

D3.js 資料視覺化入門 @ 朝陽科大 2015.12.23

infographicjavascriptd3.js
Proxy
Let proxy = new Proxy( target,
handler );
Handler: Object with one or more traps
Traps:
– Get
– Set
– Has
– deleteProperty
– defineProperty
Proxy
More Traps:
– isExtensible
– preventExtensions
– getPrototypeOf
– setPrototypeOf
– ownKeys
– apply (calling a function)
– Construct (using new)
–
–
let target = { name: "smartObject" };
let proxy = new Proxy(target, {
set(trapTarget, key, value, receiver) {
if (isNaN(value)) {
throw new TypeError("Property must be a number.");
}
return Reflect.set(trapTarget, key, value, receiver);
}
});
proxy.count = 1; // numeric properties are okay
proxy.color = "red"; // throws exception
<eot/>
References
• ecmascript 6 compatibility table
– https://kangax.github.io/compat-table/es6/
• http://exploringjs.com/es6/index.html
– Thanks to the author for tons of examples!
• leanpub.com/understandinges6
• JavaScript: The Good Parts
– Douglas Crockford
• Effective JavaScript

Recommended for you

Vue js 大型專案架構
Vue js 大型專案架構Vue js 大型專案架構
Vue js 大型專案架構

VueJS is a progressive framework for building user interfaces. It introduces key concepts like the MVVM pattern, reactivity system, lifecycle hooks and components. The document discusses various aspects of VueJS including using .vue files with different languages for templates, styles and scripts. It also covers Vuex for state management, Vue Router for routing, VueStrap for Bootstrap components, and integrating JWT authentication with Auth0.

vuejsjavascript
Vue 2.0 + Vuex Router & Vuex at Vue.js
Vue 2.0 + Vuex Router & Vuex at Vue.jsVue 2.0 + Vuex Router & Vuex at Vue.js
Vue 2.0 + Vuex Router & Vuex at Vue.js

- Vue.js Tokyo v-meetup="#1" http://vuejs-meetup.connpass.com/event/31139/ - JS Night at Bizreach http://connpass.com/event/34014/

vue.js
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come

An overview of some of the history of JavaScript, how it became ECMAScript (and what Ecma is), as well as highlights of the new features and syntax in ES6 aka ES2015. Originally presented to the New York Public Library on June 4 2015.

babeles2015es6
Thank You!
Please provide your feedback :)
Feedback from earlier sessions:
Speaker started with the concepts that were
way too simple and then at the end it became
way too complex.
ES6 PPT FOR 2016
Slides from Older Presentations
•You may not find things in sequence in rest
of the slides
ES5 Equiv of Class
function Cube(size) {
this.size = size;
}
Cube.prototype.rotate = function (direction) {
// rotate the cube;
};
Let simpleCube = new Cube(3);
simpleCube.size === 3
simpleCube.rorate(“left”);

Recommended for you

Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2

AngularJS 1.3 is by far the best version of Angular available today. It was just released a few weeks ago. It's chock full of bug fixes, feature enhancements and performance improvements. YouTube link: - https://youtu.be/bghVyCbxj6g

angularjsjsknowledge sharing
第一次用 Vue.js 就愛上 [改]
第一次用 Vue.js 就愛上 [改]第一次用 Vue.js 就愛上 [改]
第一次用 Vue.js 就愛上 [改]

This document provides an overview of Vue.js including: - Key features like MVVM pattern, data binding, directives, lifecycle hooks - How to set up a basic project using vue-cli - Components, props, events, slots - Conditional rendering, lists, transitions - Tools and resources for learning more about Vue.js

vue.jsfrontendjavascript
Free Download Powerpoint Slides
Free Download Powerpoint SlidesFree Download Powerpoint Slides
Free Download Powerpoint Slides

Powerpoint Search Engine has collection of slides related to specific topics. Write the required keyword in the search box and it fetches you the related results.

powerpoint search engine
ES 6 Class
class Cube {
constructor (size) {
this.size = size;
}
rotate(direction) {
// rotate the cube
}
}
let simpleCube = new Cube(3);
simpleCube.size === 3
simpleCube.rorate(“left”);
Derived Class
class RubiksCube extends Cube {
constructor (size, colors) {
super(size);
this.colors = colors;
}
solve() {
// solve the cube
}
}
Derived Class
class RubiksCube extends Cube {
constructor (size, colors) {
super(size);
this.colors = colors;
}
solve() {
// solve the cube
}
}
class BinaryTree {
constructor(value, left=null, right=null) {
this.value = value;
this.left = left;
this.right = right;
}
* [ Symbol.iterator ] ( ) {
yield this.value;
If ( this.left ) {
yield* this.left;
}
If ( this.right ) {
yield* this.right;
}
}
}

Recommended for you

The Art of AngularJS in 2015
The Art of AngularJS in 2015The Art of AngularJS in 2015
The Art of AngularJS in 2015

Presentation from Denver Open Source Users Group in February 2015. http://www.meetup.com/DOSUG1/events/219099019/ AngularJS is one of today's hottest JavaScript MVC Frameworks. In this session, we'll explore many concepts it brings to the world of client-side development: dependency injection, directives, filters, routing and two-way data binding. We'll also look at its recommended testing tools and build systems. Finally, you'll learn about my experience developing several real-world applications using AngularJS, HTML5 and Bootstrap.

coffeescriptgrunthttp2
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6

This contains all the slides used in Silicon Valley Code Camp presentation on Sunday Oct 4, 10:45 session on "Amazing new features in JavaScript". At the end ut also includes the last year presentation covering ES 5

ecmascript programming functionaljavascript
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript

This document provides examples and explanations of JavaScript concepts including objects and arrays, functions and contexts, closures, inheritance, namespaces and scope, module patterns, and dispatching. It demonstrates creating and manipulating objects and arrays, defining functions, using closures, implementing inheritance with prototypes and Object.create, creating namespaces, revealing and constructor module patterns, and a publisher/subscriber dispatching example.

inheritancemixinfunction
let tree = new BinaryTree(
'a',
new BinaryTree(
'b',
new BinaryTree('c'),
new BinaryTree('d')),
new BinaryTree('e'));
for (let x of tree) {
console.log(x);
}
// Output:
// a
// b
// c
// d
// e
Module
A JavaScript file is a module
One module is only one JavaScript file
Export entities in the module where declared
Import entities from a module in a module
Module
//------ lib.js ------
export function square (x) {
return x * x;
}
export function diag (x, y) {
return sqrt(square(x) + square(y));
}
export const sqrt = Math.sqrt;
//------ main.js ------
import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5
Module
import * as mylib from 'lib';
console.log ( mylib.square(11) ); // 121
console.log ( mylib.diag(4, 3) ); // 5
Imports are hoisted
Cyclic dependency is supported
Re-export some imported entities
●
Export * from lib
●
Export { square as num_square, diag }
from lib

Recommended for you

FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6

Generators in ECMAScript provide a way to write iterator functions using the yield keyword. This allows for writing functions that can be iterated over manually or used to create infinite streams. Generators also enable asynchronous programming using coroutines instead of callbacks. They allow for cooperative multitasking by starting multiple generator functions as "threads" that yield values in a nondeterministic order. Array comprehensions are also proposed as a shorthand for transforming arrays using generators.

modulesdmitry soshnikovrest
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers

This document provides an overview of JavaScript for PHP developers. It compares the syntax and core concepts between the two languages. Some of the key points covered include: variables and data types are similar, functions are objects in JavaScript, JavaScript uses prototypes instead of classes, and functions provide scope. The document also summarizes the built-in global functions and properties, common methods for objects like Array and String, and emphasizes that constructor functions are often not needed in JavaScript.

phpconfoojavascript
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015

Lecture for Binary Studio Academy PRO course about ReactJS by Nikita Semenistiy (TechLead & JS developer at Binary Studio)

javascriptbinary studioes2015
Scope
•ES5
– Function Scope
– Global Scope
– var keyword
• ES6
– Block scope
– let and const keywords
Scope of a Variable
(ES 6)●
New Features (1)
•Arrow Function
•Classes
•Enhanced object literals
•Template strings
•Destructuring
•Default, rest, spread
•Let, const
•Iterators, for..of
•Generators
New Features (2)
Unicode
Modules
Module loaders
Map, set, weakmap, weakset
Proxies
Symbols
Subclassable built-ins
Promises

Recommended for you

Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits

The document provides an overview of JavaScript fundamentals, common patterns, and an introduction to Node.js. It discusses JavaScript data types and operators, variable scoping, objects and classes. It also covers jQuery optimization techniques like selector caching and event handling. For Node.js, it demonstrates how to create an HTTP server, manage dependencies with npm, build an Express server, and use middleware.

javascriptnode.jsjquery
Javascript
JavascriptJavascript
Javascript

This document provides a summary of new features in JavaScript, including let/const block scoping, arrow functions, template strings, classes, generators, async/await, and more. It explains each feature in 1-3 sentences and includes code examples.

javascriptes6es2015
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6

ECMAScript6: Novedades y navegadores que dan soporte a ECMAScript6. Presentado por ings.: Alex Adriá y Mario García

developmentvisualengincode
New Features (3)
•Math, number, string, array, object
APIs
•Binary and octal literals
•Reflect api
•Tail call optimization
•
Silicon Valley Code Camp
2014
Learn JavaScript
by
Modeling Rubik’s Cube
Manoj Kumar
Agenda
•Scripting Language
•Crash course in Rubik’s Cube
•Code Walk-through
•Modeling
•Finding moves
Scripting Language
•Is a Programming Language
–To manipulate
–To customize
–To automate
–an existing system
•ECMAScript
–Web Scripting Language
–To work with web browser

Recommended for you

Introduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy Cresine

A discussion on the upcoming new features in ES6 and how they change the way we build applications with JavaScript. Most Notable Upcoming Changes in EcmaScript 6 Classes: Classes are now first-class citizens in ES6. The language offers support for classes ("class" keyword), constructors ("constructor" keyword) and the "extend" keyword for inheritance. Modules: Modules provide a much needed way to segment and organize JavaScript applications in logical chunks of code. Many frameworks already provide ways to modularize large apps, but standardizing a common module structure will bring a level of interoperability between various JavaScript libraries. Block Scoping: Scoping in JavaScript can be a confusing topic for programmers coming from more traditional Object-Oriented languages such as Java or C#. There are basically two scopes in JavaScript: global and function. Until now. With the help of the "let" keyword, ES6 enables the definition of block scopes for variables and functions. Default Parameters: A liked feature of many other languages such as Ruby, the default parameters save endless checking of they've been passed and if they are "undefined". Enhanced Object Literals: There is now a handy expression for property: property assignments and methods can be defined without the "function" keyword.

javascriptdevelopmentmodular
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6

The document summarizes Dmitry Soshnikov's presentation on ECMAScript 6 features at the HelsinkiJS meetup on December 12, 2011. Key features discussed include default function parameters, modules system, quasi-literals for string templates, array comprehensions, maps and weak maps, destructuring assignment, rest operator for function arguments, proxy objects for meta programming, and struct types.

modulesecmascript6proxy
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript

This document summarizes advanced JavaScript concepts including: - Object-oriented inheritance patterns in JavaScript and trends toward avoiding new and emulating private members. Pseudo-classical inheritance is recommended for better performance. - Exploiting JavaScript's support for functional programming with higher-order functions to allow functions as arguments and return values for more flexible programming. - Common issues with asynchronous code in JavaScript and how promises can help address callbacks and synchronization. - Common pitfalls to avoid with arrays, numbers, and typeof in JavaScript.

javascript
ECMA Script
•Object Based
–Object: Collection of properties
– Property
• Type : Number, Boolean, String, Array,
Function & other objects
• Attributes
•Value, Writable, Configurable, Enumerable
•Functional
•Based on
–Java, C
–Self (Prototype)
–Scheme (Functional)
Types
•Primitive Value Types
–Number
–String
–Boolean
–Null
–Undefined
•Object
•Array
•Function
Number
•64 bit floating point (sign bit, 11 exp, 52 frac)
•Represents integer and float
– 1, 3.45, 5.345e-10, 0377, 0xFF,
•Infinity
– >1.79769313486231570e+308
•NaN
– NaN != NaN
•Representation for
– MAX_VALUE, MIN_VALUE
– NEGATIVE_INFINITY, POSITIVE_INFINITY
• +0 == -0 but 1/+0 != 1/-0
String
•Within double/single quotes
– “Hello world”
– ‘u0041 world’
•Sequence of 16 bit unicode chars
•Supports + operator
•Used for character type too
•
•

Recommended for you

ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview

The document defines a LineChart class that extends the Chart class. The LineChart class constructor calls the parent constructor and draws the chart. The draw method builds a line chart from the series data using an SVG library, appends it to the canvas, and adds statistics for each data point by calling the parent addStats method. The getSerieData static method calculates max and average values for a data series. The class is exported for use in other code.

javascriptecmascript 2015web development
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction

Not so long ago Microsoft announced a new language trageting on front-end developers. Everybody's reaction was like: Why?!! Is it just Microsoft darting back to Google?! So, why a new language? JavaScript has its bad parts. Mostly you can avoid them or workaraund. You can emulate class-based OOP style, modules, scoping and even run-time typing. But that is doomed to be clumsy. That's not in the language design. Google has pointed out these flaws, provided a new language and failed. Will the story of TypeScript be any different?

typescript javascript ecmascript
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02

The document provides an overview of JavaScript for PHP developers. It discusses similarities and differences between JavaScript and PHP syntax, including variables, arrays, conditionals, loops, functions, objects, prototypes, and more. It also summarizes the built-in JavaScript API, including global functions, constructors, and properties and methods of objects like Object, Array, Function, String, Number, Math, Date, and Error.

Boolean
•Only two values
– true
– false
•6 more falsy values
– 0, -0, “”, NaN, null, undefined
• Rest all values are true
– Including ‘false’ :)
•
Undefined and Null
•Undefined Type
– Only one value: undefined
–
•Null Type
– Only one value: null
•
Binary Operators
•Binary + (Addition or concatenation)
– 1 + 2 = 3,
– ‘1’ + ‘2’ = ‘1’ + 2 = 1 + ‘2’ = ‘12’
•-, * , /, %
– 2 * ‘3’ = 6
•>=, <=, >, <
•==, !=
•=== !==
•Logical &&, ||
Prefix Operators
•+ to number
– 1 + +'2' // 3
•- negate
•! logical not
•Typeof
– typeof 1 // ‘number’
– typeof ‘a’ // ‘string’
•

Recommended for you

Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics

Javascript is a dynamic scripting language used widely for client-side web development. It allows asynchronous HTTP (AJAX) requests to update pages dynamically without reloading. Key features include variables, functions, objects, conditionals, closures and exceptions. The DOM represents the structure of a web page and can be manipulated with Javascript to dynamically change content, add/remove elements.

xhrxmlhttprequestbasics
Composition in JavaScript
Composition in JavaScriptComposition in JavaScript
Composition in JavaScript

The document discusses the concept of composition in programming. It provides examples of how to compose objects and functions to maximize code reuse. It promotes writing small, single-purpose functions that can be reused and combined through patterns like chaining and piping. This allows building complex programs from simple, composable parts that work together through universal interfaces like streams.

compositionfunctional programmingjavascript
Exploring ES6
Exploring ES6Exploring ES6
Exploring ES6

This document discusses exploring ES6 features including classes, modules, arrow functions, template literals, destructuring, iterators, generators, and proxies. It provides code examples of implementing classes, modules, and other features in ES5 syntax compared to the cleaner ES6 syntax. It also discusses setting up a development environment with Node.js, npm, and Babel to use ES6 features and introduces more advanced topics like proxies and generators.

es6es2015frontend
Bit Operators
•& and
•| or
•^ xor
•~ not
•>> signed right shift
•>>> unsigned right shift
•<< left shift
And more
•= assignment
•+=, -=, *=, /= %=
– X op= y ==> x = x op y
•++ increment
– X++ ==> x = x+1
•-- decrement
– X-- ==> x = x-1
A Simple Object
point = { x : 100, y : 200 };
point.x // 100
point[‘x’] // 100
point.y = 300;
ap = { “x-coord” : 100, “y-coord” : 200 };
ap.x-coord // Error, - means subtraction
ap[“x-coord”] // 100
ap[“X-coord”] // undefined, (note the upper
case X)
Arrays
var x = [5, 3];
x.length => 2
x.push(7) ===> add a new element
x[20] = 9 ===> 3 to 19 elements are empty
delete x[1] == remove one element
x.splice(beginIndex, noOfElemToRemove)
typeof x ==> ‘object’ .. not a good design
x.constructor == Array
concat, join, pop, reverse, slice, shift, sort

Recommended for you

ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript

The document summarizes the key features of ES6 (ECMAScript 2015), the next version of JavaScript. It discusses new features like block scoping with let and const, arrow functions, classes, enhanced object literals, template strings, and promises. It also covers iterators and generators, which allow iterable objects to be looped over and asynchronous code to be written more cleanly. The presentation provides examples to illustrate how developers can take advantage of these new language features in their code.

programmingjavascriptes6
ES6: Features + Rails
ES6: Features + RailsES6: Features + Rails
ES6: Features + Rails

This document provides an overview of ES6 features and how to set them up for use in Ruby on Rails applications. It describes key ES6 features such as let and const block scoping, template strings, destructuring assignment, default and rest parameters, loops and generators, enhanced object literals, Maps and Sets, arrow functions, modules, and classes. It then provides instructions for using the sprockets-es6 gem to transpile ES6 code to ES5 for use in Rails, as well as using Node.js and Gulp as an alternative approach.

ES6 generators
ES6 generatorsES6 generators
ES6 generators

This document discusses ES6 generators and how they can be used to avoid callback inception. Generators allow functions to pause execution and yield values using the yield keyword. Behind every generator is an iterator object that can be used to control execution. Generators can be iterated over using a for...of loop or by calling next() on the iterator. Examples demonstrate using generators to iterate through fibonacci numbers and to pause asynchronous code using yield instead of callbacks.

javascriptes6web development
ES6 PPT FOR 2016
Functions
function add(x, y) {
return x+y
}
sum = add(4,5)
myAdd = add
sum1 = myAdd(4, 5)
Function Var
Assignment
myAdd = function add(x, y) {
return x+y
}
sum1 = myAdd(4, 5)
sum2 = add(4, 5)
ReferenceError: add is not defined
Function Var
Assignment
myAdd = function (x, y) {
return x+y
}
sum1 = myAdd(4, 5)

Recommended for you

CCS367-STORAGE TECHNOLOGIES QUESTION BANK.doc
CCS367-STORAGE TECHNOLOGIES QUESTION BANK.docCCS367-STORAGE TECHNOLOGIES QUESTION BANK.doc
CCS367-STORAGE TECHNOLOGIES QUESTION BANK.doc

CCS367-STORAGE TECHNOLOGIES QUESTION BANK

 
by Dss
ccs367-storage technologies qb
Best Practices of Clothing Businesses in Talavera, Nueva Ecija, A Foundation ...
Best Practices of Clothing Businesses in Talavera, Nueva Ecija, A Foundation ...Best Practices of Clothing Businesses in Talavera, Nueva Ecija, A Foundation ...
Best Practices of Clothing Businesses in Talavera, Nueva Ecija, A Foundation ...

This study primarily aimed to determine the best practices of clothing businesses to use it as a foundation of strategic business advancements. Moreover, the frequency with which the business's best practices are tracked, which best practices are the most targeted of the apparel firms to be retained, and how does best practices can be used as strategic business advancement. The respondents of the study is the owners of clothing businesses in Talavera, Nueva Ecija. Data were collected and analyzed using a quantitative approach and utilizing a descriptive research design. Unveiling best practices of clothing businesses as a foundation for strategic business advancement through statistical analysis: frequency and percentage, and weighted means analyzing the data in terms of identifying the most to the least important performance indicators of the businesses among all of the variables. Based on the survey conducted on clothing businesses in Talavera, Nueva Ecija, several best practices emerge across different areas of business operations. These practices are categorized into three main sections, section one being the Business Profile and Legal Requirements, followed by the tracking of indicators in terms of Product, Place, Promotion, and Price, and Key Performance Indicators (KPIs) covering finance, marketing, production, technical, and distribution aspects. The research study delved into identifying the core best practices of clothing businesses, serving as a strategic guide for their advancement. Through meticulous analysis, several key findings emerged. Firstly, prioritizing product factors, such as maintaining optimal stock levels and maximizing customer satisfaction, was deemed essential for driving sales and fostering loyalty. Additionally, selecting the right store location was crucial for visibility and accessibility, directly impacting footfall and sales. Vigilance towards competitors and demographic shifts was highlighted as essential for maintaining relevance. Understanding the relationship between marketing spend and customer acquisition proved pivotal for optimizing budgets and achieving a higher ROI. Strategic analysis of profit margins across clothing items emerged as crucial for maximizing profitability and revenue. Creating a positive customer experience, investing in employee training, and implementing effective inventory management practices were also identified as critical success factors. In essence, these findings underscored the holistic approach needed for sustainable growth in the clothing business, emphasizing the importance of product management, marketing strategies, customer experience, and operational efficiency.

best practicesclothing businesskey performance indicators
21EC63_Module1B.pptx VLSI design 21ec63 MOS TRANSISTOR THEORY
21EC63_Module1B.pptx VLSI design 21ec63 MOS TRANSISTOR THEORY21EC63_Module1B.pptx VLSI design 21ec63 MOS TRANSISTOR THEORY
21EC63_Module1B.pptx VLSI design 21ec63 MOS TRANSISTOR THEORY

VLSI design 21ec63 MOS TRANSISTOR THEORY

Anonymous Function
sum = function (x, y) {
return x+y
} (4,5)
sum = (function (x, y) {
return x+y
}) (4,5)
Arguments
function add( ) {
var sum = 0
for( var i = 0; i < arguments.length; i++) {
sum += arguments[i]
}
return sum
}
add(4, 5) => 9
add(4,5,3) => 12
add() => 0
Functional Programming
• Function as a first class object
– Assign to variables
– Pass to other functions
• Avoid State change, mutability, side effects
• Prefer recursion over loop
• Higher Order Functions
– ForEach (function, collection)
– Map (function, collection)
– Filter (function, collection)
– Reduce (function, accumulator, collections)
– Curry (function)
Code Walkthrough
Model Rubik’s Cube
with
Arrays and Functions

Recommended for you

Quadcopter Dynamics, Stability and Control
Quadcopter Dynamics, Stability and ControlQuadcopter Dynamics, Stability and Control
Quadcopter Dynamics, Stability and Control

A brief introduction to quadcopter (drone) working. It provides an overview of flight stability, dynamics, general control system block diagram, and the electronic hardware.

Chlorine and Nitric Acid application, properties, impacts.pptx
Chlorine and Nitric Acid application, properties, impacts.pptxChlorine and Nitric Acid application, properties, impacts.pptx
Chlorine and Nitric Acid application, properties, impacts.pptx

Chlorine and Nitric acid

Trends in Computer Aided Design and MFG.
Trends in Computer Aided Design and MFG.Trends in Computer Aided Design and MFG.
Trends in Computer Aided Design and MFG.

Trends in CAD CAM

Scope of a Variable
function f() {
a = 6 // “a” is a global variable
}
a = 5
f()
// a is 6 now
Scope of a Variable
function f() {
var a = 6 // “a” is a local variable
alert("After assignment : a = " + a)
}
a = 5
alert("Before Calling function: a = " + a)
f()
alert("After Calling function: a = " + a)
Scope of a Variable
function f() {
a = 6
….
var a = 7 // makes “a” a local
variable!
// declaration is hoisted but not the
initializer!
}
a = 5
f()
Scope of a Variable
(ES 6)
function f() {
var a = 7; // local to function f
If ( a > 5) {
var b = 9; // Visible anywhere in the
function
let c = 1; // local to this IF block
const pi = 3.14; // constant and local to
IF block
}
}

Recommended for you

Exploring Deep Learning Models for Image Recognition: A Comparative Review
Exploring Deep Learning Models for Image Recognition: A Comparative ReviewExploring Deep Learning Models for Image Recognition: A Comparative Review
Exploring Deep Learning Models for Image Recognition: A Comparative Review

Image recognition, which comes under Artificial Intelligence (AI) is a critical aspect of computer vision, enabling computers or other computing devices to identify and categorize objects within images. Among numerous fields of life, food processing is an important area, in which image processing plays a vital role, both for producers and consumers. This study focuses on the binary classification of strawberries, where images are sorted into one of two categories. We Utilized a dataset of strawberry images for this study; we aim to determine the effectiveness of different models in identifying whether an image contains strawberries. This research has practical applications in fields such as agriculture and quality control. We compared various popular deep learning models, including MobileNetV2, Convolutional Neural Networks (CNN), and DenseNet121, for binary classification of strawberry images. The accuracy achieved by MobileNetV2 is 96.7%, CNN is 99.8%, and DenseNet121 is 93.6%. Through rigorous testing and analysis, our results demonstrate that CNN outperforms the other models in this task. In the future, the deep learning models can be evaluated on a richer and larger number of images (datasets) for better/improved results.

image recognitiondeep learning
Vernier Caliper and How to use Vernier Caliper.ppsx
Vernier Caliper and How to use Vernier Caliper.ppsxVernier Caliper and How to use Vernier Caliper.ppsx
Vernier Caliper and How to use Vernier Caliper.ppsx

A vernier caliper is a precision instrument used to measure dimensions with high accuracy. It can measure internal and external dimensions, as well as depths. Here is a detailed description of its parts and how to use it.

IWISS Catalog 2024
IWISS Catalog 2024IWISS Catalog 2024
IWISS Catalog 2024

A brand new catalog for the 2024 edition of IWISS. We have enriched our product range and have more innovations in electrician tools, plumbing tools, wire rope tools and banding tools. Let's explore together!

iwissicrimpcable tool
loop variable with var
// Objective
// funcs [ 0 ] = function( ) { return 0; } ;
// funcs [ 1 ] = function( ) { return 1; } ;
// funcs [ 2 ] = function( ) { return 2; } ;
let funcs = [ ];
for (var i=0; i < 3; i++) {
funcs.push( function() { return i;} );
}
funcs[0]() ; // 3
funcs[1]() ; // 3
funcs[2]() ; // 3
loop variable with var
Funcs = [ ];
functionCreator(n) {
return function() { return n;}
}
}
for (var i=0; i < 3; i++) {
funcs.push( functionCreator(i));
}
funcs[0]() ; // 0
funcs[1]() ; // 1
funcs[2]() ; // 2
loop variable with var
for (var i=0; i < 3; i++) {
funcs.push(
function(n) {
return function() { return n;}
}(i)
);
}
funcs[0]() ; // 0
funcs[1]() ; // 1
funcs[2]() ; // 2
loop variable with let
let funcs = [ ];
for (let i=0; i < 3; i++) {
// new binding of “ i ” is created in every
iteration
funcs.push( function() { return i;} );
}
funcs[0]() ; // 0
funcs[1]() ; // 1
funcs[2]() ; // 2
<eot/>

Recommended for you

22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf

CSS chapter 1 notes

UNIT I INCEPTION OF INFORMATION DESIGN 20CDE09-ID
UNIT I INCEPTION OF INFORMATION DESIGN 20CDE09-IDUNIT I INCEPTION OF INFORMATION DESIGN 20CDE09-ID
UNIT I INCEPTION OF INFORMATION DESIGN 20CDE09-ID

20CDE09- INFORMATION DESIGN UNIT I INCEPTION OF INFORMATION DESIGN Introduction and Definition History of Information Design Need of Information Design Types of Information Design Identifying audience Defining the audience and their needs Inclusivity and Visual impairment Case study.

information designinceptiondefine
Evento anual Splunk .conf24 Highlights recap
Evento anual Splunk .conf24 Highlights recapEvento anual Splunk .conf24 Highlights recap
Evento anual Splunk .conf24 Highlights recap

Encontro anual da comunidade Splunk, onde discutimos todas as novidades apresentadas na conferência anual da Spunk, a .conf24 realizada em junho deste ano em Las Vegas. Neste vídeo, trago os pontos chave do encontro, como: - AI Assistant para uso junto com a SPL - SPL2 para uso em Data Pipelines - Ingest Processor - Enterprise Security 8.0 (Maior atualização deste seu release) - Federated Analytics - Integração com Cisco XDR e Cisto Talos - E muito mais. Deixo ainda, alguns links com relatórios e conteúdo interessantes que podem ajudar no esclarecimento dos produtos e funções. https://www.splunk.com/en_us/campaigns/the-hidden-costs-of-downtime.html https://www.splunk.com/en_us/pdfs/gated/ebooks/building-a-leading-observability-practice.pdf https://www.splunk.com/en_us/pdfs/gated/ebooks/building-a-modern-security-program.pdf Nosso grupo oficial da Splunk: https://usergroups.splunk.com/sao-paulo-splunk-user-group/

splunksoarcybersecurity
Semicolon Insertion
You can only leave out ;
– Before }
A = 6 }
– After new line(s)
A = 6
}
– End of the program
Cannot leave ; within ‘for’ header
– for (var i=0; i < 7 .. NO ; inserted here
i++) {
Semicolon Insertion
Inserted only if next token cannot be parsed
A = 6 (; is inserted automatically)
X = 5
What if next line seems to be continuation?
A = b (; is NOT inserted
automatically)
(add(3,4),......)
– So problem starting chars are
( [ + - /
– Statements before such chars must
have ;
Building Custom Object
frontColor = { } // create empty
object
frontColor.red = 255
frontColor.blue = 0
frontColor.green = 128
redComponent = frontColor.red
Object using
constructor
function Color ( r, g, b ) {
this.red = r
this.green = g;
this.blue = b
}
red = new Color(255, 0, 0)

Recommended for you

Development of Chatbot Using AI/ML Technologies
Development of  Chatbot Using AI/ML TechnologiesDevelopment of  Chatbot Using AI/ML Technologies
Development of Chatbot Using AI/ML Technologies

The rapid advancements in artificial intelligence and natural language processing have significantly transformed human-computer interactions. This thesis presents the design, development, and evaluation of an intelligent chatbot capable of engaging in natural and meaningful conversations with users. The chatbot leverages state-of-the-art deep learning techniques, including transformer-based architectures, to understand and generate human-like responses. Key contributions of this research include the implementation of a context- aware conversational model that can maintain coherent dialogue over extended interactions. The chatbot's performance is evaluated through both automated metrics and user studies, demonstrating its effectiveness in various applications such as customer service, mental health support, and educational assistance. Additionally, ethical considerations and potential biases in chatbot responses are examined to ensure the responsible deployment of this technology. The findings of this thesis highlight the potential of intelligent chatbots to enhance user experience and provide valuable insights for future developments in conversational AI.

thesischatbotai/ml
Rotary Intersection in traffic engineering.pptx
Rotary Intersection in traffic engineering.pptxRotary Intersection in traffic engineering.pptx
Rotary Intersection in traffic engineering.pptx

Very Important design

Bangalore @ℂall @Girls ꧁❤ 0000000000 ❤꧂@ℂall @Girls Service Vip Top Model Safe
Bangalore @ℂall @Girls ꧁❤ 0000000000 ❤꧂@ℂall @Girls Service Vip Top Model SafeBangalore @ℂall @Girls ꧁❤ 0000000000 ❤꧂@ℂall @Girls Service Vip Top Model Safe
Bangalore @ℂall @Girls ꧁❤ 0000000000 ❤꧂@ℂall @Girls Service Vip Top Model Safe

For Ad post Contact : adityaroy0215@gmail.com Bangalore @ℂall @Girls ꧁❤ 0000000000 ❤꧂@ℂall @Girls Service Vip Top Model Safe

Object Using
Constructor
function Color ( r, g, b ) {
this.red = r
this.green = g;
this.blue = b
}
myColor = { }
myColor.red // undefined
Color.apply( myColor, [255, 65,
127] )
Color.call( myColor, 255, 65, 127 )
myColor.red // 255
Bad Usage of
Constructor
function Color ( r, g, b ) {
this.red = r
this.green = g
this.blue = b
}
Color(255, 127, 65)
this.red // 255.. but what is “this”
here?
Immutable Object Using
Constructor
function Color ( r, g, b ) {
this.getRed = function( ) { return r };
this.getGreen = function() { return g };
this.getBlue = function() { return b };
}
red = new Color(255, 0, 0)
red.getRed( ) // 255
?? red.r = 128 // creates a new property r
red.getRed() // 255!
Closure
•Closure is an object having
–Function
–Environment when function was created
•Local Variables of outer function
•Local functions declared in outer function
•Parameters of outer function
•this and arguments of outer function are not
available but can be saved in local variables of
outer function and then used in inner function

Recommended for you

L-3536-Cost Benifit Analysis in ESIA.pptx
L-3536-Cost Benifit Analysis in ESIA.pptxL-3536-Cost Benifit Analysis in ESIA.pptx
L-3536-Cost Benifit Analysis in ESIA.pptx

..

PMSM-Motor-Control : A research about FOC
PMSM-Motor-Control : A research about FOCPMSM-Motor-Control : A research about FOC
PMSM-Motor-Control : A research about FOC

This is research about a process called field-oriented control (FOC) that is used to control the pmsm motor.

#pmsmfoc
Germany Offshore Wind 010724 RE (1) 2 test.pptx
Germany Offshore Wind 010724 RE (1) 2 test.pptxGermany Offshore Wind 010724 RE (1) 2 test.pptx
Germany Offshore Wind 010724 RE (1) 2 test.pptx

offshore wind

Property Attributes
•Value (Named Data Property)
–Default value
•Get and Set (Named Accessor Property)
–Getter and Setter function
–Either Value or Get/Set can be used, but not both
•Writable
–False => Read Only Property
•Enumerable
–False => Obj.keys or for (key in Obj) will not show
•Configurable
–False => delete obj.prop, or redefine will not work
Defining Property
function Color(r, g, b) {
Object.defineProperties( this,
{
red : {
value: r,
writable : false,
enumerable : true,
configurable: false
}, …
} ); }
Freezing an Object
Rubik = {};
Rubik.Slope = {};
Rubik.Slope.HORIZONTAL = "Horizontal";
Rubik.Slope.VERTICAL = "Vertical";
Rubik.Slope.SLANTED = "Slanted";
// Make Rubik.Slope immutable
Object.freeze(Rubik.Slope);
Object.defineProperty( Rubik, "Slope",
{ writable : false, enumerable : true,
configurable : false }
);
Sealing an Object
Object.seal(Rubik.Slope);
No new properties can be added.
Writable properties can be re-written.
Configurable properties can be re
configured.
Object.isSealed(Rubik.Slope) // true

Recommended for you

Social media management system project report.pdf
Social media management system project report.pdfSocial media management system project report.pdf
Social media management system project report.pdf

The project "Social Media Platform in Object-Oriented Modeling" aims to design and model a robust and scalable social media platform using object-oriented modeling principles. In the age of digital communication, social media platforms have become indispensable for connecting people, sharing content, and fostering online communities. However, their complex nature requires meticulous planning and organization.This project addresses the challenge of creating a feature-rich and user-friendly social media platform by applying key object-oriented modeling concepts. It entails the identification and definition of essential objects such as "User," "Post," "Comment," and "Notification," each encapsulating specific attributes and behaviors. Relationships between these objects, such as friendships, content interactions, and notifications, are meticulously established.The project emphasizes encapsulation to maintain data integrity, inheritance for shared behaviors among objects, and polymorphism for flexible content handling. Use case diagrams depict user interactions, while sequence diagrams showcase the flow of interactions during critical scenarios. Class diagrams provide an overarching view of the system's architecture, including classes, attributes, and methods .By undertaking this project, we aim to create a modular, maintainable, and user-centric social media platform that adheres to best practices in object-oriented modeling. Such a platform will offer users a seamless and secure online social experience while facilitating future enhancements and adaptability to changing user needs.

computer technologycomputer scienceproject management
Introduction to IP address concept - Computer Networking
Introduction to IP address concept - Computer NetworkingIntroduction to IP address concept - Computer Networking
Introduction to IP address concept - Computer Networking

An Internet Protocol address (IP address) is a logical numeric address that is assigned to every single computer, printer, switch, router, tablets, smartphones or any other device that is part of a TCP/IP-based network. Types of IP address- Dynamic means "constantly changing “ .dynamic IP addresses aren't more powerful, but they can change. Static means staying the same. Static. Stand. Stable. Yes, static IP addresses don't change. Most IP addresses assigned today by Internet Service Providers are dynamic IP addresses. It's more cost effective for the ISP and you.

networkinginternetcommunication
ES 6 (Harmony) Features
• Block Scoping: let and const
• Destructuring
– [a, b] = [b, a]
• Default Parameter
• Rest and spread parameters
– function(p1, ...restAllParams)
– calling(p1,
...restAllParamsInArray)
• Module Rubik { export function ..}
• Import MyRubik as Rubik
• Class, extends and super
Code Walkthrough
Model Rubik’s Cube
with
Objects
Next step..
• DOM
• JQuery
• Java Script Design Patterns
• Coding Style/Documentation
• Books to read:
– JavaScript – The Good Parts
– Effective JavaScript
Q & A
• Source Code
– GitHub
• This presentation is available on SVCC
•
•
• kr_manoj@yahoo.com

Recommended for you

Many Variables in one
declaration
function X () {
var a = 5,
b = 6
var c = 7, d=8
alert ( "a=" + a + ", b=" + b + ",
c=" + c)
}
X()
//alert ( "a=" + a + ", b=" + b + ",
c=" + c)
Spot the mistake!
function X () {
var a = 5
b = 6
var c = 7
alert ( "a=" + a + ", b=" + this.b + ",
c=" + c)
}
X()
//alert ( "a=" + a + ", b=" + b + ", c=" +
c)
alert ( "b=" + window.b)
Spot the mistake!
function X () {
var a = 5,
b = 6
var c = 7
alert ( "a=" + a + ", b=" + this.b + ",
c=" + c)
}
X()
//alert ( "a=" + a + ", b=" + b + ", c=" +
c)
alert ( "b=" + window.b)
Constants in JavaScript
"use strict";
Object.defineProperty(this, "PI", {
value : 3.14,
writable : false,
enumerable : true,
configurable : false
});
PI = 7 // TypeError: "PI" is read-only

Recommended for you

Constants in JavaScript
"use strict";
var MyConst = { }
MyConst.PI = 3.14
Object.freeze(MyConst)
MyConst.PI = 8 //TypeError: "PI" is read-
only
Rubik’s Cube
•Cube
–Mini Cube/Cubelet/Atom
•Corner (8)
•Edge (12)
•Center (6)
–Sides/Layer
•Front/Back/Left/Right/Up/Down
Naming Atoms
•Corner: RFU
–Right, Front, Up corner
–RFU, FRU, URF … refers to same corner
•Edge : RF
–Middle cubelet of the edge shared by Right
and Front layers
•Center: R
–Center of the right layer
Moves
•R => right layer 90 deg clockwise
looking from right
•R’ => right layer 90 deg anticlockwise
looking from right
•R2 => right layer 180 deg
•RRRR, RR’, R2R2 =>No change
•(XY)’ = Y’X’

Recommended for you

Effect of a Move
•Rotating front layer clockwise
( F) ==>
[ fru -> fdr -> fld -> ful -> fru ]
[ fr -> fd -> fl -> fu -> fr ]
•FRU ->FDR
–Corner FRU has moved to FDR
–Right side color of FRU has gone to Down side of
FDR
Useful Moves
•Moves that produce the minimal
disturbance
•One cycle of 3 corners (Placement)
•Rotating corners (Orientation)
•One cycle of 3 edges (Placement)
•In-place flipping edges (Orientation)
Basic Corners Moves
•One cycle of 3 corners
–(R'D'LD RD'L'D) => [ fru -> drf -> ful -> fru ]
–(RF'L'F R'F'LF) => [ fru -> lfu -> drf -> fru ]
•Rotate corner at its own place
(R'D'LD RD'L'D RF'L'FR'F'LF) ==>
[ dfr -> rdf ]
[ flu -> luf ]
Basic Edges Moves
•One cycle of 3 edges
(V'F2VF2) ==> [ fu -> bu -> fd -> fu
]
(V'F'VFFV'F'V) ==> [ fr -> fl -> df -> fr ]
•Flipping edges in its own positions
(RFBU2F2U'FUFU2B'R'F') ==>
[ fr -> rf ]
[ fu -> uf ]

Recommended for you

Cube Representation
•Cube
•Atom
–Corner
–Edge
–Center
•Side
•Move
•MoveSequence
•MoveFinder
Built-in Objects
•Object
•Function
•Array
•String
•Boolean
•Number
•Math, Date, RegExp, JSON, Error
objects
Call and Apply
•add(4, 5, 2 ,3)
•add.call(null, 4, 5, 2, 3)
•add.apply(null, [4, 5, 2, 3])
•add.apply(undefined, [4, 5, 2, 3])
Variables
•No need to declare a variable
sum = 5
• Local Variables
var sum = 0;
•Declaring many variables in one declaration
var sum = 0, average = 0, stddev = 0;
•Always use semicolon OR know the rules
precisely

Recommended for you

Object
•Collection of properties
•Property (optional)
–primitive value
–function
–other object
•Prototype (optional)
–To share property from others
Literal Object
frontColor = {
red : 255
blue : 0
green : 128
}
redComponent = frontColor.red
greenComponent = frontColor [ “green”
]
Immutable Object
function makeColor ( r, g, b ) {
return {
getRed : function( ) { return r },
getGreen : function() { return g },
getBlue : function() { return b }
}
}
color1 = makeColor(255, 0, 0)
color1.getRed( ) // 255
color1.getGreen() // 0
color1.blue = 128 // red has no property called blue!
Error!
Arrow Functions
( ( ) => 5 ) ( ) === 5;
var b = x => x + " Arrow";
b("Hello") === "Hello Arrow"
var d = { x : "AB",
y : function() { return z => this.x +
z; }
}.y();
d( "CD" ) === "ABCD"
var e = { x : "XX", y : d };

Recommended for you

Promise
let promise = new Promise(
function(resolve,
reject) {
console.log(“1");
resolve();});
promise.then(function() {
console.log(“3");});
console.log(“2”);
You actually don't understand a
concept.
You just get used to it!
And you brain makes you believe
you got it!
Very important for our
technical/mental health.
References
• ECMAScript Support Matrix
– http://pointedears.de/scripts/test/es-matrix/
• http://www.slideshare.net/Solution4Future/javascript-17363650
• https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
•
• https://code.google.com/p/traceur-compiler/wiki/L
•

Recommended for you

ES6 PPT FOR 2016

More Related Content

What's hot

Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
Erik van Appeldoorn
 
Java script errors &amp; exceptions handling
Java script  errors &amp; exceptions handlingJava script  errors &amp; exceptions handling
Java script errors &amp; exceptions handling
AbhishekMondal42
 
React Router: React Meetup XXL
React Router: React Meetup XXLReact Router: React Meetup XXL
React Router: React Meetup XXL
Rob Gietema
 
Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
Arvind Devaraj
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
Computer Hardware & Trouble shooting
 
PHP MVC
PHP MVCPHP MVC
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
Sehwan Noh
 
炎炎夏日學 Android 課程 - Part1: Kotlin 語法介紹
炎炎夏日學 Android 課程 -  Part1: Kotlin 語法介紹炎炎夏日學 Android 課程 -  Part1: Kotlin 語法介紹
炎炎夏日學 Android 課程 - Part1: Kotlin 語法介紹
Johnny Sung
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
Bui Kiet
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
Bedis ElAchèche
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPM
Bhargav Anadkat
 
Express js
Express jsExpress js
Express js
Manav Prasad
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
Joseph de Castelnau
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
async_io
 
JQuery UI
JQuery UIJQuery UI
JQuery UI
Gary Yeh
 
Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction
Kanika Gera
 
Node.js Express Framework
Node.js Express FrameworkNode.js Express Framework
Node.js Express Framework
TheCreativedev Blog
 
Creating Single Page Applications with Oracle Apex
Creating Single Page Applications with Oracle ApexCreating Single Page Applications with Oracle Apex
Creating Single Page Applications with Oracle Apex
Dick Dral
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
Vineet Kumar Saini
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
boyney123
 

What's hot (20)

Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
Java script errors &amp; exceptions handling
Java script  errors &amp; exceptions handlingJava script  errors &amp; exceptions handling
Java script errors &amp; exceptions handling
 
React Router: React Meetup XXL
React Router: React Meetup XXLReact Router: React Meetup XXL
React Router: React Meetup XXL
 
Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 
PHP MVC
PHP MVCPHP MVC
PHP MVC
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
炎炎夏日學 Android 課程 - Part1: Kotlin 語法介紹
炎炎夏日學 Android 課程 -  Part1: Kotlin 語法介紹炎炎夏日學 Android 課程 -  Part1: Kotlin 語法介紹
炎炎夏日學 Android 課程 - Part1: Kotlin 語法介紹
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPM
 
Express js
Express jsExpress js
Express js
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
 
JQuery UI
JQuery UIJQuery UI
JQuery UI
 
Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction
 
Node.js Express Framework
Node.js Express FrameworkNode.js Express Framework
Node.js Express Framework
 
Creating Single Page Applications with Oracle Apex
Creating Single Page Applications with Oracle ApexCreating Single Page Applications with Oracle Apex
Creating Single Page Applications with Oracle Apex
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
 

Viewers also liked

JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
Solution4Future
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
Domenic Denicola
 
ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
Domenic Denicola
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
hesher
 
Fat Arrow (ES6)
Fat Arrow (ES6)Fat Arrow (ES6)
Fat Arrow (ES6)
Ryan Ewing
 
Angular2
Angular2Angular2
ES6: The future is now
ES6: The future is nowES6: The future is now
ES6: The future is now
Sebastiano Armeli
 
VueJs 簡介
VueJs 簡介VueJs 簡介
VueJs 簡介
Jocelyn Hsu
 
Building a Great Engineering Culture
Building a Great Engineering CultureBuilding a Great Engineering Culture
Building a Great Engineering Culture
Simon Guest
 
[朝陽科大] D3.js 資料視覺化入門
[朝陽科大] D3.js 資料視覺化入門 [朝陽科大] D3.js 資料視覺化入門
[朝陽科大] D3.js 資料視覺化入門
Kuro Hsu
 
Vue js 大型專案架構
Vue js 大型專案架構Vue js 大型專案架構
Vue js 大型專案架構
Hina Chen
 
Vue 2.0 + Vuex Router & Vuex at Vue.js
Vue 2.0 + Vuex Router & Vuex at Vue.jsVue 2.0 + Vuex Router & Vuex at Vue.js
Vue 2.0 + Vuex Router & Vuex at Vue.js
Takuya Tejima
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
Cory Forsyth
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2
Knoldus Inc.
 
第一次用 Vue.js 就愛上 [改]
第一次用 Vue.js 就愛上 [改]第一次用 Vue.js 就愛上 [改]
第一次用 Vue.js 就愛上 [改]
Kuro Hsu
 
Free Download Powerpoint Slides
Free Download Powerpoint SlidesFree Download Powerpoint Slides
Free Download Powerpoint Slides
George
 
The Art of AngularJS in 2015
The Art of AngularJS in 2015The Art of AngularJS in 2015
The Art of AngularJS in 2015
Matt Raible
 

Viewers also liked (17)

JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
 
Fat Arrow (ES6)
Fat Arrow (ES6)Fat Arrow (ES6)
Fat Arrow (ES6)
 
Angular2
Angular2Angular2
Angular2
 
ES6: The future is now
ES6: The future is nowES6: The future is now
ES6: The future is now
 
VueJs 簡介
VueJs 簡介VueJs 簡介
VueJs 簡介
 
Building a Great Engineering Culture
Building a Great Engineering CultureBuilding a Great Engineering Culture
Building a Great Engineering Culture
 
[朝陽科大] D3.js 資料視覺化入門
[朝陽科大] D3.js 資料視覺化入門 [朝陽科大] D3.js 資料視覺化入門
[朝陽科大] D3.js 資料視覺化入門
 
Vue js 大型專案架構
Vue js 大型專案架構Vue js 大型專案架構
Vue js 大型專案架構
 
Vue 2.0 + Vuex Router & Vuex at Vue.js
Vue 2.0 + Vuex Router & Vuex at Vue.jsVue 2.0 + Vuex Router & Vuex at Vue.js
Vue 2.0 + Vuex Router & Vuex at Vue.js
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2
 
第一次用 Vue.js 就愛上 [改]
第一次用 Vue.js 就愛上 [改]第一次用 Vue.js 就愛上 [改]
第一次用 Vue.js 就愛上 [改]
 
Free Download Powerpoint Slides
Free Download Powerpoint SlidesFree Download Powerpoint Slides
Free Download Powerpoint Slides
 
The Art of AngularJS in 2015
The Art of AngularJS in 2015The Art of AngularJS in 2015
The Art of AngularJS in 2015
 

Similar to ES6 PPT FOR 2016

EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
Manoj Kumar
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
Giovanni Scerra ☃
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
Stoyan Stefanov
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
Binary Studio
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
Chris Saylor
 
Javascript
JavascriptJavascript
Javascript
Vlad Ifrim
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
Visual Engineering
 
Introduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy Cresine
Movel
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
Zsolt Mészárovics
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
Bruno Scopelliti
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
Seri Moth
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
Richard Paul
 
Composition in JavaScript
Composition in JavaScriptComposition in JavaScript
Composition in JavaScript
Josh Mock
 
Exploring ES6
Exploring ES6Exploring ES6
Exploring ES6
Ximing Dai
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
RameshNair6
 
ES6: Features + Rails
ES6: Features + RailsES6: Features + Rails
ES6: Features + Rails
Santosh Wadghule
 
ES6 generators
ES6 generatorsES6 generators
ES6 generators
Steven Foote
 

Similar to ES6 PPT FOR 2016 (20)

EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 
Javascript
JavascriptJavascript
Javascript
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
Introduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy Cresine
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
 
Composition in JavaScript
Composition in JavaScriptComposition in JavaScript
Composition in JavaScript
 
Exploring ES6
Exploring ES6Exploring ES6
Exploring ES6
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
ES6: Features + Rails
ES6: Features + RailsES6: Features + Rails
ES6: Features + Rails
 
ES6 generators
ES6 generatorsES6 generators
ES6 generators
 

Recently uploaded

CCS367-STORAGE TECHNOLOGIES QUESTION BANK.doc
CCS367-STORAGE TECHNOLOGIES QUESTION BANK.docCCS367-STORAGE TECHNOLOGIES QUESTION BANK.doc
CCS367-STORAGE TECHNOLOGIES QUESTION BANK.doc
Dss
 
Best Practices of Clothing Businesses in Talavera, Nueva Ecija, A Foundation ...
Best Practices of Clothing Businesses in Talavera, Nueva Ecija, A Foundation ...Best Practices of Clothing Businesses in Talavera, Nueva Ecija, A Foundation ...
Best Practices of Clothing Businesses in Talavera, Nueva Ecija, A Foundation ...
IJAEMSJORNAL
 
21EC63_Module1B.pptx VLSI design 21ec63 MOS TRANSISTOR THEORY
21EC63_Module1B.pptx VLSI design 21ec63 MOS TRANSISTOR THEORY21EC63_Module1B.pptx VLSI design 21ec63 MOS TRANSISTOR THEORY
21EC63_Module1B.pptx VLSI design 21ec63 MOS TRANSISTOR THEORY
PradeepKumarSK3
 
Quadcopter Dynamics, Stability and Control
Quadcopter Dynamics, Stability and ControlQuadcopter Dynamics, Stability and Control
Quadcopter Dynamics, Stability and Control
Blesson Easo Varghese
 
Chlorine and Nitric Acid application, properties, impacts.pptx
Chlorine and Nitric Acid application, properties, impacts.pptxChlorine and Nitric Acid application, properties, impacts.pptx
Chlorine and Nitric Acid application, properties, impacts.pptx
yadavsuyash008
 
Trends in Computer Aided Design and MFG.
Trends in Computer Aided Design and MFG.Trends in Computer Aided Design and MFG.
Trends in Computer Aided Design and MFG.
Tool and Die Tech
 
Exploring Deep Learning Models for Image Recognition: A Comparative Review
Exploring Deep Learning Models for Image Recognition: A Comparative ReviewExploring Deep Learning Models for Image Recognition: A Comparative Review
Exploring Deep Learning Models for Image Recognition: A Comparative Review
sipij
 
Vernier Caliper and How to use Vernier Caliper.ppsx
Vernier Caliper and How to use Vernier Caliper.ppsxVernier Caliper and How to use Vernier Caliper.ppsx
Vernier Caliper and How to use Vernier Caliper.ppsx
Tool and Die Tech
 
IWISS Catalog 2024
IWISS Catalog 2024IWISS Catalog 2024
IWISS Catalog 2024
Iwiss Tools Co.,Ltd
 
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
sharvaridhokte
 
UNIT I INCEPTION OF INFORMATION DESIGN 20CDE09-ID
UNIT I INCEPTION OF INFORMATION DESIGN 20CDE09-IDUNIT I INCEPTION OF INFORMATION DESIGN 20CDE09-ID
UNIT I INCEPTION OF INFORMATION DESIGN 20CDE09-ID
GOWSIKRAJA PALANISAMY
 
Evento anual Splunk .conf24 Highlights recap
Evento anual Splunk .conf24 Highlights recapEvento anual Splunk .conf24 Highlights recap
Evento anual Splunk .conf24 Highlights recap
Rafael Santos
 
Development of Chatbot Using AI/ML Technologies
Development of  Chatbot Using AI/ML TechnologiesDevelopment of  Chatbot Using AI/ML Technologies
Development of Chatbot Using AI/ML Technologies
maisnampibarel
 
Rotary Intersection in traffic engineering.pptx
Rotary Intersection in traffic engineering.pptxRotary Intersection in traffic engineering.pptx
Rotary Intersection in traffic engineering.pptx
surekha1287
 
Bangalore @ℂall @Girls ꧁❤ 0000000000 ❤꧂@ℂall @Girls Service Vip Top Model Safe
Bangalore @ℂall @Girls ꧁❤ 0000000000 ❤꧂@ℂall @Girls Service Vip Top Model SafeBangalore @ℂall @Girls ꧁❤ 0000000000 ❤꧂@ℂall @Girls Service Vip Top Model Safe
Bangalore @ℂall @Girls ꧁❤ 0000000000 ❤꧂@ℂall @Girls Service Vip Top Model Safe
bookhotbebes1
 
L-3536-Cost Benifit Analysis in ESIA.pptx
L-3536-Cost Benifit Analysis in ESIA.pptxL-3536-Cost Benifit Analysis in ESIA.pptx
L-3536-Cost Benifit Analysis in ESIA.pptx
naseki5964
 
PMSM-Motor-Control : A research about FOC
PMSM-Motor-Control : A research about FOCPMSM-Motor-Control : A research about FOC
PMSM-Motor-Control : A research about FOC
itssurajthakur06
 
Germany Offshore Wind 010724 RE (1) 2 test.pptx
Germany Offshore Wind 010724 RE (1) 2 test.pptxGermany Offshore Wind 010724 RE (1) 2 test.pptx
Germany Offshore Wind 010724 RE (1) 2 test.pptx
rebecca841358
 
Social media management system project report.pdf
Social media management system project report.pdfSocial media management system project report.pdf
Social media management system project report.pdf
Kamal Acharya
 
Introduction to IP address concept - Computer Networking
Introduction to IP address concept - Computer NetworkingIntroduction to IP address concept - Computer Networking
Introduction to IP address concept - Computer Networking
Md.Shohel Rana ( M.Sc in CSE Khulna University of Engineering & Technology (KUET))
 

Recently uploaded (20)

CCS367-STORAGE TECHNOLOGIES QUESTION BANK.doc
CCS367-STORAGE TECHNOLOGIES QUESTION BANK.docCCS367-STORAGE TECHNOLOGIES QUESTION BANK.doc
CCS367-STORAGE TECHNOLOGIES QUESTION BANK.doc
 
Best Practices of Clothing Businesses in Talavera, Nueva Ecija, A Foundation ...
Best Practices of Clothing Businesses in Talavera, Nueva Ecija, A Foundation ...Best Practices of Clothing Businesses in Talavera, Nueva Ecija, A Foundation ...
Best Practices of Clothing Businesses in Talavera, Nueva Ecija, A Foundation ...
 
21EC63_Module1B.pptx VLSI design 21ec63 MOS TRANSISTOR THEORY
21EC63_Module1B.pptx VLSI design 21ec63 MOS TRANSISTOR THEORY21EC63_Module1B.pptx VLSI design 21ec63 MOS TRANSISTOR THEORY
21EC63_Module1B.pptx VLSI design 21ec63 MOS TRANSISTOR THEORY
 
Quadcopter Dynamics, Stability and Control
Quadcopter Dynamics, Stability and ControlQuadcopter Dynamics, Stability and Control
Quadcopter Dynamics, Stability and Control
 
Chlorine and Nitric Acid application, properties, impacts.pptx
Chlorine and Nitric Acid application, properties, impacts.pptxChlorine and Nitric Acid application, properties, impacts.pptx
Chlorine and Nitric Acid application, properties, impacts.pptx
 
Trends in Computer Aided Design and MFG.
Trends in Computer Aided Design and MFG.Trends in Computer Aided Design and MFG.
Trends in Computer Aided Design and MFG.
 
Exploring Deep Learning Models for Image Recognition: A Comparative Review
Exploring Deep Learning Models for Image Recognition: A Comparative ReviewExploring Deep Learning Models for Image Recognition: A Comparative Review
Exploring Deep Learning Models for Image Recognition: A Comparative Review
 
Vernier Caliper and How to use Vernier Caliper.ppsx
Vernier Caliper and How to use Vernier Caliper.ppsxVernier Caliper and How to use Vernier Caliper.ppsx
Vernier Caliper and How to use Vernier Caliper.ppsx
 
IWISS Catalog 2024
IWISS Catalog 2024IWISS Catalog 2024
IWISS Catalog 2024
 
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
 
UNIT I INCEPTION OF INFORMATION DESIGN 20CDE09-ID
UNIT I INCEPTION OF INFORMATION DESIGN 20CDE09-IDUNIT I INCEPTION OF INFORMATION DESIGN 20CDE09-ID
UNIT I INCEPTION OF INFORMATION DESIGN 20CDE09-ID
 
Evento anual Splunk .conf24 Highlights recap
Evento anual Splunk .conf24 Highlights recapEvento anual Splunk .conf24 Highlights recap
Evento anual Splunk .conf24 Highlights recap
 
Development of Chatbot Using AI/ML Technologies
Development of  Chatbot Using AI/ML TechnologiesDevelopment of  Chatbot Using AI/ML Technologies
Development of Chatbot Using AI/ML Technologies
 
Rotary Intersection in traffic engineering.pptx
Rotary Intersection in traffic engineering.pptxRotary Intersection in traffic engineering.pptx
Rotary Intersection in traffic engineering.pptx
 
Bangalore @ℂall @Girls ꧁❤ 0000000000 ❤꧂@ℂall @Girls Service Vip Top Model Safe
Bangalore @ℂall @Girls ꧁❤ 0000000000 ❤꧂@ℂall @Girls Service Vip Top Model SafeBangalore @ℂall @Girls ꧁❤ 0000000000 ❤꧂@ℂall @Girls Service Vip Top Model Safe
Bangalore @ℂall @Girls ꧁❤ 0000000000 ❤꧂@ℂall @Girls Service Vip Top Model Safe
 
L-3536-Cost Benifit Analysis in ESIA.pptx
L-3536-Cost Benifit Analysis in ESIA.pptxL-3536-Cost Benifit Analysis in ESIA.pptx
L-3536-Cost Benifit Analysis in ESIA.pptx
 
PMSM-Motor-Control : A research about FOC
PMSM-Motor-Control : A research about FOCPMSM-Motor-Control : A research about FOC
PMSM-Motor-Control : A research about FOC
 
Germany Offshore Wind 010724 RE (1) 2 test.pptx
Germany Offshore Wind 010724 RE (1) 2 test.pptxGermany Offshore Wind 010724 RE (1) 2 test.pptx
Germany Offshore Wind 010724 RE (1) 2 test.pptx
 
Social media management system project report.pdf
Social media management system project report.pdfSocial media management system project report.pdf
Social media management system project report.pdf
 
Introduction to IP address concept - Computer Networking
Introduction to IP address concept - Computer NetworkingIntroduction to IP address concept - Computer Networking
Introduction to IP address concept - Computer Networking
 

ES6 PPT FOR 2016

  • 1. Silicon Valley Code Camp Amazing New Features In JavaScript Manoj Kumar
  • 2. Agenda •Scope of Variables •Parameters: default/rest/spread •Destructuring •Object Literals •Arrow functions •Iterators & Generators •Promises & Proxies
  • 3. Scope of a Variable (ES5) var x = 1 // global variable, a property in global obj b = 2 // global variable, a property in global obj function f() { a = b + 6 // “a” is a global variable, what about b? var b = 7; // b is local to this function // declaration is hoisted but not the assignment }
  • 4. Scope of a Variable (ES 6) function f() { var a = 7; // local to function f let c = 8; // local to function f If ( a > 5) { var b = 9 + c; // Visible anywhere in the function let x = 1; // local to this IF block const pi = 3.14; // constant and local to IF block // redefining is not allowed const obj = { x:9, y:10 }; // obj.x is still
  • 5. const const pi1; // error: Missing initialization const pi2 = 3.14159 ; // works! pi2 = 3.14 ; // error: can't change the value for( let i = 5;....) { const c = i * 9; // const can get a fresh value inside loop in different iteration
  • 6. Temporal Dead Zone Let x = 6; If ( true ) { // new block scope so TDZ starts console.log(x) ; // reference error (outer x not visible) x = 5; // reference error let x; // now x can be referenced console.log(x); // undefined x = 6; console.log(x); // 6 }
  • 7. Temporal => Time If ( true ) { // new block scope so TDZ starts const func1 = function () { Console.log(x); }; console.log(x) ; // still inside TDZ, so reference error let x = 8; func1(); // inside this call “let x” is effective }
  • 8. Default Parameter Value function f(x = 0, y = 0) { } f(); // 0,0 f(5); // 5,0 f(5, someVarUndefined); // 5,0 f(undefined, 6); // 0, 6 f(5,6); // 5,6 Function(x, y=x) { } //OK Function (x=y, y=5) { } // y is not available to use (TDZ)
  • 9. Rest of the Parameters function func(x, y, ...others) { //others[0..n] contains rest of the parameters } func(5,6); // 5,6, others.length==0 func(5,6, 7); // 5,6, others.length==1, others[0] === 7 Func(5,6, 7,8,9); // 5,6, others.length==3, others[0..2] are 7,8,9
  • 10. Spread Operator Math.max(2, 5, 6, 8); Math.max( …[2, 5, 6, 8] ) Same as Math.max.apply(null, [2,5,6,8]) [1, ...[2,3], 4] => [1, 2, 3, 4]
  • 11. Destructuring let [x, y] = [5, 8]; // x === 5, y ===8 var [a, , [b], c] = [5, null, [6]]; // a === 5 && b === 6 && c === undefined [a, b] = [b, a] var [a, b, c] = "xy"; // think “xy” as [“x”, “y”] // a === "x" && b === "y" && c === undefined
  • 12. Destructuring { first: f, last: l } = { first: 'Manoj', last: 'Kumar' } // f === 'Manoj' && l === 'Kumar' let { x: x } = { x: 1, y: 2 }; // x = 1 let [ x, ...y ] = 'abc'; // x = 'a'; y = [ 'b', 'c' ] let [ x, y ] = new Set( [ 'a', 'b' ] ); // x = 'a'; y = 'b’; [ ] = { }; // TypeError, empty objects are not iterable [ ] = undefined; // TypeError, not iterable [ ] = null; // TypeError, not iterable let [x] = [ ]; // x = undefined
  • 13. Object Literals obj = { red : 255, blue : 127, [ “green” ] : 255 }; red = 255; blue = 127; green = 255; obj = { red : red, blue : blue, green: green }; obj = { red, blue, green } // ES 6
  • 14. Computed Property let prop = "red"; green = 255; obj = { [ prop ] : 255, // [“red”] : 255 or red : 255 [ "b" + "lue" ] : 127, green }; <eot/>
  • 15. Arrow Functions ● New way of creating functions ● function square( x ) { // ES 5 function ● return x * x; ● } x => x * x ; // Arrow function (x, y) => x + y ; ( ) => 5; (x, y) => { f(x,y); return x + y; } x => { a:x+1, b:x+2}; // wrong! { means block x => ({ a:x+1, b:x+2 });
  • 16. Arrow Functions vs Normal Functions 1. Following constructs are lexical ● Arguments ● this ● super ● new.target (target object of new, null in normal functions) 2. Cannot be used as constructor new ( () => { } ) throws an error
  • 17. Symbol obj.red = 255; obj[“red”] === 255; // ES5 const my_prop = Symbol(); // ES6 obj[my_prop] = 127; // ES6 Obj = { [my_prop] : 127 }; const red = Symbol('my_red') red.toString() === 'Symbol(my_red)' Symbol() != Symbol() Symbol( 'red' ) != Symbol( 'red' )
  • 18. Symbol (Global Registry) const globalRedProp = Symbol.for( 'red'); globalRedProp.toString() === 'Symbol(red)'; Symbol.for ( 'red' ) === globalRedProp Symbol.keyFor( globalRedProp ) === 'red' Symbol.for( 'red' ) === Symbol.for( 'red' ) Symbol( 'red' ) != Symbol( 'red' ) Built-in symbols: Symbol.iterator Symbol.match (=== String.prototype.match )
  • 19. Iterators Iterable object makes its element accessible in for-of loops and spread operators for (let x of ['a', 'b', 'c']) { // arrays are iterable console.log(x); } Iterable Objects: ● Arrays ● Strings ● Maps ● Sets ●
  • 20. Iterable How to make any object iterable? ● Implement a method Symbol.iterator ● That returns Iterator object IterableObject = { [Symbol.iterator] ( ) { // create an iterator object and return } }
  • 21. Iterator Iteartor = { next () { // keep returning IteratorResult in successive calls } } IteratorResult = { value : // current value done: // false, but at the end true }
  • 22. let iterable = { [Symbol.iterator]() { let step = 0; let iterator = { next() { if (step <= 2) step++; switch (step) { case 1: return { value: 'hello', done: false }; case 2: return { value: 'world', done: false }; default: return { value: undefined, done: true }; } } }; return iterator; }
  • 23. Iterable Let iterator = iterable [ Symbol.iterator ] ( ) ; Iterator.next() === { value : 'hello', done: false } Iterator.next() === { value : 'world', done: false } Iterator.next() === { value : undefined, done: true } While (true) { let result = iterator.next(); if ( result.done ) break;
  • 24. Iterable in for-of for (let x of iterable) { console.log(x); } for ( let [k,v] of map) for ( let x of Array.from(arrayLike)) //length, 0:, 1:.. for ( let [k,v] of array.entries())
  • 25. Generator function * simpleGenFunc () { yield 'hello'; yield 'world'; } Iterator = simpleGenFunc (); Iterator.next ( ) ; // { value: “hello”, done: false } Iterator.next ( ); // { value: “world”, done: false } Iterator.next ( ); // { value: undefined, done: true } for ( x of simpleGenFunc () ) {
  • 26. Generator let arr = [ ...simpleGenFunc ( ) ]; // [ 'hello', 'world'] let [ x, y ] = simpleGenFunc ( ); x === 'hello' y === 'world'
  • 27. Generator Generators are ● Data Producers (as iterator) ● Data Consumer (Yield can get data from next()) ● Communicating sequential tasks..
  • 28. function * genFunc () { try { let hint = yield 'hello'; // do something with hint yield 'world'; } finally { // Do some cleanup here } } Iterator = genFunc(); Iterator.next(); // gives hello Iterator.next(“stop”); // gives 'world', hint === “stop” Iterator.next(); // cleanup code executes,
  • 29. Promise setTimeout( function() { console.log("timeout!");}, delay ); promise = timeout(delay) ; promise.then( function(result) { console.log("Result: " + result);} );
  • 30. Promise function timeout(delay) { return new Promise( function(resolve, reject) { setTimeout( function() { resolve(); }, delay); }); } promise = timeout(delay) ; promise.then( function(result) {….} );
  • 31. Promise let promise = someAsyncOp() ; promise.then ( function (result) { console.log(“Result: “ + result); }, function (err) { console.log(“Failed: “ + err); } )
  • 32. Promise promise.then ( null, function (err) { console.log(“Failed: “ + err); }); promise.catch(function (err) { console.log(“Failed: “ + err); } );
  • 33. Promise • Life Cycle – Unsettled Promise • State: PENDING – Settled Promise • State: FULFILLED • State: REJECTED – – promise.then ( fulfilledCaseCallback, rejectedCaseCallBack); – promise.then(fulfilledCaseCallback); – promse.catch(rejectedCaseCallback);
  • 34. Promise Chaining promise.then ( fulfillmentFunction1 ) .then ( fulfillmentFunction2 ); promise2 = promise.then ( fulfillmentFunction1 ) promise2.then ( fulfillmentFunction2 );
  • 35. Promise Promise.all([promise1, promise2]) .then(function(results) { // Both resolved }) .catch(function(error) { // One rejected });
  • 36. Promise Promise.race([promise1, promise2]) .then(function(results) { // one got resolved }) .catch(function(error) { // First settlement was in rejection }); <eot/>
  • 37. Proxy Let proxy = new Proxy( target, handler ); Handler: Object with one or more traps Traps: – Get – Set – Has – deleteProperty – defineProperty
  • 38. Proxy More Traps: – isExtensible – preventExtensions – getPrototypeOf – setPrototypeOf – ownKeys – apply (calling a function) – Construct (using new) – –
  • 39. let target = { name: "smartObject" }; let proxy = new Proxy(target, { set(trapTarget, key, value, receiver) { if (isNaN(value)) { throw new TypeError("Property must be a number."); } return Reflect.set(trapTarget, key, value, receiver); } }); proxy.count = 1; // numeric properties are okay proxy.color = "red"; // throws exception <eot/>
  • 40. References • ecmascript 6 compatibility table – https://kangax.github.io/compat-table/es6/ • http://exploringjs.com/es6/index.html – Thanks to the author for tons of examples! • leanpub.com/understandinges6 • JavaScript: The Good Parts – Douglas Crockford • Effective JavaScript
  • 41. Thank You! Please provide your feedback :) Feedback from earlier sessions: Speaker started with the concepts that were way too simple and then at the end it became way too complex.
  • 43. Slides from Older Presentations •You may not find things in sequence in rest of the slides
  • 44. ES5 Equiv of Class function Cube(size) { this.size = size; } Cube.prototype.rotate = function (direction) { // rotate the cube; }; Let simpleCube = new Cube(3); simpleCube.size === 3 simpleCube.rorate(“left”);
  • 45. ES 6 Class class Cube { constructor (size) { this.size = size; } rotate(direction) { // rotate the cube } } let simpleCube = new Cube(3); simpleCube.size === 3 simpleCube.rorate(“left”);
  • 46. Derived Class class RubiksCube extends Cube { constructor (size, colors) { super(size); this.colors = colors; } solve() { // solve the cube } }
  • 47. Derived Class class RubiksCube extends Cube { constructor (size, colors) { super(size); this.colors = colors; } solve() { // solve the cube } }
  • 48. class BinaryTree { constructor(value, left=null, right=null) { this.value = value; this.left = left; this.right = right; } * [ Symbol.iterator ] ( ) { yield this.value; If ( this.left ) { yield* this.left; } If ( this.right ) { yield* this.right; } } }
  • 49. let tree = new BinaryTree( 'a', new BinaryTree( 'b', new BinaryTree('c'), new BinaryTree('d')), new BinaryTree('e')); for (let x of tree) { console.log(x); } // Output: // a // b // c // d // e
  • 50. Module A JavaScript file is a module One module is only one JavaScript file Export entities in the module where declared Import entities from a module in a module
  • 51. Module //------ lib.js ------ export function square (x) { return x * x; } export function diag (x, y) { return sqrt(square(x) + square(y)); } export const sqrt = Math.sqrt; //------ main.js ------ import { square, diag } from 'lib'; console.log(square(11)); // 121 console.log(diag(4, 3)); // 5
  • 52. Module import * as mylib from 'lib'; console.log ( mylib.square(11) ); // 121 console.log ( mylib.diag(4, 3) ); // 5 Imports are hoisted Cyclic dependency is supported Re-export some imported entities ● Export * from lib ● Export { square as num_square, diag } from lib
  • 53. Scope •ES5 – Function Scope – Global Scope – var keyword • ES6 – Block scope – let and const keywords
  • 54. Scope of a Variable (ES 6)●
  • 55. New Features (1) •Arrow Function •Classes •Enhanced object literals •Template strings •Destructuring •Default, rest, spread •Let, const •Iterators, for..of •Generators
  • 56. New Features (2) Unicode Modules Module loaders Map, set, weakmap, weakset Proxies Symbols Subclassable built-ins Promises
  • 57. New Features (3) •Math, number, string, array, object APIs •Binary and octal literals •Reflect api •Tail call optimization •
  • 58. Silicon Valley Code Camp 2014 Learn JavaScript by Modeling Rubik’s Cube Manoj Kumar
  • 59. Agenda •Scripting Language •Crash course in Rubik’s Cube •Code Walk-through •Modeling •Finding moves
  • 60. Scripting Language •Is a Programming Language –To manipulate –To customize –To automate –an existing system •ECMAScript –Web Scripting Language –To work with web browser
  • 61. ECMA Script •Object Based –Object: Collection of properties – Property • Type : Number, Boolean, String, Array, Function & other objects • Attributes •Value, Writable, Configurable, Enumerable •Functional •Based on –Java, C –Self (Prototype) –Scheme (Functional)
  • 63. Number •64 bit floating point (sign bit, 11 exp, 52 frac) •Represents integer and float – 1, 3.45, 5.345e-10, 0377, 0xFF, •Infinity – >1.79769313486231570e+308 •NaN – NaN != NaN •Representation for – MAX_VALUE, MIN_VALUE – NEGATIVE_INFINITY, POSITIVE_INFINITY • +0 == -0 but 1/+0 != 1/-0
  • 64. String •Within double/single quotes – “Hello world” – ‘u0041 world’ •Sequence of 16 bit unicode chars •Supports + operator •Used for character type too • •
  • 65. Boolean •Only two values – true – false •6 more falsy values – 0, -0, “”, NaN, null, undefined • Rest all values are true – Including ‘false’ :) •
  • 66. Undefined and Null •Undefined Type – Only one value: undefined – •Null Type – Only one value: null •
  • 67. Binary Operators •Binary + (Addition or concatenation) – 1 + 2 = 3, – ‘1’ + ‘2’ = ‘1’ + 2 = 1 + ‘2’ = ‘12’ •-, * , /, % – 2 * ‘3’ = 6 •>=, <=, >, < •==, != •=== !== •Logical &&, ||
  • 68. Prefix Operators •+ to number – 1 + +'2' // 3 •- negate •! logical not •Typeof – typeof 1 // ‘number’ – typeof ‘a’ // ‘string’ •
  • 69. Bit Operators •& and •| or •^ xor •~ not •>> signed right shift •>>> unsigned right shift •<< left shift
  • 70. And more •= assignment •+=, -=, *=, /= %= – X op= y ==> x = x op y •++ increment – X++ ==> x = x+1 •-- decrement – X-- ==> x = x-1
  • 71. A Simple Object point = { x : 100, y : 200 }; point.x // 100 point[‘x’] // 100 point.y = 300; ap = { “x-coord” : 100, “y-coord” : 200 }; ap.x-coord // Error, - means subtraction ap[“x-coord”] // 100 ap[“X-coord”] // undefined, (note the upper case X)
  • 72. Arrays var x = [5, 3]; x.length => 2 x.push(7) ===> add a new element x[20] = 9 ===> 3 to 19 elements are empty delete x[1] == remove one element x.splice(beginIndex, noOfElemToRemove) typeof x ==> ‘object’ .. not a good design x.constructor == Array concat, join, pop, reverse, slice, shift, sort
  • 74. Functions function add(x, y) { return x+y } sum = add(4,5) myAdd = add sum1 = myAdd(4, 5)
  • 75. Function Var Assignment myAdd = function add(x, y) { return x+y } sum1 = myAdd(4, 5) sum2 = add(4, 5) ReferenceError: add is not defined
  • 76. Function Var Assignment myAdd = function (x, y) { return x+y } sum1 = myAdd(4, 5)
  • 77. Anonymous Function sum = function (x, y) { return x+y } (4,5) sum = (function (x, y) { return x+y }) (4,5)
  • 78. Arguments function add( ) { var sum = 0 for( var i = 0; i < arguments.length; i++) { sum += arguments[i] } return sum } add(4, 5) => 9 add(4,5,3) => 12 add() => 0
  • 79. Functional Programming • Function as a first class object – Assign to variables – Pass to other functions • Avoid State change, mutability, side effects • Prefer recursion over loop • Higher Order Functions – ForEach (function, collection) – Map (function, collection) – Filter (function, collection) – Reduce (function, accumulator, collections) – Curry (function)
  • 80. Code Walkthrough Model Rubik’s Cube with Arrays and Functions
  • 81. Scope of a Variable function f() { a = 6 // “a” is a global variable } a = 5 f() // a is 6 now
  • 82. Scope of a Variable function f() { var a = 6 // “a” is a local variable alert("After assignment : a = " + a) } a = 5 alert("Before Calling function: a = " + a) f() alert("After Calling function: a = " + a)
  • 83. Scope of a Variable function f() { a = 6 …. var a = 7 // makes “a” a local variable! // declaration is hoisted but not the initializer! } a = 5 f()
  • 84. Scope of a Variable (ES 6) function f() { var a = 7; // local to function f If ( a > 5) { var b = 9; // Visible anywhere in the function let c = 1; // local to this IF block const pi = 3.14; // constant and local to IF block } }
  • 85. loop variable with var // Objective // funcs [ 0 ] = function( ) { return 0; } ; // funcs [ 1 ] = function( ) { return 1; } ; // funcs [ 2 ] = function( ) { return 2; } ; let funcs = [ ]; for (var i=0; i < 3; i++) { funcs.push( function() { return i;} ); } funcs[0]() ; // 3 funcs[1]() ; // 3 funcs[2]() ; // 3
  • 86. loop variable with var Funcs = [ ]; functionCreator(n) { return function() { return n;} } } for (var i=0; i < 3; i++) { funcs.push( functionCreator(i)); } funcs[0]() ; // 0 funcs[1]() ; // 1 funcs[2]() ; // 2
  • 87. loop variable with var for (var i=0; i < 3; i++) { funcs.push( function(n) { return function() { return n;} }(i) ); } funcs[0]() ; // 0 funcs[1]() ; // 1 funcs[2]() ; // 2
  • 88. loop variable with let let funcs = [ ]; for (let i=0; i < 3; i++) { // new binding of “ i ” is created in every iteration funcs.push( function() { return i;} ); } funcs[0]() ; // 0 funcs[1]() ; // 1 funcs[2]() ; // 2 <eot/>
  • 89. Semicolon Insertion You can only leave out ; – Before } A = 6 } – After new line(s) A = 6 } – End of the program Cannot leave ; within ‘for’ header – for (var i=0; i < 7 .. NO ; inserted here i++) {
  • 90. Semicolon Insertion Inserted only if next token cannot be parsed A = 6 (; is inserted automatically) X = 5 What if next line seems to be continuation? A = b (; is NOT inserted automatically) (add(3,4),......) – So problem starting chars are ( [ + - / – Statements before such chars must have ;
  • 91. Building Custom Object frontColor = { } // create empty object frontColor.red = 255 frontColor.blue = 0 frontColor.green = 128 redComponent = frontColor.red
  • 92. Object using constructor function Color ( r, g, b ) { this.red = r this.green = g; this.blue = b } red = new Color(255, 0, 0)
  • 93. Object Using Constructor function Color ( r, g, b ) { this.red = r this.green = g; this.blue = b } myColor = { } myColor.red // undefined Color.apply( myColor, [255, 65, 127] ) Color.call( myColor, 255, 65, 127 ) myColor.red // 255
  • 94. Bad Usage of Constructor function Color ( r, g, b ) { this.red = r this.green = g this.blue = b } Color(255, 127, 65) this.red // 255.. but what is “this” here?
  • 95. Immutable Object Using Constructor function Color ( r, g, b ) { this.getRed = function( ) { return r }; this.getGreen = function() { return g }; this.getBlue = function() { return b }; } red = new Color(255, 0, 0) red.getRed( ) // 255 ?? red.r = 128 // creates a new property r red.getRed() // 255!
  • 96. Closure •Closure is an object having –Function –Environment when function was created •Local Variables of outer function •Local functions declared in outer function •Parameters of outer function •this and arguments of outer function are not available but can be saved in local variables of outer function and then used in inner function
  • 97. Property Attributes •Value (Named Data Property) –Default value •Get and Set (Named Accessor Property) –Getter and Setter function –Either Value or Get/Set can be used, but not both •Writable –False => Read Only Property •Enumerable –False => Obj.keys or for (key in Obj) will not show •Configurable –False => delete obj.prop, or redefine will not work
  • 98. Defining Property function Color(r, g, b) { Object.defineProperties( this, { red : { value: r, writable : false, enumerable : true, configurable: false }, … } ); }
  • 99. Freezing an Object Rubik = {}; Rubik.Slope = {}; Rubik.Slope.HORIZONTAL = "Horizontal"; Rubik.Slope.VERTICAL = "Vertical"; Rubik.Slope.SLANTED = "Slanted"; // Make Rubik.Slope immutable Object.freeze(Rubik.Slope); Object.defineProperty( Rubik, "Slope", { writable : false, enumerable : true, configurable : false } );
  • 100. Sealing an Object Object.seal(Rubik.Slope); No new properties can be added. Writable properties can be re-written. Configurable properties can be re configured. Object.isSealed(Rubik.Slope) // true
  • 101. ES 6 (Harmony) Features • Block Scoping: let and const • Destructuring – [a, b] = [b, a] • Default Parameter • Rest and spread parameters – function(p1, ...restAllParams) – calling(p1, ...restAllParamsInArray) • Module Rubik { export function ..} • Import MyRubik as Rubik • Class, extends and super
  • 102. Code Walkthrough Model Rubik’s Cube with Objects
  • 103. Next step.. • DOM • JQuery • Java Script Design Patterns • Coding Style/Documentation • Books to read: – JavaScript – The Good Parts – Effective JavaScript
  • 104. Q & A • Source Code – GitHub • This presentation is available on SVCC • • • kr_manoj@yahoo.com
  • 105. Many Variables in one declaration function X () { var a = 5, b = 6 var c = 7, d=8 alert ( "a=" + a + ", b=" + b + ", c=" + c) } X() //alert ( "a=" + a + ", b=" + b + ", c=" + c)
  • 106. Spot the mistake! function X () { var a = 5 b = 6 var c = 7 alert ( "a=" + a + ", b=" + this.b + ", c=" + c) } X() //alert ( "a=" + a + ", b=" + b + ", c=" + c) alert ( "b=" + window.b)
  • 107. Spot the mistake! function X () { var a = 5, b = 6 var c = 7 alert ( "a=" + a + ", b=" + this.b + ", c=" + c) } X() //alert ( "a=" + a + ", b=" + b + ", c=" + c) alert ( "b=" + window.b)
  • 108. Constants in JavaScript "use strict"; Object.defineProperty(this, "PI", { value : 3.14, writable : false, enumerable : true, configurable : false }); PI = 7 // TypeError: "PI" is read-only
  • 109. Constants in JavaScript "use strict"; var MyConst = { } MyConst.PI = 3.14 Object.freeze(MyConst) MyConst.PI = 8 //TypeError: "PI" is read- only
  • 110. Rubik’s Cube •Cube –Mini Cube/Cubelet/Atom •Corner (8) •Edge (12) •Center (6) –Sides/Layer •Front/Back/Left/Right/Up/Down
  • 111. Naming Atoms •Corner: RFU –Right, Front, Up corner –RFU, FRU, URF … refers to same corner •Edge : RF –Middle cubelet of the edge shared by Right and Front layers •Center: R –Center of the right layer
  • 112. Moves •R => right layer 90 deg clockwise looking from right •R’ => right layer 90 deg anticlockwise looking from right •R2 => right layer 180 deg •RRRR, RR’, R2R2 =>No change •(XY)’ = Y’X’
  • 113. Effect of a Move •Rotating front layer clockwise ( F) ==> [ fru -> fdr -> fld -> ful -> fru ] [ fr -> fd -> fl -> fu -> fr ] •FRU ->FDR –Corner FRU has moved to FDR –Right side color of FRU has gone to Down side of FDR
  • 114. Useful Moves •Moves that produce the minimal disturbance •One cycle of 3 corners (Placement) •Rotating corners (Orientation) •One cycle of 3 edges (Placement) •In-place flipping edges (Orientation)
  • 115. Basic Corners Moves •One cycle of 3 corners –(R'D'LD RD'L'D) => [ fru -> drf -> ful -> fru ] –(RF'L'F R'F'LF) => [ fru -> lfu -> drf -> fru ] •Rotate corner at its own place (R'D'LD RD'L'D RF'L'FR'F'LF) ==> [ dfr -> rdf ] [ flu -> luf ]
  • 116. Basic Edges Moves •One cycle of 3 edges (V'F2VF2) ==> [ fu -> bu -> fd -> fu ] (V'F'VFFV'F'V) ==> [ fr -> fl -> df -> fr ] •Flipping edges in its own positions (RFBU2F2U'FUFU2B'R'F') ==> [ fr -> rf ] [ fu -> uf ]
  • 119. Call and Apply •add(4, 5, 2 ,3) •add.call(null, 4, 5, 2, 3) •add.apply(null, [4, 5, 2, 3]) •add.apply(undefined, [4, 5, 2, 3])
  • 120. Variables •No need to declare a variable sum = 5 • Local Variables var sum = 0; •Declaring many variables in one declaration var sum = 0, average = 0, stddev = 0; •Always use semicolon OR know the rules precisely
  • 121. Object •Collection of properties •Property (optional) –primitive value –function –other object •Prototype (optional) –To share property from others
  • 122. Literal Object frontColor = { red : 255 blue : 0 green : 128 } redComponent = frontColor.red greenComponent = frontColor [ “green” ]
  • 123. Immutable Object function makeColor ( r, g, b ) { return { getRed : function( ) { return r }, getGreen : function() { return g }, getBlue : function() { return b } } } color1 = makeColor(255, 0, 0) color1.getRed( ) // 255 color1.getGreen() // 0 color1.blue = 128 // red has no property called blue! Error!
  • 124. Arrow Functions ( ( ) => 5 ) ( ) === 5; var b = x => x + " Arrow"; b("Hello") === "Hello Arrow" var d = { x : "AB", y : function() { return z => this.x + z; } }.y(); d( "CD" ) === "ABCD" var e = { x : "XX", y : d };
  • 125. Promise let promise = new Promise( function(resolve, reject) { console.log(“1"); resolve();}); promise.then(function() { console.log(“3");}); console.log(“2”);
  • 126. You actually don't understand a concept. You just get used to it! And you brain makes you believe you got it! Very important for our technical/mental health.
  • 127. References • ECMAScript Support Matrix – http://pointedears.de/scripts/test/es-matrix/ • http://www.slideshare.net/Solution4Future/javascript-17363650 • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference •