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.
Functional Programming Patterns for the Pragmatic ProgrammerRaúl Raja Martínez
In this talk we will see a pragmatic approach to building a purely functional architecture that delivers cohesive functional components.
We will cover functional patterns such as Free Monads, Transformers, Kleisli arrows, dependently typed checked exceptions
and types as well as how they can be glued together to achieve pure functions that are composable, context free, dependently injectable and testable.
Dome project and code with instructions to run it can be found at:
https://github.com/47deg/func-architecture
(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
Все началось давно, еще в школе, классе эдак 7. Тогда учитель математики впервые произнесла фразу: "Игрек равно эф от икс". В то время я и не догадывался что это самое "эф от икс", является базовым принципом функционального программирования, да и не только функционального.
Functional Programming, Reactive Programming, Transducers, MapReduce и многое другое, так или иначе корнями уходит в то самое, незамысловатое f(x). Это настолько серьезная часть программирования, что ежеминутно, если не ежесекундно, по всему миру на клавиатуре нажимаются клавиши f, u, n, c, t, i, o, n. И нажимаются они именно в этой последовательности.
Пора принять тот факт, что без функционального программирования, программирования не существует!
Пора разобраться. Пора понять для чего нужны функции в программирование, как они должны работать и чем они могут быть полезны в ежедневной работе.
Functional Programming Patterns for the Pragmatic ProgrammerRaúl Raja Martínez
In this talk we will see a pragmatic approach to building a purely functional architecture that delivers cohesive functional components.
We will cover functional patterns such as Free Monads, Transformers, Kleisli arrows, dependently typed checked exceptions
and types as well as how they can be glued together to achieve pure functions that are composable, context free, dependently injectable and testable.
Dome project and code with instructions to run it can be found at:
https://github.com/47deg/func-architecture
(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
Все началось давно, еще в школе, классе эдак 7. Тогда учитель математики впервые произнесла фразу: "Игрек равно эф от икс". В то время я и не догадывался что это самое "эф от икс", является базовым принципом функционального программирования, да и не только функционального.
Functional Programming, Reactive Programming, Transducers, MapReduce и многое другое, так или иначе корнями уходит в то самое, незамысловатое f(x). Это настолько серьезная часть программирования, что ежеминутно, если не ежесекундно, по всему миру на клавиатуре нажимаются клавиши f, u, n, c, t, i, o, n. И нажимаются они именно в этой последовательности.
Пора принять тот факт, что без функционального программирования, программирования не существует!
Пора разобраться. Пора понять для чего нужны функции в программирование, как они должны работать и чем они могут быть полезны в ежедневной работе.
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
Object-Oriented Programming has well established design principles, such as SOLID. For many developers architecture and functional programming are at odds with each other: they don’t know how their existing tricks of the trade convert into functional design. This problem becomes worse as hybrid languages such as Java 8 or Scala become common. We’ll talk about how functional programming helps you implement the SOLID principles, and how a functional mindset can actually help you achieve cleaner and simpler OO design.
It's not your mother's C++ anymore. Manual memory management, tedious loops, difficult-to-use STL algorithms -- are all a thing of the past now. The new C++ 11 standard contains a huge number of improvements to the C++ core language and standard library, and can help C++ developers be more productive.
In this session we will discuss the major features of C++ 11, including lambda functions, type inference for local variables, range-based for loops, smart pointers, and more. We will see how to use these features effectively to modernize your existing C++ programs and how to develop in the modern C++ style.
Scala, Haskell and LISP are examples of programming languages using the functional programming paradigm. Join us in this TechTalk to know why functional programming is so important, how to implement some of its core concepts in your existing programming languages, and how functional programming inspired Google's Map Reduce, Twitter's Algebird, and many other technologies.
By Mohammad Ghabboun - Senior Software Engineer, SOUQ.com
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
Higher-order functions such as map(), flatmap(), filter() and reduce() have their origins in mathematics and ancient functional programming languages such as Lisp. But today they have entered the mainstream and are available in languages such as JavaScript, Scala and Java 8. They are well on their way to becoming an essential part of every developer’s toolbox.
In this talk you will learn how these and other higher-order functions enable you to write simple, expressive and concise code that solve problems in a diverse set of domains. We will describe how you use them to process collections in Java and Scala. You will learn how functional Futures and Rx (Reactive Extensions) Observables simplify concurrent code. We will even talk about how to write big data applications in a functional style using libraries such as Scalding.
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
Object-Oriented Programming has well established design principles, such as SOLID. For many developers architecture and functional programming are at odds with each other: they don’t know how their existing tricks of the trade convert into functional design. This problem becomes worse as hybrid languages such as Java 8 or Scala become common. We’ll talk about how functional programming helps you implement the SOLID principles, and how a functional mindset can actually help you achieve cleaner and simpler OO design.
It's not your mother's C++ anymore. Manual memory management, tedious loops, difficult-to-use STL algorithms -- are all a thing of the past now. The new C++ 11 standard contains a huge number of improvements to the C++ core language and standard library, and can help C++ developers be more productive.
In this session we will discuss the major features of C++ 11, including lambda functions, type inference for local variables, range-based for loops, smart pointers, and more. We will see how to use these features effectively to modernize your existing C++ programs and how to develop in the modern C++ style.
Scala, Haskell and LISP are examples of programming languages using the functional programming paradigm. Join us in this TechTalk to know why functional programming is so important, how to implement some of its core concepts in your existing programming languages, and how functional programming inspired Google's Map Reduce, Twitter's Algebird, and many other technologies.
By Mohammad Ghabboun - Senior Software Engineer, SOUQ.com
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
Higher-order functions such as map(), flatmap(), filter() and reduce() have their origins in mathematics and ancient functional programming languages such as Lisp. But today they have entered the mainstream and are available in languages such as JavaScript, Scala and Java 8. They are well on their way to becoming an essential part of every developer’s toolbox.
In this talk you will learn how these and other higher-order functions enable you to write simple, expressive and concise code that solve problems in a diverse set of domains. We will describe how you use them to process collections in Java and Scala. You will learn how functional Futures and Rx (Reactive Extensions) Observables simplify concurrent code. We will even talk about how to write big data applications in a functional style using libraries such as Scalding.
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?
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
An introductory presentation I'm doing at my workplace for other developers. This is geared toward programmers that are very new to javascript and covers some basics, but focuses on Functions, Objects and prototypal inheritance ideas.
This is the slide for what I shared in JS Group meetup, 2014, Taiwan. It covers what JavaScript could do for making the program more "functional", the benefits, price and the limitation.
2. $ whoami
Programming languages:
Compiled, general purpose: Java; C/C++; Scala
Scripting: JavaScript; Python; etc…
Experimental: Go; Dart; CoffeeScript
Recent works (non-project, related to JS):
NodeJS based stuff involving custom C++ extensions
Closure Compiler / Closure Templates enhancements
3. Agenda
OO Inheritance patterns in JS, which one to use?
Exploiting functional paradigm support
Asynchronity in JS
(still) common pitfalls, how to avoid them?
Agenda is based on my observations during every day work, working with 3rd party
sources.
4. OO & Inheritance Patterns
Devs tend to trust various frameworks to construct classes with
inheritance.
Popular types (Crockford’s terms):
„Pseudoclassical”
„Power-constructor” or „Parasital”
Trends:
Avoiding new keyword
Emulating private members with closures
Assembling objects from prototypes „by hand”
5. Pseudo-Classical Pattern
Popular types (Crockfod’s terms):
„Pseudo-classical”
„Power-Constructor” or „Parasital”
Concerning trends:
„Power constructors” – avoiding new keyword
Emulating private members with closures
Assembling objects from prototypes „by hand”
7. Object.create Polyfill
if (!Object.create) {
Object.create = function (o) {
if (arguments.length > 1) {
throw new Error('properties not implemented');
}
function F() {}
F.prototype = o;
return new F();
};
}
9. Difference of Resulting Objects
Prototype chain (__proto__):
„Pseudo-Classical” „Power-constructor”
Rectangle Rectangle + Shape
Shape Object
Object
Shape
Object
• layered structure, head object • flat structure, every head
has only instance members object has all members
• Instantiated with new • new keyword is optional
keyword
10. Which One is Better?
Power-Constructor pattern is extremely popular. A lot of frameworks
using it, including jQuery.
Do we need privates? – not really
Performance?
Demo time! Let’s evaluate performance with a particle system.
11. Conclusion
Despite a little bit more verbose, might look not as self-contained than
other variants, Pseudo-Classical inheritance is the way to go.
Advantages:
Way batter performance, especially at large number of instances
Better IDE recognition
Better tooling (Closure-Compiler friendly)
12. Functional Paradigm: Higher Order Functions
Functions could be passed as arguments, and could be returned by other
functions as return values.
Functions are threated as first-class values.
This provides a flexible way to compose programs.
13. Example:
Take the sum of the integers between a and b:
// sum of integers between a and b
function sumInts(a, b) {
var sum = 0, i;
for (i = a; i <= b; i += 1) {
sum += i;
}
return sum;
}
Take the sum of the cubes of all integers between a and b:
function cube(n) {
return Math.pow(n, 3);
}
function sumCubes(a, b) {
var sum = 0, i;
for (i = a; i <= b; i += 1) {
sum += cube(i);
}
return sum;
}
14. Example (continued)
function factorial(n) {
var i, f = 1;
for (i = 2; i <= n; i += 1) {
f *= i;
}
return f;
}
function sumFactorials(a, b) {
var sum = 0, i;
for (i = a; i <= b; i += 1) {
sum += factorial(i);
}
return sum;
}
15. Advanced version using higher-order functions
A generic sum:
function sum(f, a, b) {
var sum = 0, i;
for (i = a; i <= b; i += 1) {
sum += f(i);
}
return sum;
}
Rewritten special cases:
function identity(n) { return n; }
sumInts = function (a, b) { return sum(identity, a, b); };
sumCubes = function (a, b) { return sum(cube, a, b); };
sumFactorials = function (a, b) { return sum(factorial, a, b); };
Taking functions as parameters, but still a lot of redundancy here…
16. More advanced version, removed redundancy
Let’s rewrite sum to return a function:
function sum(fn) {
return function (a, b) {
var sum = 0, i;
for (i = a; i <= b; i += 1) {
sum += fn(i);
}
return sum;
};
}
So specific cases could be written as:
sumInts = sum(identity);
sumCubes = sum(cube);
sumFactorials = sum(factorial);
Or could be invoked without the middle-man:
// equivalent to sumCubes
sum(cube)(3, 5);
// sum of the halves of integers between a and b
sum(function (n) { return Math.round(n / 2); })(3, 5);
17. Asynchronicity
JS is…
Event driven
Single threaded (setTimeout doesn’t do the trick)
Long running code could block execution, UI responsiveness
Standard APIs rely on call-backs
They are often nested multiple levels
Hard to debug: reading the call-stack is hard; exceptions
might not get propagated up to the initiator
„Pyramid of Doom”!
18. Difficulties with Call-backs
„Pyramid of doom”
When the code marches to the right faster than it marches forward:
step1(function (value1) {
step2(value1, function(value2) {
step3(value2, function(value3) {
step4(value3, function(value4) {
// Do something with value4
});
});
});
});
This is sequential, what if step3 could be executed when both step1 and
step2 are completed, but those two steps doesn’t depend on each other?
19. Difficulties with Call-backs (continued)
Synchronizing multiple call-backs
var callbackACompleted = false;
var callbackBCompleted = false;
function callbackA(result) {
// process result
callbackACompleted = true;
if (callbackBCompleted) {
done();
}
}
function callbackB(result) {
// process result
callbackBCompleted = true;
if (callbackACompleted) {
done();
}
}
function done() {
// things to do when boot callbacks completed their jobs
}
processA(params, callbackA);
processB(params, callbackB);
20. Deferred objects / Promises / Futures
Designed to solve exactly these problems
Under used, not widely known
API
done()
then() A promise is the stripped down
Promise version of the deferred instance,
fail()
Deferred doesn’t contain any state mutator
always() methods.
resolve()
reject()
Usage: a task creates a deferred object, and resolves (or fails it) later by
calling .resolve() / .reject(). Clients use promise, which doesn’t provide state
manipulation, just change subscription methods.
22. Pitfalls
Array
Deleting
delete arr[2]; // [1, 3, undefined × 1, 29, 45, 51]
arr.splice(2, 1); // ok! [1, 3, 29, 45, 51]
Never attempt to remove an element from an array with delete, use splice.
Sorting
arr = [1, 3, 24, 29, 45, 51];
arr.sort(); // [1, 24, 29, 3, 45, 51]
arr.sort(function (x, y) {return x > y;}); // ok
What happened? Don’t relay on default sort functionality; implement getComparator() ->
function for objects.
23. Pitfalls (continued)
Number Conversion
+"08"; // ok (8)
+new Date; // .valueOF()
Number("08"); // same as +
parseInt("08"); // 0 why?
parseInt("ff", 16); // 256
Prefer the + unary operator, you may implement valueOf(), always provide radix for
parseInt()!
Typeof
// typeof
typeof array === "object"; // Array.isArray() (polyfill)
typeof null === "object"; // spec error :(
Worst is typeof null, it returns „object” as a result of an early language specification.