- Valid Parenthesis
- Moving zeros to the end
- Where my anagrams at
- Remove duplicates
- Simple sequence
- Numbers in order
- Take or leave it
- missing summaries in Eloquent JS
- automate: performance? testing? gulp?
- ES5 is the "current" version in all major browsers (specially IE).
- ES6, now ES2015, is the newer spec.
- Because the support for ES6 is spotty in some browsers (cough, cough), we have to depend on transpilers
- Basically translate from ES6 to ES5 in a new tooling step.
- But we can use polyfills/shims, basically added features (like new functions in ES6) that don't require syntactic changes and can added in older JS versions.
-
let instead of var, with block scoping!
-
Temporal Dead Zone (TDZ), the place variables occupy when they are not initialized
-
let in a for loop creates a variable for each iteration of the loop (so closures works as expected)
-
const are constant (references!)
-
Block scoping works! (yay!)
-
... operator, called spread to transform an array to parameters or rest to transform parameters to an array.
-
spread behaves like apply with arrays or concat
-
rest behaves like arguments
-
Default parameters, like:
function foo(x = 11) { }
-
Default parameters can be expressions (functions) or references to other previous parameter
-
...
Repo for resources & notes for the JS Learning Group by @nhpatt
- Values, Types, and Operators
- Program structure
- Functions
- Data Structures: Objects and Arrays
- Higher order functions
- The Secret Life of Objects
- Project: Electronic Life
- Bugs and Error handling
- Drawing on Canvas
- HTTP
- Forms and Form Fields
- Conventions, tips & tricks
Missing description
- Chessboard in canvas
Missing description
Missing description
Like other arrays... with []
With methods like
push
(with variable arguments)pop
join
Classic fields, available through dot notation and square brackets (metaprogramming!)
- With
{}
- You can delete a property (very uncommon)
- And check with if a property exists
in
- Existing values in JS (numbers, strings and booleans) are immutable.
Abstractions hide details and allow us to work in a more abstract level.
forEach
is available in arrays- We can create functions based on parameters
apply
let us call a function with an array number of arguments ->f.apply(null, arguments)
-> calls the functionf
passingarguments
JSON.stringify
andJSON.parse
built into the languagefilter
belongs to the array object, accepts a function to filter.map
,reduce
in the classic incarnation are also available.- functional functions are great but be aware of the efficiency
bind
let us apply arguments.
Missing description
Missing description
Bugs are unavoidable and we have to learn to deal with them.
-
JS is very tolerant with errors and bugs, usually keeps computing until it finishes.
-
Calling something that is not a function or looking a property of undefined will halt the program.
-
JS can be made more strict by enabling strict mode at the top of a file or function.
- Fails when using variables not defined
- Fails when using this when functions are not called as methods
please, use strict mode
-
Do testing, either manually, with a custom method or a library.
-
We can do manual debugging with
console.log
or a browser. -
How to do error propagation?
- return
null
or a special value - Exceptions!
- return
throw
raises an exceptiontry
andcatch (error)
mechanism.new Error(message)
is the typical object thrown.finally
as everybody is used to.- JS does not have selective catching of exceptions (for example, we can't define several
catch
clauses). - But we can create our own exception (should have a name property and an stack like
(new Error()).stack)
.
- We can do custom checks with assets after defining our own custom function.
- SVG = vector shapes, against canvas that is not vectorial.
- SVG -> circle, rect elements with xml namespace.
- Canvas -> 2d & 3d (WebGL)
<canvas></canvas>
with width and height- Based on the context object, document.getElementById('').getContext("2d")
-
Vector methods
- ctx.fillRect(10, 10, 100, 50) and ctx.fillStyle = 'red'
- fill, give color to an area with fillStyle
- stroke, give color to a border with strokeStyle
- lineWidth, to add width to a border
- path, sequence of lines with beginPath(), moveTo or lineTo and stroke to finish.
- in a path you can use fill if the path is closed or it will be closed automatically
- quadraticCurveTo to draw a curve by attracting
- and bezierCurve
- and arcTo
-
so we can do a pie chart by applying math (:S)
-
Text methods
fillText
allows us to paint text (strokeText maybe useful too), with position.
-
Images
drawImage
can paint a bitmap image based on a<img>
but we need to wait until it's loaded.- We also can paint sprites (
drawImage
with 9 arguments).
-
Transformation
ctx.scale
allows to scale the next thing it's painted.- scaling allows negative values to flip things
- but we hace to play with
translate
and coordinate systems to paint it inside our canvas region
-
Store state
save
andrestore
allows us to use a stack of states.
Example in few lines of JS:
- GET, DELETE, PUT, POST...
- 2xx -> OK, 3xx -> not here, 4xx -> you messed up, 5xx -> we messed up
- encodeURIComponent to encode to url format and decodeURIComponent to decode it
var req = new XMLHttpRequest();
req.open("GET", "example/data.txt", false);
req.send(null);
console.log(req.responseText);
- Relative GET request
- ...
- Forms are special
-
Use always
[]
instead ofnew Array()
-
Create objects with
{}
-
Set a default value with
||
, for example:var something_that_could_be_undefined = undefined; var number = something_that_could_be_undefined || 0;
-
Check if array is not empty with
if (array.length) {...}
or empty with!array.length
. -
‘Double negation operator':
!!variable
to force a cast to boolean.
-
Module pattern, a way of having private methods and properties. Typically similar to:
(function() {} return {})()
. A function that is being executed instantly. For example:(function module_pattern_revealed() { var private_element = 2; function example_function() { //operate_with_private_element } return { example_function: example_function } })();
-
Understanding prototype: every object is linked to a prototype object from which it can inherit properties. This is done dynamically, so you can decorate language objects like
Array
or all your own objects at the same time. -
Closures: functions can be defined inside of other functions. An inner function of course has access to the parameters and variables of the functions it is nested within. The function object created by a function literal contains a link to that outer context. This is really powerful and can be the origin of strange behaviours with loops and event handlers if not understood correctly.
-
Truthy and falsy: a lot of values cast to false, like
undefined
or 0, so in JS we talk about truthy and falsy values (those who cast to true or false, respectively). -
Hoisting: variables and functions are moved to the top of the scope in which are defined.
We have 4 ways of invoking a function:
-
Method invocation,
this
is the scope of our object.var myObject = { value: 0, increment: function (inc) { this.value += typeof inc === 'number' ? inc : 1; } }; myObject.increment(); // 1 myObject.increment(2); // 3
-
Function invocation, where
this
is the scope of the “global” object (window
in a browser).var myObject = {}; myObject.double = function () { var that = this; // Workaround. var helper = function () { that.value = add(that.value, that.value); }; helper(); // Invoke helper as a function. }; // Invoke double as a method. myObject.double( );
helper
is invoked as a function andthis
refers to the global scope.The usual workaround is use a variable called
that
orself
that “caches” the value ofthis
. -
Constructor invocation,
this
refers to the scope of our objectvar Quo = function (string) { this.status = string; }; Quo.prototype.get_status = function () { return this.status; }; // Make an instance of Quo. var myQuo = new Quo("value"); myQuo.get_status() // value
-
And use
bind
,apply
,call
... where the programmer sets the value ofthis
.
The only strange behaviour is calling a function with a function invocation (constructor and method works fine).
The bad case is more common as it seems, because event handlers, DOM events, timeouts or other corner cases.
The solutions are:
- Understand why
this
behaves this way and react accordingly. - Program only using properties, constructors (without forgetting new) or use
apply
(and derivates). - Create variables like
that
. - Don’t use
this
ever.