├── .gitignore
├── JavaScript
├── Closures.md
├── ECMAScript 6.md
├── JavaScript-Classes.md
├── JavaScript-Scope.md
├── JavaScript_Limitations.md
├── Objects.md
├── array-map.md
├── array-methods-overview.md
├── array-reduce.md
├── basic-performance-testing.md
├── best-js-resources.md
├── by-value-and-by-reference.md
├── call-apply-bind.md
├── conditional-operator.md
├── hoisting.md
├── inheritance-and-javascript.md
├── large-numbers-in-js.md
├── linked-list.md
├── math-object-beginner-guide.md
├── modulo-operator.md
├── prototypes-more.md
├── raising-exceptions.md
├── recursive-function.md
├── regular-expressions-beginners-guide.md
├── regular-expressions-lookaheads.md
├── replace-method.md
├── scope-and-hoisting.md
├── shortcuts.md
├── string-dissection-and-manipulation.md
├── synchronous-and-asynchronous.md
├── writable-enumerable-configurable.md
└── xhr.md
├── README.md
├── SUMMARY.md
├── codewars
├── codewars.md
├── random-test-cases-for-complete-beginners.md
└── writing-your-own-kata.md
├── contribution-workflow.md
├── gitbook-chapter-headers
├── arrays.md
├── codewars.md
├── courses-notes.md
├── html-css.md
├── js.md
├── numbers.md
└── programmer-skills.md
├── html-css
├── choosing-a-css-framework.md
├── css-centering.md
├── document-object-model.md
├── laying-out-content-with-flexbox.md
└── manipulating-inline-styles.md
├── images
├── Array.map.png
├── ClassesExample.png
├── Debugging-img-1.png
├── Debugging-img-2.png
├── Debugging-img-3.png
├── Debugging-img-4.png
├── Debugging-img-5.png
├── Debugging-img-6.png
├── Debugging-img-7.png
├── Debugging-img-8.png
├── OnlineConsoleOptions__codepen_io.png
├── OnlineConsoleOptions__jsbin_com.png
├── OnlineConsoleOptions__jsfiddle.png
├── OnlineConsoleOptions__jshint_com.png
├── OnlineConsoleOptions__repl_it.png
├── array.reduce1.gif
├── array.reduce2.gif
├── array.reduce3.gif
├── array.reduce4.gif
├── brackets_alert.png
├── brackets_code_errors.png
├── brackets_first_run.png
├── brackets_live_preview.png
├── brackets_live_preview_button.png
├── brackets_live_preview_changes.png
├── brackets_warning_button.png
├── developer_tool_js_output.png
├── developer_tool_js_output_hello.png
├── dom
│ ├── document-child-child.png
│ ├── document-childnode.png
│ ├── document.png
│ ├── dom-tree-small.png
│ ├── dom-tree.png
│ ├── get-by-classname.png
│ ├── get-by-id.png
│ ├── get-by-tag.png
│ ├── get-option.png
│ ├── her-homepage.png
│ ├── manipulate-after.png
│ ├── manipulate-before.png
│ ├── parent-node.png
│ └── visual-dom-tree.png
├── flexbox-flex-direction-column-justify-content.jpg
├── flexbox-flex-direction-column.jpg
├── flexbox-flex-direction-row-align-content.jpg
├── flexbox-flex-direction-row-align-items.jpg
├── flexbox-flex-direction-row-justify-content.jpg
├── flexbox-flex-direction-row.jpg
├── includes.png
├── jsbin.png
├── jsbin_choose_lang.png
├── jsbin_code.png
├── jsbin_errors.png
├── jsbin_fix.png
├── jsbin_panels.png
├── jsbin_run.png
├── jsbin_share.png
├── liquid.png
├── objprop1.png
├── objpropproto.png
├── package-control.png
├── protochain.png
├── remainder.png
├── s1.png
├── s2.png
├── s3.png
├── s4.png
├── s5.png
├── s6.png
├── setting-up-a-local-server.png
├── transpose2dArray.gif
├── tsc_options.png
├── tsc_sublime_view.png
├── twoobjectschain.png
└── typescript_venn_small.png
├── notes-for-online-courses
├── CS50-Videos.md
└── javascript-the-good-parts-by-douglas-crockford.md
├── programmer-skills
├── Debugging-Javascript.md
├── big-O-notation.md
├── command-line.md
├── git-GUI-linux.md
├── git-basics.md
├── git-flow.md
├── hosting-on-github-gh-pages.md
├── jekyll-on-gh-pages-basics.md
├── markdown-cheat-sheet.md
├── mutable-vs-immutable.md
├── online-console-options.md
├── setting-up-a-local-server.md
├── setting-up-your-development-environment.md
├── sorting-algorithms.md
├── start-to-develop-js.md
└── typescript_get_started.md
└── responsiveD3.md
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea/
2 |
--------------------------------------------------------------------------------
/JavaScript/Closures.md:
--------------------------------------------------------------------------------
1 | # Closures
2 |
3 | ### Introduction
4 |
5 | Closures have a reputation for being one of JavaScript's most difficult concepts to grasp. However, if you're already comfortable with how JavaScript deals with functions and [scope][1], you're already halfway there.
6 |
7 | ----
8 |
9 | ### Scope
10 |
11 | As you should know before attempting to understand closures, JavaScript variables are accessible within:
12 |
13 | **global scope** when defined outside of any function or declared without the `var` keyword
14 | **local scope** when defined inside a function
15 | **lexical scope** when defined as part of a nested function chain
16 | **block scope** when defined with ES6 keywords `let` or `const`
17 |
18 | Consider the following example of a nested function:
19 |
20 | ```javascript
21 | var a = 1;
22 | function outer(){
23 | var b = 2;
24 | function inner(){
25 | var c = 3;
26 | return a + b + c;
27 | }
28 | return inner();
29 | }
30 |
31 | var d = outer();
32 |
33 | d; // 6
34 | ```
35 |
36 | The variable `a` has **global scope** so can be accessed anywhere.
37 |
38 | The variable `b` has **local scope**, local to the function `outer()` - it can only be accessed inside of it. Similarly, variable `c` is local to the function `inner()` and can only be accessed inside of it.
39 |
40 | However, due to **lexical scope**, `inner()` also has access to variables `b` and `a` because they are defined within the its parent functions - `outer()` and the global space.
41 |
42 | Running this code, we set `a` and then call `outer()`, which sets `b` and calls `inner()`, which sets `c` and adds `a`, `b` and `c` together, returning a value of `6` because it has access to all 3 variables. Finally, the value of `6` is returned by `outer()` and assigned to `d`.
43 |
44 | Now onto closures. (We can ignore **block scope** for now.)
45 |
46 | ----
47 |
48 | ### Closures
49 |
50 | According to [MDN][2]:
51 |
52 | > Closures are functions that [...] 'remember' the environment in which they were created.
53 |
54 | In the example above, if we tried to call `inner()` from the global space, we would get an error telling us that the function is not defined. This is because - like variables - functions are also affected by scope. `inner()` is local to the function `outer()` and can't be used outside of it.
55 |
56 | With a small tweak, we can make `inner()` available to the global space without changing the scope of the variables involved:
57 |
58 | ```javascript
59 | var a = 1;
60 | function outer(){
61 | var b = 2;
62 | var inner = function(){
63 | var c = 3;
64 | return a + b + c;
65 | }
66 | return inner;
67 | }
68 |
69 | var d = outer();
70 |
71 | b; // undefined
72 | d(); // 6
73 | ```
74 |
75 | Here, we've replaced the function declaration of `inner()` with a function expression, and then returned the function stored in `inner`, rather than its return value.
76 |
77 | When we assign the function to `d`, calling `d()` from the global space has the same effect as calling `inner()`, except this time we get the returned value of `6`, instead of an error. If we try to access `b` from the same space, we still get an error like last time.
78 |
79 | This is unusal because now `d()` has access to all 3 variables `a`, `b` and `c` in the global space, but any new function will not. Although it is defined in the global space, `d()` has **'remembered' the original environment (scope) in which it was created**.
80 |
81 | ----
82 |
83 | ### Why... do I need to know this?
84 |
85 | #### Avoid exposing data you don't need to
86 |
87 | Closures are useful when you want to set a variable to use in a function that shouldn't be accessed or changed by other functions, either intentionally or accidentally.
88 |
89 | Rather than using an object with properties and methods, you can use a closure to make sure that the properties don't get altered.
90 |
91 | #### Object
92 |
93 | ```javascript
94 | var human = {
95 | greeting : 'Hello!',
96 | sayHello : function(){
97 | console.log(this.greeting);
98 | }
99 |
100 | human.greeting = 'Go away.';
101 | human.sayHello(); // outputs 'Go away.' :(
102 | ```
103 |
104 | #### Closure (with [immediately invoked function expression][3])
105 |
106 | ```javascript
107 | var sayHello = (function(){
108 | var greeting = 'Hello!';
109 | var greet = function(){
110 | console.log(greeting);
111 | }
112 | return greet;
113 | })();
114 |
115 | var greeting = 'Go away.';
116 | sayHello(); // outputs 'Hello!' :)
117 | ```
118 |
119 | ----
120 |
121 | #### Maintaining state
122 |
123 | In the code below, the closure sets up an `i` value of `0` and updates the value every time the function is called. This allows iteration through an array one element at a time - the function 'remembers' the state of `i` at the last iteration.
124 |
125 | ```javascript
126 | var array = ['a','b','c','d','e','f','g'];
127 |
128 | function iterate(arr){
129 | var i = 0;
130 | var iterator = function(){
131 | return arr[i++];
132 | }
133 | return iterator;
134 | };
135 |
136 | var next = iterate(array);
137 |
138 | next(); // returns 'a'
139 | next(); // returns 'b'
140 | next(); // returns 'c'
141 | next(); // returns 'd'
142 | ...
143 | ```
144 |
145 | ----
146 |
147 | ### Related
148 |
149 | [JavaScript Scope: A Beginners Perspective][4]
150 | [Variable scope and hoisting][5]
151 | [Hoisting][6]
152 |
153 | ### Resources
154 |
155 | - [Closures - JavaScript | MDN][7]
156 | - [How do JavaScript closures work? - Stack Overflow][14]
157 | - [what's the point of closures? - Journey Into JavaScript][8]
158 | - [JavaScript Scope - Lexical Scoping, Closures & Controlling Context][9]
159 | - [Closure (computer programming) - Wikipedia][10]
160 | - [Explaining JavaScript scope and closures - Robert's Talk][11]
161 | - [Ben Alman » Immediately-Invoked Function Expression (IIFE)][12]
162 | - [Alwin Solanky's post in codingforeveryone/today-i-learned][13]
163 |
164 |
165 | [1]: https://github.com/codingforeveryone/READMEs/blob/master/JavaScript/JavaScript-Scope.md
166 | [2]: https://developer.mozilla.org/en/docs/Web/JavaScript/Closures
167 | [3]: https://developer.mozilla.org/en-US/docs/Glossary/IIFE
168 | [4]: https://github.com/codingforeveryone/READMEs/blob/master/JavaScript/JavaScript-Scope.md
169 | [5]: https://github.com/codingforeveryone/READMEs/blob/master/JavaScript/scope-and-hoisting.md
170 | [6]: https://github.com/codingforeveryone/READMEs/blob/master/JavaScript/hoisting.md
171 | [7]: https://developer.mozilla.org/en/docs/Web/JavaScript/Closures
172 | [8]: https://journeyintojavascript.quora.com/whats-the-point-of-closures
173 | [9]: https://spin.atomicobject.com/2014/10/20/javascript-scope-closures/
174 | [10]: https://en.wikipedia.org/wiki/Closure_(computer_programming)
175 | [11]: https://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/
176 | [12]: http://benalman.com/news/2010/11/immediately-invoked-function-expression/
177 | [13]: https://github.com/codingforeveryone/today-i-learned/blob/master/oojs/closures.md
178 | [14]: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work#answer-111111
--------------------------------------------------------------------------------
/JavaScript/JavaScript-Classes.md:
--------------------------------------------------------------------------------
1 | #JavaScript Functional Classes
2 |
3 | ###Introduction
4 |
5 | JavaScript is a prototypal object-oriented language, meaning that objects can inherit properties directly from other objects. This will be a bit different for those who have learned to develop in other langauges like Java or C#, where a subclass inherits from a superclass, and objects are instances of classes.
6 |
7 | If you want to create multiple objects with similar methods and properties in JavaScript, the best options are functional classes, or the constructor function. There are four styles of functional classes.
8 |
9 | #####*Functional*
10 |
11 | #####*Functional-shared*
12 |
13 | #####*Prototypal*
14 |
15 | #####*Pseudoclassical*
16 |
17 | Each of these four is a different style of object construction; they all accomplish the same thing in a slightly different way.
18 |
19 | Take for example, a street with many houses. Every house on the street is painted a `colour` and it will have a front `door` which can either be opened or closed. So Houses may be thought of as objects.
20 |
21 | If we implement functional classes here, every instance created by the function will have the attributes of house colour and the method to open and close the door.
22 |
23 | From here we can potentially create unlimited new `House` objects, which are similar. So each functional class performs the same basic steps to generate the new houses:
24 |
25 | * generate an object
26 | * assign properties
27 | * add methods
28 | * return that object
29 |
30 | Each of the four styles has its pros and cons, which will now be outlined below.
31 |
32 | ###Functional
33 |
34 | Firstly, the functional style is a fast, very simple and clear means of object creation. However it duplicates all of the methods for every single object created. This means a new function is stored in memory every time the object is generated. If you are working with large numbers of objects, this may not be the best choice.
35 |
36 |
37 |
38 | var House = function(colour){
39 | var obj = {}; // generate object
40 |
41 | obj.colour = colour;
42 | obj.door = 'open'; //assign properties
43 |
44 | obj.openDoor = function(){
45 | obj.door = 'open';
46 | }; //explicitly define or borrow methods
47 |
48 | obj.closeDoor = function(){
49 | obj.door = 'close';
50 | }; //explicitly define or borrow methods
51 |
52 | return obj;
53 | }
54 |
55 | var house = House('red'); //instantiation pattern
56 |
57 |
58 | ###Functional-shared
59 |
60 | Secondly there is functional-shared, a better approach for memory management as it utilises a single repository for the methods. Every time an object is created, pointers are generated, so every new object will point back to the houseMethods object, where the functions are stored one single time in memory.
61 |
62 |
63 | var House = function(colour){
64 | var obj = {}; // generate object
65 |
66 | obj.colour = colour;
67 | obj.door = 'open'; //assign properties
68 |
69 | obj.open = houseMethods.openDoor;
70 | obj.close = houseMethods.closeDoor; //explicitly define or borrow methods
71 |
72 | return obj;
73 | };
74 |
75 | var houseMethods = {};
76 |
77 | houseMethods.openDoor = function(){
78 | this.door = 'open'; //Add method to delegate fallback object
79 | };
80 |
81 | houseMethods.closeDoor = function(){
82 | this.door = 'close'; //Add method to delegate fallback object
83 |
84 | };
85 |
86 | var house = House('red'); //instantiation pattern
87 |
88 | `this` is not as efficient as using the properties of its prototype which is known as delegating through fallback.
89 |
90 | ###Prototypal
91 |
92 | If a method or property is called on an object, where it does not exist for that object, JavaScript will check if it's defined on its fallback object. (See the README on [Inheritance and JavaScript](https://github.com/codingforeveryone/READMEs/blob/master/JavaScript/inheritance-and-javascript.md)). Fallbacks are like a back-up plan for objects, they are the cornerstone of *prototypal* style. Every function has a property called `prototype` where the fallback methods are stored. So in the prototypal House function, the House function's property (`House.prototype`) is explicitly delegated as the fallback location for EVERY house object created by House. So every method in `House.prototype` is available to every object created by House. The advantage is that methods are not duplicated in memory. However, it utilises more code than the others.
93 |
94 | var House = function(colour){
95 | var obj = Object.create(House.prototype); // generate object
96 |
97 | obj.colour = colour;
98 | obj.door = 'open'; //assign properties
99 |
100 | return obj;
101 | };
102 |
103 | //(Automatically generated by interpreter)
104 | //House.prototype = {};
105 |
106 | House.prototype.openDoor = function(){
107 | this.door = 'open';
108 | };
109 |
110 | House.prototype.closeDoor = function(){
111 | this.door = 'close';
112 | };
113 |
114 | var house = House('red'); //instantiation pattern
115 |
116 |
117 | ###Pseudoclassical
118 |
119 | Lastly we come to pseudoclassical. Instead of assigning the `Object.create(House.prototype)` to a new variable, it is assigned to `this` for the purpose of simple property assignment and method creation. The interpreter will do this automatically 'under the bonnet', and return the object, so long as the keyword `new` is initialised at instantiation `var house = new House('red')`. The disadvantage is that object creation is not that clear.
120 |
121 | var House = function(colour){
122 | //(Automatically generated by interpreter)
123 | //var this = Object.create(House.prototype);
124 | this.colour = colour;
125 | this.door = 'open';
126 |
127 | //(Automatically generated by interpreter)
128 | //return this;
129 | };
130 |
131 | //(Automatically generated by interpreter)
132 | //House.property = {}
133 |
134 | House.prototype.openDoor = function(){
135 | this.door = 'open';
136 | };
137 |
138 | House.prototype.closeDoor = function(){
139 | this.door = 'close';
140 | };
141 |
142 | var house = new House('red'); //instantiation pattern
143 |
144 |
145 | Instantiation happens when a functional class is utilized to create a new object,
146 |
147 | var house = House('red')
148 |
149 | Note that pseudoclassical is the only style that makes use of the `new` keyword, the other three classes are used like a function call.
150 |
151 | ###Summary
152 |
153 | None of these four are better or worse than each other to use, they are just styles. It is up to you as the programmer to decide which your program would benefit the most from.
154 |
155 | *Functional*
156 |
157 | * Most transparent and easy to understand
158 |
159 | * Higher memory cost because each instance retains its own properties
160 |
161 | *Functional-shared*
162 |
163 | * Offers memory cost advantage over functional
164 |
165 | * A bit more complex than functional
166 |
167 | *Prototypal*
168 |
169 | * Shared properties in a separate object and not extended within the instatiated object
170 |
171 | * Code is more complex to read
172 |
173 | *Pseudoclassical*
174 |
175 | * Often the most optimized pattern and very common
176 |
177 | * The keyword *this* can be difficult to understand
178 |
179 | ###Related
180 |
181 | [Objects](https://github.com/codingforeveryone/READMEs/blob/master/JavaScript/Objects.md)
182 |
183 | [Inheritance and JavaScript](http://codingforeveryone.foundersandcoders.org/JavaScript/inheritance-and-javascript.html)
184 |
185 | ###References
186 |
187 | [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript)
188 |
189 | [Udacity Object-oriented JavaScript course](https://www.udacity.com/course/object-oriented-javascript--ud015)
190 |
191 | [Instantiation patterns in JavaScript](http://callmenick.com/post/instantiation-patterns-in-javascript)
192 |
193 | JavaScript: The Good Parts - Douglas Crockford Chapter 5
194 |
--------------------------------------------------------------------------------
/JavaScript/JavaScript-Scope.md:
--------------------------------------------------------------------------------
1 |
2 | #JavaScript Scope: A Beginners Perspective
3 |
4 |
5 |
6 | ###Understanding scope is a fundamental part of learning any programming language, scope tells you where a variable is stored as well as where it can be accessed. Scope is also closely tied to a concept known as **[Hoisting](http://codingforeveryone.foundersandcoders.org/JavaScript/hoisting.html)**.
7 |
8 | ------------
9 |
10 | ###Different Types of Scope
11 |
12 | #####**Global Scope**
13 | In JavaScript there are now three main types of scope: Global, Local, Lexical, and now with ECMAScript 6 there is Block Level. We will start off with the Global Scope. When you declare a variable globally you are ensuring that the particular variable is available everywhere and so every single function has access to that variable. Here is an example of a Globally scoped variable.
14 |
15 |
16 | **Example of Global Scoped variable:**
17 | ```
18 | var global = 'everywhere';
19 |
20 | function scope(){
21 |
22 | var local = 'local'; //returns the string 'local'
23 |
24 | }
25 | console.log(global); //returns the string 'everywhere'
26 | ```
27 |
28 | > Things to note: You have to be wary when declaring Global variables as they can interact or possibly override other variables, which can ruin scripts and make your code harder to debug. Also, if a variable isn't declared explicitly with the `var` keyword it automatically becomes a Global variable.
29 |
30 | -----
31 | #####**Local Scope**
32 | So now that we've covered Global scope, let's move on to understanding a locally scoped environment. When you declare a Local variable, that variable or argument is only tied to that particular function, which means you can only use it in that environment. Essentially each function gives way to its own unique environment.
33 |
34 | **Example of Locally Scoped variable:**
35 |
36 | ```
37 | function scope(){
38 | var local = 'local'; //returns 'local'
39 | }
40 | console.log(local); //returns undefined.
41 |
42 | ```
43 |
44 | > Things To Note: Since the variable is defined locally it has no reference to the parent or global scope, so when you try to use the variable outside the function you will get an undefined value.
45 |
46 | ------
47 | #####**Lexical Scope**
48 |
49 | Lexical scope sounds a little tricky but it's actually pretty straightforward. When I think of 'lexical' in a programming environment I like to think that it means 'in relation to' or 'sharing'. You will see why: a lexical scope is basically a variable that is accessible within a nested function.
50 | **Example of Lexical Scoped variable:**
51 |
52 | ```
53 | function outer(){
54 | var lexical = 'local'; //returns 'local'
55 | //Scope A
56 | function inner() {
57 | // Variable lexical is accessible here
58 | //Scope B
59 | function inner() {
60 | // Variable lexical is accessible here
61 | //Scope C
62 | }
63 | }
64 | }
65 | ```
66 |
67 | > Things To Note: Lexically scoped variables are accessible down the scope chain but they will not work when trying to get values of variables hoisted above a function.
68 |
69 | ------------
70 | #####**Block Scope**
71 | The advent of ECMAScript 6 has brought us some new keywords, `let` and `const`. Block level scope refers to a variable that has its own scope, in other words a variable defined in an `if` statement will be tied to that particular statement and will not be accessible anywhere outside of it. So, when you declare a variable with the let or const keyword you are ensuring that the variable is block scoped.
72 |
73 | **Example of Block Scoped variable:**
74 |
75 | ```
76 | function outer(){
77 |
78 | if(){
79 | let block = 'block scope' //Will return Block Scope
80 | }
81 | block = 'local scope' //Will return reference error
82 | }
83 |
84 | ```
85 |
86 | > Things To Note: Block scoped variables also cannot be [hoisted](http://codingforeveryone.foundersandcoders.org/JavaScript/hoisting.html), the const variable has to have a value; if not it will throw a syntax error. Also, once a const has a declared value, it cannot be changed or an error will be thrown.
87 |
88 | ------------
89 |
90 |
91 | ####References
92 | #####[http://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/](http://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/)
93 |
94 | #####[http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/](http://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/)
95 |
96 | #####[http://www.sitepoint.com/joys-block-scoping-es6/](http://www.sitepoint.com/joys-block-scoping-es6/)
97 |
98 | #####[https://toddmotto.com/everything-you-wanted-to-know-about-javascript-scope/](https://toddmotto.com/everything-you-wanted-to-know-about-javascript-scope/)
99 |
100 | #####[http://ryanmorr.com/understanding-scope-and-context-in-javascript/](http://ryanmorr.com/understanding-scope-and-context-in-javascript/)
101 |
102 | [https://www.youtube.com/watch?v=aJixpk6Avxs](https://www.youtube.com/watch?v=aJixpk6Avxs)
103 |
104 | [https://www.udemy.com/understand-javascript/](https://www.udemy.com/understand-javascript/)
105 |
106 | -----------
107 |
108 |
--------------------------------------------------------------------------------
/JavaScript/JavaScript_Limitations.md:
--------------------------------------------------------------------------------
1 | # The Not So Good Parts of JavaScript
2 |
3 | JavaScript is quite an amazing programming language, despite what some in the development community have to say about it. It runs in web browsers, which is great as it's executed on the client side, as opposed to the server, making it faster for the end user. It makes web pages feel 'alive' with its interactivity. However there are also problems - for example, the fact it runs on the web browser makes it a security issue, as this can be used to exploit the user's system. This article is not a definitive guide of all the limitations of JavaScript, but it does cover common points that as a developer, you should be aware of.
4 |
5 | #### Multithreading
6 |
7 | Firstly JavaScript does not support multithreading. Multithreading is a way to manage multiple events, known as threads simultaneously, so that different stages of a program run at the same time without interfering with each other. Most modern programming languages like Java and C# support multithreading, so intensive code maybe executed. JavaScript runs in a single execution thread, this is a design feature which you cannot change. However multithreading may be simulated, so code which would freeze up the browser can be run. Using asynchronous timers which can run repetitive code at staggered times so the browser will have interpreter time to process separate iterations. HTML5 Web workers are multithreaded and allow a single javascript thread to run, thus giving the appearance that it is multithreaded.
8 |
9 | #### Separate Domain Access
10 |
11 | Web pages hosted on different domains cannot be accessed using JavaScript. This is based on the "Same origin policy", which prevents a document or script loaded from one origin, from getting or setting properties of a document from another origin. This policy dates all the way back to Netscape Navigator 2.0. It helps to ensure that potentially malicious documents/scripts can be isolated.
12 |
13 | A workaround is in place with HTML5 using postMessage interface, or using server side scripts using AJAX calls. There are a few methods to do this the common ones are _document.domain_ method which is an iframe method that sets the value of document.domain to a suffix of the current domain.
14 | ````
15 | For example, assume a script in the document at `http://shop.company.com/dir/other.html`
16 | which executes the following statement:
17 |
18 | document.domain = "company.com";
19 |
20 | After execution, the page would pass the origin check with http://company.com/dir/page.html.
21 | However, by the same reasoning, company.com could not set document.domain to othercompany.com.
22 |
23 | ````
24 | Using this you can execute javascript from an iframe. Please note that this is not suitable for Firefox which will not allow a change to `document.domain`
25 |
26 | Another notable method is `window.postMessage` which safely enables cross-origin communication. Cross-window messaging security model is two-sided. The sender ensures that the receiving domain is targetDomain. The receiver checks that the message came from proper event.origin.
27 |
28 | ````
29 | postMessage(data, targetDomain), where:
30 |
31 | data - The message. According to the specification, it could be any object. But as of now, only strings are supported in major browsers.
32 |
33 | targetDomain - Limit receiving iframe by given domain. Can contain ‘*’ which doesn’t put any restrictions.
34 | ````
35 |
36 |
37 | #### Database Access
38 |
39 | Accessing databases, in particular backend databases, is a problem without the help of a server side script like Ajax which performs the database access.
40 |
41 | One example would be a user wanting to select an item in a dropdown list, which is implemented by JavaScript and these items are in a database. A function could be used to show the dropdown details. This function would do the following.
42 |
43 | 1. Check if item is selected.
44 |
45 | 2. Create an XMLHttpRequest object.
46 |
47 | 3. Create the function to be executed when the server response is ready.
48 |
49 | 4. Send the request off to a file on the server.
50 |
51 | Then in turn the page on the server called by the JavaScript above is an ASP file called "getdetails.asp". This file would run a query against a database, and return the result in an HTML table
52 |
53 |
54 | #### Writing files to the server
55 |
56 | JavaScript cannot write to files on the server without the help of a server side script. Using Ajax, JavaScript can send a request to the server, which can read a file in XML or plain text format. However it cannot write to a file unless the file called on the server actually runs as a script, to do the file write for you.
57 |
58 | ````
59 | $.ajax({
60 | type: 'POST',
61 | url: url,//url of receiver file on server
62 | data: data, //your data
63 | success: success, //callback when ajax request finishes
64 | dataType: dataType //text/json...
65 | });
66 |
67 | ````
68 |
69 | #### Other
70 |
71 | JavaScript cannot close a window if it didn't open it, for obvious security reasons. Also, protection of page source or images is not done by JavaScript. Finally the option to disable JavaScript, many users disable it for security reasons. If your site is highly scripted and the user has disabled JavaScript then it can be disadvantageous to both parties.
72 |
73 | There are more limitations which are not mentioned here. As a developer it is good to be aware of pitfalls and work around them.
74 |
75 | ### Refernces
76 |
77 | [About Tech](http://javascript.about.com/od/reference/a/cannot.htm)
78 |
79 | [Sitepoint](https://www.sitepoint.com/multi-threading-javascript/)
80 |
81 | [Microsoft Developer Network](https://msdn.microsoft.com/en-us/hh549259.aspx)
82 |
83 | [Tutorials Point](http://www.tutorialspoint.com/javascript/javascript_overview.htm)
84 |
85 | [Stack Overflow Same Origin Policy](http://stackoverflow.com/questions/3076414/ways-to-circumvent-the-same-origin-policy)
86 |
87 | [window-postmessage](https://davidwalsh.name/window-postmessage)
88 |
89 | [w3 schools AJAX](http://www.w3schools.com/ajax/ajax_database.asp)
90 |
--------------------------------------------------------------------------------
/JavaScript/Objects.md:
--------------------------------------------------------------------------------
1 | #Objects
2 |
3 |
4 | ##Introduction
5 |
6 | 
7 |
8 | The following is a basic introduction to objects, covering what objects are, how to access their properties, how to create objects via the *object literal*, as well as by using *constructor functions*, and how to add new properties to an object.
9 |
10 | ##What is an object?
11 |
12 | An object is a list which contains items. Each of these items is stored by a _name:value_ pair. The values can be either primitive data types or reference data types. [Click here](http://codingforeveryone.foundersandcoders.org/programmer-skills/mutable-vs-immutable.html) to see the different behaviour of primitive and reference types.
13 |
14 |
15 |
16 | Let's take a look at an object:
17 |
18 | `var person = {firstName: "Ben", lastName: "Howard", age: 45};`
19 |
20 | In this example `firstName` and `lastName` are the _property names_ and the _values_ are `Ben` and `Howard`.
21 |
22 | ##Accessing object property values
23 |
24 | The property values are accessed by referring to their paired names. Property names can be either a number or a string. If the property name is a string, we can access its value with *dot notation* or *bracket notation*. If it is a number, we have to use bracket notation to access it.
25 |
26 | Dot notation:
27 |
28 | ```javascript
29 | var person = {firstName: "Ben", lastName: "Howard", age: 45};
30 | var family = {3: "Brothers", 5: "Sisters"};
31 | console.log(person.firstName); // Ben
32 | console.log(family.3); // SyntaxError. Does not work.
33 | ```
34 | Bracket notation:
35 |
36 | ```javascript
37 | console.log(person['firstName']); // Ben
38 | console.log(family[3]); // Brothers
39 | ```
40 | Note the required quotation marks around the string when using bracket notation.
41 |
42 | Functions stored within objects are referred to as *methods* of the object. To invoke a method of an object we use dot notation along with the parentheses that we normally use when invoking a function:
43 |
44 | ```javascript
45 | var person = {firstName: "Ben", greet: function(){return 'Hello!';}};
46 | person.greet(); // Hello
47 | ```
48 |
49 |
50 | ##Creating objects
51 |
52 | ###The object literal
53 | One way to create an object is the _object literal_. This is done by _name:value_ pairs inside curly braces as seen in the example given above:
54 |
55 | `var person = {firstName: "Ben", lastName: "Howard", age: 45};`
56 |
57 | Object literals can also be spread over more than one line which makes them easier to read:
58 |
59 | ```javascript
60 | var person = {
61 | firstName: "Ben",
62 | lastName: "Howard",
63 | age: 45,
64 | printAge: function() {
65 | console.log("I'm " + this.age + " years old."
66 |
67 | };
68 | ```
69 |
70 | ###The object constructor
71 | Another way to create objects is with the the _object constructor_. This does the same as the _object literal_ but it uses the `new` keyword to call the constructor:
72 |
73 | ```javascript
74 | var person = new Object();
75 | person.firstName = "Ben";
76 | person.lastName = "Howard";
77 | person.age = 45;
78 | ```
79 |
80 | In the first line we initialise the `person` object. In the following three lines we assign _name:value_ pairs to this object.
81 |
82 | Let's say we had ten different persons with different values. Using either of the previous ways of creating objects we would have to create that whole object ten different times. There are more efficient ways to do this: one of them is the _constructor pattern_.
83 |
84 | ```javascript
85 | function Person(firstName, lastName, age, profession) {
86 | this.firstName = firstName;
87 | this.lastName = lastName;
88 | this.age = age,
89 | this.profession = profession;
90 |
91 | this.showFullName = function() {
92 | console.log("My name is " + this.firsName + " " + this.lastName);
93 | }
94 | }
95 | ```
96 |
97 | When we use the `this` keyword we use it as a shortcut: it refers to the object of the executing code (the actual object you're creating or using).
98 |
99 | Now we can create different person objects by initialising the `Person` object. Note that we use a capital letter for the first letter of the function when we use the constructor pattern (in this case `Person`). This is a convention that signals that the `new` keyword must be used when calling the function:
100 |
101 | ```javascript
102 | var hobbit = new Person("Bilbo", "Baggins", 233, "Coding enthusiast");
103 |
104 | hobbit.showFullName();
105 | ```
106 | As we did with Bilbo we can create as many person objects (or hobbit objects) as we like.
107 |
108 | ##Adding object properties
109 | Remember that all instances of `Person` will inherit their properties from `Person`. If we wanted all the instances of `Person` to have a _height attribute_ then we would add it to the `Person` constructor.
110 |
111 | ```javascript
112 | function Person(firstName, lastName, age, profession, height) {
113 | this.firstName = firstName;
114 | this.lastName = lastName;
115 | this.age = age,
116 | this.profession = profession;
117 | this.height = height;
118 |
119 | this.showFullName = function() {
120 | console.log("My name is " + this.firsName + " " + this.lastName);
121 | }
122 | }
123 | ```
124 |
125 | If we wanted to add a property to one of the instances of `Person` then we would do it directly on the object itself:
126 |
127 | ```
128 | hobbit.favouriteFood = "Elf bread";
129 | ```
130 |
131 | Now Bilbo has his own property of `favouriteFood`, which is not an inherited one.
132 |
133 |
134 | ##Katas
135 |
136 | Here is a kata I created where you can try your hand at adding a function to a constructor object:
137 |
138 | [Paperboy 2](http://www.codewars.com/kata/56fa467e0ba33b8b1100064a)
139 |
140 | A couple more katas using objects:
141 |
142 | [Doggy Daycare](http://www.codewars.com/kata/56951add53eccacf44000030)
143 |
144 | [Shop inventory manager](http://www.codewars.com/kata/shop-inventory-manager)
145 |
146 | ##Related
147 |
148 | [Inheritance and Javascript](http://codingforeveryone.foundersandcoders.org/JavaScript/inheritance-and-javascript.html)
149 |
150 | ##References
151 | For basic tutorials explaining step by step how to put Objects into practise you can try [Introduction to Objects I](https://www.codecademy.com/en/courses/spencer-sandbox/resume?curriculum_id=506324b3a7dffd00020bf661) and [Introduction to Objects II](https://www.codecademy.com/en/courses/objects-ii/resume?curriculum_id=506324b3a7dffd00020bf661)
152 |
153 | For a more advanced introduction to objects in Javascript, see the articles [Working with objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects) and [Introduction to Object-Oriented Javascript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript) on the Mozilla Development Network..
154 |
--------------------------------------------------------------------------------
/JavaScript/array-map.md:
--------------------------------------------------------------------------------
1 | # Array `map()` method
2 |
3 |
4 | The `map()` method creates a new array, without altering the original, by applying a function to each element of the array. The transformation (or processing) is done by a callback function, which is specified as the first parameter of the method. Higher-order functions such as `map()`, `reduce()` or `filter()` are a shorter, more readable alternative to iterating through an array with a loop.
5 |
6 | ## Example
7 |
8 | Let's see one of the examples on the [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map). Assume that you have an array `[1, 4, 9]` and you want to create a new array containing the square roots of the numbers in the array.
9 |
10 | It is possible to loop through the array and construct a new array as shown below:
11 |
12 | ```javascript
13 | var numbers = [1, 4, 9];
14 | var roots = [];
15 |
16 | for (var i = 0; i < numbers.length; i++) {
17 | roots.push(Math.sqrt(numbers[i]));
18 | }
19 | console.log(roots);
20 | // [1, 2, 3]
21 | ```
22 |
23 | However, by using the `map()` method, you can write the same operation as shown below:
24 |
25 | ```javascript
26 | var numbers = [1, 4, 9];
27 | var roots = numbers.map(Math.sqrt);
28 | console.log(roots);
29 | // [1, 2, 3]
30 | ```
31 |
32 | This is much more concise. Brevity and simplicity reduce the potential for bugs to appear in your code.
33 |
34 | ## Callback function
35 |
36 | In this example, the callback function is `Math.sqrt()`, which takes a number as a parameter and returns the square root of the number. The `map()` method applies this callback function to each of the elements in the array (`numbers`) and returns an array containing the result of the callback function.
37 |
38 | 
39 |
40 | Often an anonymous function is used as a callback function. Just to illustrate the point, the same example can be written as shown below:
41 |
42 | ```javascript
43 | var numbers = [1, 4, 9];
44 | var roots = numbers.map(function(n) {
45 | return Math.sqrt(n);
46 | });
47 | console.log(roots);
48 | // [1, 2, 3]
49 | ```
50 |
51 | In this example, the callback function is an anonymous function and each element of the array is passed to the function as a parameter (`n`). The function returns the result of `Math.sqrt` of the parameter, and the `map()` method returns an array containing the output of the callback function.
52 |
53 | ## Parameters of the callback function
54 |
55 | The callback function can actually take 3 parameters. The first parameter is an element of the array, as in the example above. The second and the third parameters are the index of the element in the array and the array itself. So, the example above can also be written as shown below. The additional parameters are not particularly useful in this case, so the values are just displayed using `console.log`.
56 |
57 | ```javascript
58 | var numbers = [1, 4, 9];
59 | var roots = numbers.map(function(n, i, arr) {
60 | console.log('n = ' + n + ', i = ' + i + ', arr = ' + arr);
61 | return Math.sqrt(n);
62 | });
63 | console.log(roots);
64 | //n = 1, i = 0, arr = 1,4,9
65 | //n = 4, i = 1, arr = 1,4,9
66 | //n = 9, i = 2, arr = 1,4,9
67 | //[1, 2, 3]
68 | ```
69 |
70 | ## The second parameter of the `map()` method
71 |
72 | The `map()` method can take two parameters. The first parameter is a callback function, as we've seen above. The second parameter is optional and it is the value to be used as `this` in the callback function. When the second parameter is not specified, the default value of `this` is the `Window` object.
73 |
74 | To illustrate how this parameter works, the same example can be rewritten as shown below:
75 |
76 | ```javascript
77 | var numbers = [1, 4, 9];
78 | var roots = numbers.map(function(n) {
79 | return this.sqrt(n);
80 | }, Math);
81 | console.log(roots);
82 | // [1, 2, 3]
83 | ```
84 |
85 | As you can see, `Math` is specified as the second parameter, which is used as `this` in the callback function. (This is just an example of the usage and obviously there is not much point in using it in a simple case like this.)
86 |
87 | ## Slightly more practical example
88 |
89 | One slightly more practical example of using the `map()` method is transposing a 2-dimensional array (swapping rows and columns), which I found [here on StackOverflow](http://stackoverflow.com/questions/17428587/transposing-a-2d-array-in-javascript):
90 |
91 | ```javascript
92 | var newArray = array[0].map(function(col, i) {
93 | return array.map(function(row) {
94 | return row[i]
95 | })
96 | });
97 | ```
98 |
99 | For example,
100 |
101 | ```javascript
102 | var array = [
103 | [1, 2, 3],
104 | [4, 5, 6],
105 | [7, 8, 9]
106 | ];
107 |
108 | var newArray = array[0].map(function(col, i) {
109 | return array.map(function(row) {
110 | return row[i]
111 | })
112 | });
113 |
114 | print2DArray(array);
115 | // 1, 2, 3
116 | // 4, 5, 6
117 | // 7, 8, 9
118 |
119 | print2DArray(newArray);
120 | // 1, 4, 7
121 | // 2, 5, 8
122 | // 3, 6, 9
123 |
124 | // This function prints out a 2D array
125 | function print2DArray(arr) {
126 | arr.forEach(function(row) {
127 | console.log(row.join(', '));
128 | });
129 | }
130 | ```
131 |
132 | Two `map()` functions are used in this piece of code. The first `map()` obtains the indexes of the columns from the first row of the source array. The output of the first `map()` basically forms the rows in the new array. The second `map()` goes through the array and fills the rows. This might look a bit complicated, but the following image hopefully helps you understand how the code above works.
133 |
134 | 
135 |
136 | I have not found a practical example of using the second parameter of the `map()` method yet.
137 |
138 | ## Points to remember
139 |
140 | - The `map()` method returns a new array and the original array is not modified.
141 | - The `map()` method takes a callback function as a parameter, and the optional second parameter to be used as `this` in the callback function.
142 | - The callback function takes 3 parameters, the element of the array, the index of the element and the array itself.
143 |
144 | ## Related
145 |
146 | [Array methods overview](http://codingforeveryone.foundersandcoders.org/JavaScript/array-methods-overview.html)
147 |
148 |
149 | ## References
150 |
151 | - [Array.prototype.map() – MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
152 | - [From Map/Reduce to JavaScript Functional Programming](https://hacks.mozilla.org/2015/01/from-mapreduce-to-javascript-functional-programming/)
153 | - [Eloquent Javascript Chapter 5 - Chapter 5 Higher-Order Functions](http://eloquentjavascript.net/05_higher_order.html)
154 | - [Codecademy Advanced Array manipulation](https://www.codecademy.com/courses/javascript-advanced-en-eQcHT/0/1)
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
--------------------------------------------------------------------------------
/JavaScript/basic-performance-testing.md:
--------------------------------------------------------------------------------
1 | # Basic Performance Testing
2 |
3 | This guide will follow a worked example on how to go about comparatively performance testing functions. Performance testing is not a subject that should worry beginners, however, it is very interesting to look at and will become useful on complex projects.
4 |
5 | The following is almost certainly not the only (or necessarily the best) way, however, it is fairly easy to understand and use.
6 |
7 | ## The Functions
8 |
9 | We are tasked with performance testing two different ways of generating random strings 50 characters in length ([see random test cases guide](http://codingforeveryone.foundersandcoders.org/codewars/random-test-cases-for-complete-beginners.html).
10 |
11 | Our original function took the following form:
12 |
13 | ```javascript
14 | function makestring() {
15 | var text = "";
16 | var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
17 |
18 | for( var i=0; i < 50; i++ ) {
19 | text += possible.charAt(Math.floor(Math.random() * possible.length));
20 | }
21 | return text;
22 | }
23 | ```
24 |
25 | This received feedback that it is extremely ineffcient to sum X strings as it generates X-1 intermediate objects; but it is instead always better to use an array and finally perform a .join("") over them. So we created the following:
26 |
27 | ```javascript
28 | function makestring2() {
29 | var array = [];
30 | var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
31 | for( var i=0; i < 50; i++ ) {
32 | array.push(possible.charAt(Math.floor(Math.random() * possible.length)));
33 | }
34 | return array.join("");
35 | }
36 | ```
37 |
38 | ## Performance Test
39 |
40 | Now rather than just accepting the advice, how do we actually test these?
41 |
42 | Our chosen method is to make use of Javascript's `new Date()` constructor. This gives the time since 01 January 1970 00:00:00 UTC. The number is specified in milliseconds. Therefore if we wrap a for loop repeating the function in two variables that equal `new Date()` and find the difference between these variables we should have the time taken to perform the function. To give a large enough data set, consider repeating the function 20,000 times.
43 |
44 | ```javascript
45 | var start = new Date(); // log start timestamp
46 | for (var i = 0; i < 20000; i++) {
47 | console.log(makestring());
48 | }
49 | var end = new Date(); // log end timestamp
50 | var diff = end - start;
51 | console.log(diff.toString());
52 | ```
53 |
54 | and for the second function:
55 |
56 | ```javascript
57 | var start1 = new Date(); // log start timestamp
58 | for (var i = 0; i < 20000; i++) {
59 | console.log(makestring1());
60 | }
61 | var end1 = new Date(); // log end timestamp
62 | var diff1 = end1 - start1;
63 | console.log(diff1.toString());
64 | ```
65 |
66 | ## The Comparison
67 |
68 | By comparing the time taken to perform each function you will be able to get a rough idea of their performance. In this example, our `makestring()` takes approximately 2322 ms and our array function `makestring1()` takes approximately 323 ms.
69 |
70 | *Note: Values may not be constant between seperate runs, but will be in a similar range. Likewise consider moving `console.log(diff)` to end of function for ease of reading.*
71 |
72 | Moving beyond this example, the same method should be applicable to any other set of functions. Wrap a loop repeating functions in date variables, find the difference, compare!
73 |
74 | ## Appendix
75 |
76 | ### Complete Script
77 |
78 | ```javascript
79 | function makestring() {
80 | var text = "";
81 | var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
82 |
83 | for( var i=0; i < 50; i++ ) {
84 | text += possible.charAt(Math.floor(Math.random() * possible.length));
85 | }
86 | return text;
87 | }
88 |
89 | function makestring2() {
90 | var array = [];
91 | var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
92 | for( var i=0; i < 50; i++ ) {
93 | array.push(possible.charAt(Math.floor(Math.random() * possible.length)));
94 | }
95 | return array.join("");
96 | }
97 |
98 | var start = new Date(); // log start timestamp
99 | for (var i = 0; i < 20000; i++) {
100 | console.log(makestring());
101 | }
102 | var end = new Date(); // log end timestamp
103 | var diff = end - start;
104 |
105 | var start1 = new Date(); // log start timestamp
106 | for (var i = 0; i < 20000; i++) {
107 | console.log(makestring2());
108 | }
109 | var end1 = new Date(); // log end timestamp
110 | var diff1 = end1 - start1;
111 |
112 | console.log(diff.toString());
113 | console.log(diff1.toString());
114 | ```
115 |
116 |
117 |
118 |
119 |
120 |
--------------------------------------------------------------------------------
/JavaScript/by-value-and-by-reference.md:
--------------------------------------------------------------------------------
1 | #By Value and by Reference
2 |
3 | ###By Value
4 |
5 | Suppose we have a variable called `num` that contains a primitive:
6 |
7 | ```javascript
8 | var num = 8;
9 | ```
10 |
11 | This creates a new space in memory that contains the number `8`. It has an address just like people have addresses where they live. Numbers, Strings and Booleans are primitive values (primitives).
12 |
13 | If we then assign a new variable with the value of `num`:
14 |
15 | ```javascript
16 | var num2 = num;
17 | ```
18 |
19 | This creates another, new, space in memory (this is important, there are two separate spaces in memory now) and that memory space gets a copy of whatever the memory space of `num` contains, in this example the number `8`.
20 |
21 | ```javascript
22 | console.log(num);
23 | //-----> 8
24 | console.log(num2);
25 | //-----> 8
26 | ```
27 |
28 | The same process takes place for the other primitives and is what is called 'by value'. There are two separate addresses in memory and one contains a copy of the other value. They are now on their own and don’t affect each other. So if we change the value of `num` to `9` the variable `num2` is unaffected:
29 |
30 | ```javascript
31 | var num = 9;
32 | console.log(num);
33 | //-----> 9
34 | console.log(num2);
35 | //-----> 8
36 | ```
37 |
38 | **However** - Things work differently with objects.
39 |
40 | ###By Reference
41 |
42 | Suppose we have an object:
43 |
44 | ```javascript
45 | var person = { name: 'Sheldon' };
46 | ```
47 |
48 | And we also initialize another variable and make it equal to `person`:
49 |
50 | ```javascript
51 | var person2 = person;
52 | ```
53 |
54 | At this point, because we are dealing with objects rather than primitives no new memory space is created and no copy of the object is created and stored there. Instead, `person2` is now pointing at the same memory space as `person` and that memory space contains an object. We effectively now have two names (`person` and `person2`) for the same object. So we can access and change that one object through either of these two variables.
55 |
56 | The same result will be returned if we log the name property of either the `person` or `person2` object.
57 |
58 | ```javascript
59 | console.log(person.name);
60 | //-----> Sheldon
61 | console.log(person2.name);
62 | //-----> Sheldon
63 | ```
64 |
65 | And if we change the `name` property via, for example, the `person2` variable then logging via either variable will reflect the change.
66 |
67 | ```javascript
68 | person2.name = 'Wollowitz';
69 | console.log(person.name);
70 | //-----> Wollowitz
71 | console.log(person2.name);
72 | //-----> Wollowitz
73 | ```
74 |
75 | It doesn’t matter which of the two variables we use to change the name property because they are both pointing at the same object.
76 |
77 | This is called 'By Reference'.
78 |
79 | Just remember that primitives are by value (new memory space is created with a copy of the original value in it) and objects are by
80 | reference (we simply point to the same spot in memory, so we now have two names for the same thing).
81 |
--------------------------------------------------------------------------------
/JavaScript/conditional-operator.md:
--------------------------------------------------------------------------------
1 | #Conditional Operator
2 |
3 | ###What is it?
4 |
5 | The ternary operator (also called the conditional operator) allows us to return different values depending on the results of checks.
6 | It can be a cleaner and shorter alternative to the `if...else` statement.
7 |
8 | ###General syntax
9 |
10 | ```javascript
11 | var test = condition ? expr1 : expr2;
12 | ```
13 |
14 | `if...else` equivalent:
15 |
16 | ```javascript
17 | if (condition) {
18 | test = expr1;
19 | } else {
20 | test = expr2;
21 | }
22 | ```
23 |
24 | In this case, we check for the condition called `condition`. If it is true, then the var `test` is equal to `expr1`. Else, it is equal to `expr2`.
25 |
26 | ###Simple example
27 |
28 | ```javascript
29 | return condition ? "condition check result is true" : "condition check result is false";
30 | ```
31 |
32 | In this case, the first string is returned if the condition evaluates to `true`, otherwise the second string is returned.
33 |
34 | ###Combining conditional operators
35 |
36 | The ternary operator can also be used multiple times in a row:
37 | ```javascript
38 | var a = 5, b = 5;
39 | var compare = a > b ? "a is greater" : a < b ? "b is greater" : "a and b are equal";
40 | console.log(compare); // logs "a and b are equal"
41 | ```
42 |
43 | ###Combining different operations
44 |
45 | It is possible to use different operations for the two cases, and to use more than one operation per case. In this case, the operations should be separated from each other with a comma.
46 |
47 | Example:
48 | ```javascript
49 | function listTasks (time) {
50 | var list = [];
51 | time < 10 ? (
52 | console.log('Good morning!'),
53 | list.push('eat breakfast')
54 | ) : (
55 | console.log('Good day!'),
56 | list.push('do some work'),
57 | list.push('go for a walk')
58 | );
59 | return list;
60 | }
61 |
62 | listTasks(11);
63 | // logs 'Good day!'
64 | // returns ["do some work", "go for a walk"]
65 | ```
66 |
67 | It's an awesome tool that'll add readability to your code. Special thanks to warrior @GiacomoSorbi who posted a kata about it on the gitter channel ;).
68 |
69 | ###Related:
70 |
71 | [Kata:Training JS #7: if..else and ternary operator](http://www.codewars.com/kata/57202aefe8d6c514300001fd)
72 |
73 | [MDN Page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator)
74 |
--------------------------------------------------------------------------------
/JavaScript/inheritance-and-javascript.md:
--------------------------------------------------------------------------------
1 | #Inheritance and JavaScript
2 |
3 | Most modern object oriented programming (OOP) languages support the concept of inheritance. Think of inheritance as a child inheriting the functionality of its parent, where the child can add its own specifics. In this tutorial, I outline the difference between the version of inheritance found in C#, C++ or Java ("classical inheritance") and that found in Javascript ("prototypal inheritance"), and describe how prototypal inheritance in Javascript works. For a more detailed discussion of how to access and define prototypes, see [More on Javascript prototypes](http://codingforeveryone.foundersandcoders.org/JavaScript/prototypes-more.html)
4 |
5 | ##Classical inheritance
6 |
7 | Classical inheritance depends on the concept of classes. Classes may be thought of as blueprints.
8 |
9 | So for example in C#, C++ or Java we may have a Vehicle class, a parent blueprint, which will have a steering wheel, engine and wheels. This Vehicle can be specified further with the following classes of Car and Lorry, child blueprints, which can be specified further and so on. The important thing is that Car and Lorry both inherit from the Vehicle class.
10 |
11 | 
12 |
13 | Another way to look at this is that Car “_is A_” Vehicle and Hatchback “_is A_” Car. Inheritance of a class from a parent class exemplifies the "_Is A_" relationship. This is known as classical inheritance.
14 |
15 | However, JavaScript **DOES NOT SUPPORT** classical inheritance. It has no real concept of classes (the `class` keyword in [ECMAScript 6](/JavaScript/ECMAScript%206.html) is [syntactic sugar](https://en.wikipedia.org/wiki/Syntactic_sugar)). This is very important, especially if you have learned another class-based language. JavaScript is a Class-Free Object Oriented Language. It uses prototypal inheritance, which is where an object inherits from another object. This allows for a more flexible system of inheritance, since any object can be set up to inherit from any other. With a class-based system, the type distinction between objects and classes ensures that objects can only inherit from classes.
16 |
17 | ##Prototypal inheritance
18 |
19 | Prototypal inheritance is determined by the prototype property of an object. A prototype may be thought of as an object from which other objects inherit properties. The prototype itself may inherit from another object, so effectively it is a chain of objects. Therefore, object properties that are defined within the prototype object are inherited by all instances that reference it. This can be a bit confusing so it may be demonstrated as follows.
20 |
21 | ####An object and and an assigned property
22 | 
23 |
24 | In code, the property can be accessed by `obj.prop1`
25 |
26 | Besides properties which are assigned, all objects in JavaScript have a prototype property, which holds a reference to another object, the prototype. The protoype can also have a property. This property will be inherited, as shown in the example below.
27 |
28 | ####An object and an inherited property
29 |
30 | 
31 |
32 | Then what happens if we call `obj.prop2`?
33 | We are actually calling the prototype property _prop2_. It looks like _prop2_ is on the _obj_, however it is actually on _proto{}_.
34 |
35 | Now the prototype may also point to another prototype, in turn pointing to another prototype, forming a prototype chain.
36 |
37 | ####A prototype chain
38 |
39 | 
40 |
41 | Now, in this example, what happens if we call `obj.prop3`?
42 | We will actually call the property from _proto2{}_, itself a property of _proto{}_. We are calling down the prototype chain. We are seeing where we have access to the property amongst a sequence of objects.
43 |
44 | We can also have another object referencing _proto{}_, _obj2_:
45 |
46 | ####Multiple inheritance
47 |
48 | 
49 |
50 | Now if we call `obj2.prop1`, what happens?
51 | Then, `obj.prop1` is accessing the same property. `obj1` and `obj2` are effectively sharing the same property, not directly, but via the prototype chain.
52 |
53 |
54 | ##Example
55 |
56 | In code terms here is an example. Let's start by defining an object, `person` and assigning it some properties.
57 |
58 | ```javascript
59 | var person = {
60 | firstName: 'Default',
61 | lastName: 'Default',
62 | getFullName: function(){
63 | return this.firstName + ' ' + this.lastName;
64 | }
65 | }
66 | ```
67 | Now let's add another object called `ben`.
68 |
69 | ```javascript
70 | var ben = {
71 | firstName: 'Ben',
72 | lastName: 'Smith',
73 | }
74 | ```
75 |
76 | The next step is for demonstration purposes only and should not be used. It can, however, be done in most modern browsers. We can set the prototype of the `ben` object to the `person` object by using the inbuilt `__proto__` accessor. For information about `__proto__`, see [More on Javascript prototypes](http://codingforeveryone.foundersandcoders.org/JavaScript/prototypes-more.html).
77 |
78 | ```javascript
79 | ben.__proto__.person;
80 | ```
81 | Ben now inherits from `person`. If we try to access a property or method on `ben` which does not exist, the search will move to `person`. Let's try:
82 |
83 | ```javascript
84 | console.log(ben.getFullName()); //prints 'Ben Smith'
85 | console.log(ben.firstName); //prints 'Ben', NOT 'Default'
86 | ```
87 |
88 | What happens if we create a new object that only has a first name?
89 |
90 | ```
91 | var colin = {
92 | firstName: 'Colin'
93 | }
94 |
95 | colin.__proto__.person;
96 |
97 | console.log(colin.getFullName()); //prints 'Colin Default'
98 | ```
99 |
100 | So we can see that if a an object and its prototype have properties with the same name, the property will only be inherited from the prototype if it is missing in the object.
101 |
102 | The above was for example purposes only. So to conclude, **Prototypal Inheritance happens when an object's prototype attribute points to another object to inherit it’s attributes and methods.**
103 |
104 | ##Related
105 |
106 | [More on Javascript prototypes](/JavaScript/prototypes-more.md)
107 |
108 | ##References
109 |
110 | Youtube videos ([here](https://www.youtube.com/watch?v=qMO-LTOrJaE) and [here](https://www.youtube.com/watch?v=doXpW5AD60Q))
111 |
112 | Two articles ([Prototypal](http://javascript.crockford.com/prototypal.html) and [Inheritance](http://javascript.crockford.com/inheritance.html)) by Douglas Crockford
113 |
114 | [Prototypal inheritance examples](http://stackoverflow.com/questions/2064731/good-example-of-javascripts-prototype-based-inheritance) on Stackoverflow
115 |
116 | [Inheritance and the prototype chain](https://developer.mozilla.org/en/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) on MDN.
117 |
118 | [Detailed comparison of prototypal and classical inheritance](http://aaditmshah.github.io/why-prototypal-inheritance-matters/) by Aadit M. Shah.
119 |
120 |
121 |
122 |
123 |
--------------------------------------------------------------------------------
/JavaScript/large-numbers-in-js.md:
--------------------------------------------------------------------------------
1 | ## Arithmetic with large Numbers in JS
2 |
3 | #### Intro
4 |
5 | Consciously or otherwise, we rely heavily on large numbers in our every day lives. Through their prevalence in [current encryption methods](https://www.youtube.com/watch?v=M7kEpw1tn50), they have become central to our well-being: as we increasingly place our personal information in the digital realm, we become ever more reliant upon them. Applications of cryptography include ATM cards, computer passwords and broadcast encryption, amongst a host of others. The ability to maintain precision whilst handling large numbers is therefore vital to our safety, security and ultimately freedom of expression.
6 |
7 |
8 |
9 |
10 |
11 | #### Large Numbers in JS
12 |
13 | As specified by the [ECMAScript standard](http://www.ecma-international.org/ecma-262/5.1/#sec-8.5), all arithmetic operations in JavaScript are done using double-precision floating-point arithmetic. The "floating-point" format allows for a trade off between precision and range: a number is approximated to a fixed amount of "significant digits" (called the _Significand_) which is then scaled by an exponent. Given a certain total amount of digits to play with, the decimal point (or binary point in computing) can "float" relative to the Significand, increasing the range of real numbers that can be represented. Essentially, "floating-point" is a formulaic representation of a real number. It occupies 64 bits of computer memory.
14 |
15 | This system has its limitations. The binary floating-point format used by JS (binary64) has a standard specification:
16 |
17 | * **Sign bit**: 1 bit
18 |
19 | * **Exponent**: 11 bits
20 |
21 | * **Significand precision**: 53 bits
22 |
23 | Crucially, this gives us 15-17 significant decimal digits worth of precision.
24 |
25 | For example:
26 | ```javascript
27 | console.log(999999999999999) // 999999999999999
28 | console.log(9999999999999999) // 10000000000000000
29 |
30 | ```
31 |
32 | But what if we want to perform calculations on number strings with a larger number of digits? Our real integer values will no longer be precisely represented by the number format and will suffer from rounding errors.
33 |
34 | This is analogous to overflow: an inherent limitation of fixed-precision arithmetic. Consider trying to add 1 more unit to a 4-digit Odometer's display which currently reads 9999, rather than incrementing up to 10,000, it would reset to 0000. Similarly, a fixed-precision integer sometimes exhibits wraparound if the numbers involved grow too large to be represented at the fixed level of precision. Some processors overcome this problem via saturation (if a result can't be represented, it is replaced with the nearest representable value).
35 |
36 | But what about circumstances where we need to avoid overflow and saturation? The 53 bit limit becomes an issue whenever an API returns 64 bit numbers. For example, the Twitter API encodes tweets in JSON as follows:
37 |
38 | > {"id": 10765432100123456789, "id_str": "10765432100123456789", ...}
39 |
40 | The Twitter IDs detailed above are 64 bits long. JSON is a text format (so it can represent integers of arbitrary size) but precision will be lost in JavaScript when the ID is parsed:
41 |
42 | > parseInt("10765432100123456789")
43 | 10765432100123458000
44 |
45 | Therefore to retain the precise value of an ID in JavaScript, it needs to be stored in a string or an array.
46 |
47 | #### Workaround for Addition
48 |
49 | How can we perform basic operations on Large Numbers in JS? Here is a quick guide to one possible approach to performing addition (which incidentally may help in the Kata linked below):
50 |
51 | First of all, we need our two numbers stored in arrays, allowing us to maintain precision. Next, we need to ensure we allow for place value when combining our two arrays. We do this by reversing the arrays. This way, a[0] and b[0] are the least significant digits in their respective arrays and the place value is the same for both. Now we can loop through the arrays, adding each matching pair. But what if a pair sums to greater than 10? We then need to store 1 in a 'carry' variable which can then be added during the next iteration where the place value has increased by a factor of 10 (so our 1 is now worth 10). Also, if there's a 'carry' left over at the end, we need to add that too. This method follows the same principle as basic addition with pen and paper!
52 |
53 | ```JavaScript
54 |
55 | var a = []; // Your 1st number
56 | var b = []; // Your 2nd number
57 | var c = []; // Store the result in c
58 | var carry = 0; // Declare carry variable
59 | for (var i = 0; i < a.length; i++) {
60 |
61 | c[i] = a[i] + b[i] + carry;
62 |
63 | if(c[i] >= 10) { // Sum too large to fit into this place value
64 | carry = 1; // Set carry value to be added into the next digit
65 | c[i] -= 10;
66 | }
67 | else {
68 | carry = 0; // Sum was less than 10, so there's nothing to carry forward
69 | }
70 | }
71 | if (carry) { // Add the final carry if necessary
72 | c[i] = carry;
73 | }
74 |
75 | ```
76 | #### Related
77 |
78 | No doubt there are other approaches to adding Large Numbers together. There is definitely scope for this article to be extended, both in terms of types of Operations and in terms of describing alternative methods for handling Large Numbers. There is also potential to discuss and explore further real world Large Number applications. Related topics include:
79 |
80 | * Cryptography
81 | * Privacy vs Security
82 | * Using JavaScript libraries for arbitrary-precision decimal and non-decimal arithmetic
83 |
84 | #### References
85 |
86 | [Floating Point](https://en.wikipedia.org/wiki/Double-precision_floating-point_format)
87 |
88 | [Twitter Example](http://www.2ality.com/2012/07/large-integers.html)
89 |
90 | [Twitter Dev Documentation](https://dev.twitter.com/overview/api/twitter-ids-json-and-snowflake)
91 |
92 | [Arithmetic Operations](https://silentmatt.com/blog/2011/10/how-bigintegers-work/)
93 |
94 | [A relevant Kata](https://www.codewars.com/kata/sum-strings-as-numbers)
95 |
--------------------------------------------------------------------------------
/JavaScript/linked-list.md:
--------------------------------------------------------------------------------
1 | # The Linked List
2 | This tutorial presents a solution to a problem taken from chapter four of "Eloquent Javascript" concerning a special kind of data structure called a linked list. Since the book doesn't provide solutions, these are my own.
3 |
4 | I haven't understood yet how often linked lists are used in web development, but it was a good exercise to write one and I learned a lot. If someone is reading Eloquent Javascript and solving the exercises, we could compare our solutions.
5 |
6 | ##What is a linked list?
7 | If you are not familiar with lists, they look something like this:
8 | ```Javascript
9 | var list = {
10 | value: 1,
11 | rest: {
12 | value: 2,
13 | rest: {
14 | value: 3,
15 | rest: null
16 | }
17 | }
18 | };
19 | ```
20 | A list is a nested set of objects, where one object holds the reference to the next one.
21 |
22 | 
23 |
24 | The objects are sometimes referred to as "nodes" and the references as "pointers". Each node holds a value and a pointer to the next node, apart from the final node, whose pointer is null.
25 |
26 | Eloquent Javascript challenges us to write various functions to implement linked lists.
27 |
28 | ##1. Convert an array to a list
29 | The first task is to create a function that creates a list, starting from an array of integers:
30 | ```Javascript
31 | function arrayToList (arr){
32 | var list = {
33 | value: arr[arr.length-1],
34 | rest: null
35 | }
36 | for (var i = arr.length-1; i >= 0; i-- ){
37 | list = {
38 | value: arr[i],
39 | rest: list
40 | }
41 | }
42 | return list
43 | }
44 | ```
45 | The first function was easy to write without recursion. You can see that lists are easier to write from the last value backwards. That is why the array is traversed backwards.
46 |
47 | ##2. Convert a list to an array
48 |
49 | The second task is to create a function that transforms a list into an array:
50 | ```Javascript
51 | function listToArray(list){
52 | var res = []
53 | function traverse(list){
54 | if(list.rest == null) {
55 | return res
56 | } else {
57 | res.push(list.value)
58 | return traverse(list.rest)
59 | }
60 | }
61 | traverse(list)
62 | return res
63 | }
64 | ```
65 | Here, we use do use recursion: `traverse` adds the value of the current node to the array, then calls itself with the pointer to the next node as argument. The "base case" (when we stop the recursion) is when the pointer is null.
66 |
67 | ##3. Prepend a node
68 | The third task is to write a function that will prepend a node to an existing list:
69 | ```Javascript
70 | function prepend(value, list){
71 | return {
72 | value:value,
73 | rest: list
74 | }
75 | }
76 | ```
77 |
78 | ##4. Get the *nth* value
79 | The last task is to create a function that, given an integer and a list, returns the value held by the list at the position corresponding to the integer:
80 | ```Javascript
81 | function nth(pos,list){
82 | var counter = 0
83 | function reach(list){
84 | if (pos == counter) {
85 | return list.value
86 | } else {
87 | counter++
88 | return reach(list.rest)
89 | }
90 | }
91 | return reach(list)
92 | }
93 | ```
94 | This works similarly to converting a list to an array, except instead of adding each value to the array, we increment the counter. Here, the base case, when we return the value, is when the counter matches the desired number (`pos`).
95 |
96 | ## An object-oriented version
97 |
98 | So far our list is created and manipulated via a group of free-standing functions. However, we can easily package these functions with the list itself to create an object-oriented version.
99 |
100 | The first step is to write a constructor for `Node` objects, rather than writing them as object literals.
101 |
102 | ```Javascript
103 | function Node(value, rest) {
104 | this.value = value;
105 | this.rest = rest || null; // default value of null
106 | }
107 | ```
108 |
109 | In order to create a new terminal node, we can simply do the following:
110 |
111 | ```Javascript
112 | var list = new Node(5);
113 | ```
114 |
115 | We can then chain nodes together backwards to create a linked list:
116 |
117 | ```Javascript
118 | list = new Node(4, list);
119 | list = new Node(3, list);
120 | ```
121 |
122 | Of course, we don't want to do this manually, so we create a constructor which takes an array, turns it into a chain of nodes and stores this as the `head` attribute of a `LinkedList` object:
123 |
124 | ```Javascript
125 | function LinkedList(arr) {
126 | if (!arr) {
127 | this.head = null; // default head for empty lists
128 | } else {
129 | var list = new Node( arr[ arr.length - 1 ] )
130 | for ( var i = arr.length - 2; i >= 0; i-- ) {
131 | list = new Node( arr[i], list )
132 | }
133 | this.head = list;
134 | }
135 | }
136 | ```
137 |
138 | This constructor plays the role of the `arrayToList` function.
139 |
140 | We can now add the `listToArray`, `prepend` and `nth` functions, with some modifications, as methods of a `LinkedList` object.
141 |
142 | ```Javascript
143 | LinkedList.prototype.toArray = function toArray() {
144 | if (this.head === null) {
145 | return [];
146 | } else {
147 | var res = [];
148 | traverse(this.head);
149 | return res;
150 | }
151 |
152 | function traverse(head){
153 | res.push(head.value)
154 | if(head.rest !== null) {
155 | traverse(head.rest);
156 | }
157 | }
158 |
159 | };
160 |
161 | LinkedList.prototype.prepend = function prepend(value) {
162 | var n = new Node(value, this.head);
163 | this.head = n;
164 | };
165 |
166 | LinkedList.prototype.nth = function nth(index) {
167 | var counter = 0;
168 |
169 | function reach(head) {
170 | if (head == null) {
171 | throw "Index out of range";
172 | }
173 | if (index === counter) {
174 | return head.value;
175 | } else {
176 | counter++;
177 | return reach(head.rest);
178 | }
179 | }
180 |
181 | return reach(this.head);
182 | };
183 | ```
184 |
185 | Here's a demonstration of the usage of this object-oriented version:
186 |
187 | ```Javascript
188 | > var list = new LinkedList([4,5,6]);
189 | undefined
190 |
191 | > list;
192 | LinkedList {
193 | head: Node { value: 4, rest: Node { value: 5, rest: [Object] } } }
194 |
195 | > list.head;
196 | Node {
197 | value: 4,
198 | rest: Node { value: 5, rest: Node { value: 6, rest: null } } }
199 |
200 | > list.toArray();
201 | [ 4, 5, 6 ]
202 |
203 | > list.prepend('h');
204 | undefined
205 |
206 | > list.toArray()
207 | [ 'h', 4, 5, 6 ]
208 |
209 | > list.nth(0);
210 | 'h'
211 |
212 | > list.nth(1);
213 | 4
214 |
215 | > list.nth(2);
216 | 5
217 |
218 | > list.nth(3);
219 | 6
220 |
221 | > list.nth(4);
222 | "Index out of range"
223 | ```
224 |
225 |
226 | ##Related
227 |
228 | ##References
229 | [Linked list exercise in Eloquent Javascript](http://eloquentjavascript.net/04_data.html#h_nSTX34CM1M)
230 | [More fun with linked lists](http://code.tutsplus.com/articles/data-structures-with-javascript-singly-linked-list-and-doubly-linked-list--cms-23392)
--------------------------------------------------------------------------------
/JavaScript/math-object-beginner-guide.md:
--------------------------------------------------------------------------------
1 | ## JavaScript Math Object
2 | The Math object allows you to perform mathematical tasks on numbers. Below is a beginners guide to the syntax and methods available.
3 |
4 | *Math is not a constructor. All properties/methods of Math can be called by using Math as an object, without creating it.*
5 |
6 | ## Finding Integers
7 |
8 | **`Math.round()`** - Round a number to the nearest integer.
9 | ```javascript
10 | Math.round(2.5); // 3
11 | ```
12 | **`Math.floor()`** - Round a number downward to its nearest integer.
13 | ```javascript
14 | Math.floor(1.6); // 1
15 | ```
16 | **`Math.ceil()`** - Round a number upward to its nearest integer.
17 | ```javascript
18 | Math.ceil(1.4) // 2
19 | ```
20 | **`Math.max()`** - Return the number with the highest value from one or more numbers. Syntax `Math.max(n1,n2,n3,...,nX)`.
21 | ```javascript
22 | Math.max(14, 10, 5, 20) // 20
23 | ```
24 | **`Math.min()`** - Return the number with the lowest value from one or more numbers. Syntax `Math.min(n1,n2,n3,...,nX)`.
25 | ```javascript
26 | Math.min(14, 10, 5, 20) // 5
27 | ```
28 | **`Math.trunc()`** - Unlike other three Math methods: `Math.floor()`, `Math.ceil()` and `Math.round()`, the way `Math.trunc()` works is very simple and straightforward, just truncate (remove) the dot and the digits behind it, no matter whether the argument is a positive number or a negative number.
29 | ```javascript
30 | Math.trunc(1.213) // 1
31 | ```
32 | **`Math.sign(x)`** - Returns the sign of a number, indicating whether the number is positive, negative or zero.
33 | ```javascript
34 | Math.sign(-5) // -1
35 | ```
36 | This function has 5 kinds of return values, 1, -1, 0, -0, NaN, which represent "positive number", "negative number", "positive zero", "negative zero" and NaN respectively.
37 |
38 | ## Random Numbers
39 |
40 | **`Math.random()`** - Returns a random number between 0 (included) and 1 (excluded).
41 | ```javascript
42 | Math.random() // e.g 0.39622215856797993
43 | ```
44 | Commonly used in tandem with `Math.round()` to generate random integers for random tests cases in Codewars. See [Random Test Cases for Complete Beginners](http://codingforeveryone.foundersandcoders.org/codewars/random-test-cases-for-complete-beginners.html).
45 |
46 | ## Exponentiation
47 |
48 | The process of using exponents is called "raising to a power", where the exponent is the "power".
49 |
50 | **`Math.pow(x, y)`** - Return the value of the number `x` to be the power of `y`.
51 | ```javascript
52 | Math.pow(5, 4) // 625
53 | ```
54 | **`Math.sqrt(x)`** - Returns the square root of number `x`.
55 | ```javascript
56 | Math.sqrt(16) // 4
57 | ```
58 | **`Math.cbrt(x)`** - Returns the cube root of number `x`.
59 | ```javascript
60 | Math.cbrt(16) // 2
61 | ```
62 | Both square root and cube root can be replaced by `Math.pow(x, y)`. To find roots of numbers you must have input `y` as `1/y`. E.g.
63 | ```javascript
64 | Math.sqrt(16) // 4
65 | Math.pow(16, 0.5) // 4
66 | Math.cbrt(64) // 4
67 | Math.pow(256, 0.25) // 4
68 | ```
69 |
70 | **`Math.exp(x)`** -Returns the value of E^x, where E is Euler's number (approximately 2.7183) and `x` is the number passed to it.
71 | ```javascript
72 | Math.exp(1) // 2.718281828459045
73 | ```
74 | **`Math.log(x)`** -Returns the natural logarithm (base E) of number `x`.
75 | ```javascript
76 | Math.log(2) // 0.6931471805599453
77 | ```
78 |
79 | ## Trigonometry
80 |
81 | Trigonometry is a branch of mathematics that studies relationships involving lengths and angles of triangles. See more [here](https://en.wikipedia.org/wiki/Trigonometry).
82 |
83 | **`Math.sin(x)` & `Math.cos(x)`** - Returns the sine/cosine of angle `x` (**in radians not degrees!**).
84 | ```javascript
85 | Math.sin(3) // 0.1411200080598672
86 | Math.cos(3) // -0.9899924966004454
87 | ```
88 | Both methods return a value between -1 and 1. For more information on Sine & Cosine see [here](https://en.wikipedia.org/wiki/Sine).
89 |
90 | **`Math.asin(x)` & `Math.acos(x)`** - Returns the arcsine/arccosine of number `x`.
91 | ```javascript
92 | Math.asin(0.5) // 0.5235987755982989
93 | Math.acos(0.5) // 1.0471975511965979
94 | ```
95 | The `asin()` method returns the arcsine of a number as a value between -PI/2 and PI/2 radians. The `acos()` method returns the arccosine of a number as a value value between 0 and PI radians. If the parameter `x` is outside the range -1 to 1, the method will return NaN. For more information on arcsine & arccosine see [here](https://en.wikipedia.org/wiki/Inverse_trigonometric_functions).
96 |
97 | **`Math.tan(x)`** - Returns the tangent of a number `x` representing an angle (in radians).
98 | ```javascript
99 | Math.tan(90) // -1.995200412208242
100 | ```
101 | **`Math.atan(x)`** - Returns the arctangent of a number `x`.
102 | ```javascript
103 | Math.atan(2) // 1.1071487177940904
104 | ```
105 | The `atan()` method returns the arctangent of a number as a value between -PI/2 and PI/2 radians.
106 |
107 | *Note that the trigonometric functions (sin(), cos(), tan(), asin(), acos(), atan(), atan2()) expect or return angles in radians. To convert radians to degrees, divide by (Math.PI / 180), and multiply by this to convert the other way.*
108 |
109 | Example kata:
110 |
111 | [Triangle Type](http://www.codewars.com/kata/triangle-type)
112 |
113 | [Wind Component Calculation](http://www.codewars.com/kata/542c1a6b25808b0e2600017c)
114 |
115 | [Convert Between Radian and Degrees](http://www.codewars.com/kata/convert-between-radians-and-degrees)
116 |
117 |
118 | ## Constants
119 |
120 | As well as having methods, the Math object also allows you to access some mathematical contants as properties. There is a programming convention of writing constants in UPPERCASE as opposed to camelCase. So the Pi property of Math is written `Math.PI` instead of `Math.pi` or `Math.Pi`. Constants are defined with the full precision of real numbers in JavaScript.
121 |
122 | **`Math.E`** - Euler's constant and the base of natural logarithms, approximately 2.718.
123 |
124 | **`Math.LN2`** - Natural logarithm of 2, approximately 0.693.
125 |
126 | **`Math.LN10`** - Natural logarithm of 10, approximately 2.303.
127 |
128 | **`Math.LOG2E`** -Base 2 logarithm of E, approximately 1.443.
129 |
130 | **`Math.LOG10E`** - Base 10 logarithm of E, approximately 0.434.
131 |
132 | **`Math.PI`** - Ratio of the circumference of a circle to its diameter, approximately 3.14159.
133 |
134 | **`Math.SQRT1_2`** - Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.
135 |
136 | **`Math.SQRT2`** - Square root of 2, approximately 1.414.
137 |
138 | ## References
139 |
140 | There are a number of Math object resources on the web, the above is a simplied and combined version of the following resources:
141 |
142 | [W3Schools JavaScript RegExp Math Object Reference](http://www.w3schools.com/jsref/jsref_obj_math.asp)
143 |
144 | [Mozilla Developer Network Math Object](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Math)
145 |
--------------------------------------------------------------------------------
/JavaScript/modulo-operator.md:
--------------------------------------------------------------------------------
1 | #Modulo
2 | This is an introduction to *modulo*, one of the many Javascript operators. It explains what modulo does and describes some of its important uses.
3 |
4 | ##What is modulo?
5 |
6 | Modulo is represented by the `%` symbol and it evaluates the remainder of a division.
7 |
8 | E.g., six fits entirely into 15 twice, with three left over (the remainder).
9 |
10 | #####Example 1
11 |
12 | ```javascript
13 | var result = 11 % 3;
14 |
15 | console.log(result); //prints 2
16 | ```
17 |
18 | `3` goes into `11` in its entirety, _three_ times (3 × 3 = 9). This leaves a remainder of two. Making `result` equal `2` (11 - 9 = 2).
19 |
20 | 
21 |
22 | #####Example 2
23 |
24 | ```javascript
25 | var resultTwo = 25 % 3.5;
26 | ```
27 |
28 | In this example `resultTwo` equals `0.5` as `3.5` goes into `25` _seven_ times (3.5 × 7 = 24.5), leaving a remainder of `0.5`.
29 |
30 | ##Important Uses
31 |
32 | The modulo operator can be used in a number of other useful cases:
33 |
34 | You can use it to test whether an integer is odd or even:
35 |
36 | ```javascript
37 | function oddOrEven(n) {
38 | if (n % 2 === 0) return "even"
39 | if (n % 2 === 1) return "odd"
40 | }
41 | ```
42 | Or whether a number is an integer:
43 |
44 | ```javascript
45 | function isInteger(n) {
46 | if (n % 1 === 0) return "Integer"
47 | if (n % 1 !== 0) return "Not Integer"
48 | }
49 | ```
50 |
51 | In, for example, prime number generation it can be used to test whether a candidate integer y has a divisor x:
52 |
53 | ```javascript
54 | function isDivisor(y, x) {
55 | if (y % x !== 0) return "Not divisor"
56 | if (y % x === 0) return "Divisor"
57 | }
58 | ```
59 |
60 | ##Warning!
61 |
62 | In some other languages, the result of the modulo operation takes the sign of the divisor (the number doing the dividing). In Javascript, it takes the sign of the dividend (the number being divided into). So:
63 |
64 | ```javascript
65 | var result = -11 % 3;
66 | console.log(result); //prints -3
67 | var resultTwo = 11 % -3;
68 | console.log(resultTwo); //prints 3
69 | ```
70 | This is important to remember when implementing tests like those in the previous section. For example, the following function will return `'odd'` for positive odd numbers, but `'even'` for negative odd numbers:
71 |
72 | ```javascript
73 | function oddOrEven(n) {
74 | if (n % 2 === 1) return 'odd';
75 | else return 'even';
76 | }
77 | ```
78 |
79 | ##Katas
80 |
81 | Here is a kata I created to practise using modulo:
82 |
83 | [Paperboy](http://www.codewars.com/kata/56ed5f13c4e5d6c5b3000745)
84 |
85 | Here are some example katas that can be solved with the modulo operator:
86 |
87 | [Fizz Buzz](http://www.codewars.com/kata/5300901726d12b80e8000498)
88 |
89 | [Normalizing out of range array indexes](http://www.codewars.com/kata/5285bf61f8fc1b181700024c)
90 |
91 | ##Related
92 |
93 | [Math object](http://codingforeveryone.foundersandcoders.org/JavaScript/math-object-beginner-guide.html)
94 |
95 | ##References
96 |
97 | Here's a link to the documentation of the modulo operator:
98 |
99 | [Remainder operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder)
100 |
101 |
102 |
103 |
104 |
--------------------------------------------------------------------------------
/JavaScript/recursive-function.md:
--------------------------------------------------------------------------------
1 | # Recursive Functions
2 |
3 | A recursive function is a function that, at some point during it's execution, calls itself. This type of function can be very useful for iterating over data where the total number of elements/objects is not readily apparent, such as in a linked list; or branching is required to access all elements, as in an array whose elements may be arrays which may contain further arrays as elements. In this tutorial, we'll look closely at how recursive functions work over several examples.
4 |
5 | ## Anatomy of a Recursive Function
6 |
7 | A recursive function will typically first check if a condition is satisfied. This condition is called the **base case**. If the condition is met, the function will return a value or perform some other task. If the condition is not met, the function will return a call to itself with **modified** arguments. This cycle will continue until the condition is met, returning any target value back through the stack to the initial call.
8 |
9 | ##### Example 1 - Searching a [linked list](JavaScript/linked-list.md)
10 | ```javascript
11 | function searchList(list, named){
12 | if (list == null){return 'Not Found';}
13 | if (list.name == named){
14 | return list.status;
15 | } else {
16 | return searchList(list.next, named);
17 | }
18 | }
19 |
20 | var sunnyVale = {name: 'Ricky',
21 | status: 'Resident',
22 | next: {name: 'Bubbles',
23 | status: 'Resident',
24 | next: {name: 'Julian',
25 | status: 'Resident',
26 | next: {name: 'Lahey',
27 | status: 'Park Supervisor',
28 | next: {name: 'Randy',
29 | status: 'Assistant Park Supervisor',
30 | next: null}}}}};
31 |
32 | searchList(sunnyVale, 'Lahey'); //returns 'Park Supervisor'
33 | searchList(sunnyVale, 'Randy'); //returns 'Assistant Park Supervisor'
34 | searchList(sunnyVale, 'Julian'); //returns 'Resident'
35 | searchList(sunnyVale, 'Bubbs'); //returns 'Not Found'
36 | ```
37 | In the example above, the function ```searchList``` takes 2 arguments, a linked list called ```list```; and a string called ```named```. ```searchList``` first checks if ```list``` is null (which would mean we have come to the end of the list) and returns ```'Not Found'``` if so. The function then checks if the list property ```name``` equals the variable ```named``` we are looking for. If ```list.name``` matches ```named```, then the value of `list.status` is returned. If not, ```searchList``` calls itself with ```list.next``` as the list to check. This continues like a loop until the right ```name``` is found, or the list ends.
38 |
39 | ##### Example 2 - Adding two numbers
40 | ```javascript
41 | function sum(num, add){
42 | if (add===0){return num}
43 | else {
44 | num += 1;
45 | return sum(num, add-1)
46 | }
47 | }
48 | sum(9,10); //returns 19
49 | ```
50 | In this example, function ```sum``` adds two numbers. It does this by adding 1 to ```num``` and returning a call to ```sum``` with the argument ```add``` decremented by 1. When ```add``` is 0, ```num``` (having been incremented by 1 ```add``` number of times) is returned.
51 |
52 |
53 | ##### Example 3 - Finding a number's factorial
54 | ```javascript
55 | function factorial(n){
56 | if (n==0 || n==1){
57 | return 1;
58 | }
59 | return factorial(n-1)*n;
60 | }
61 | factorial(2) // return 2
62 | ```
63 | A factorial number is defined as follows: 
64 |
65 | In this example, the base case is n = 1. n = 0 is added as alternative to take into account the value zero as input.
66 |
67 | When the function is invoked, for example with the value 2 as input, one instance of the function is added to the execution stack. Since n is not equal to the base case, the function calls itself again, this time with the input value of n-1, which is one. The first created instance of the function remains in the execution stack as it waits for the second instance to return a value. In the second instance of the function the base case is met, and one is returned to the first instance. The value is multiplied by the value of n inside the first instance, so 1*2, and then returned. The result, as expected, is 2.
68 |
69 | This is a classic example used for recursion, as there is a significant advantage in calculating a factorial in this way, in terms of simplicity of code. Try to solve the same problem using a for loop to see for yourself.
70 |
71 | ##### Example 4 - The Fibonacci Sequence
72 |
73 | A common problem found in many Codewars kata is how to generate the Fibonacci sequence. The first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1 and each subsequent number is the sum of the previous two.
74 |
75 | The first method we’re going to look at is by looping since it is often easier for people to wrap their head around.
76 |
77 | ```javascript
78 | var looping = function(n) {
79 | var a = 0, b = 1, f = 1;
80 | for(var i = 2; i <= n; i++) {
81 | f = a + b;
82 | a = b;
83 | b = f;
84 | }
85 | return f;
86 | };
87 | ```
88 |
89 | We know that each Fibonacci number is the sum of the previous two sequence numbers, which is why we are starting our loop at index two, which is really the third value since our index starts at zero. The first two numbers in our sequence are zero and one. The goal is to find the Fibonacci number at a certain sequence index, which in this example is fifteen.
90 |
91 | Every loop iteration we are summing the previous two sequence values, then pushing our values up, in a sense. By this I mean that `a` is dropped off and replaced with `b` and `b` is replaced with the current index value of the sequence, being our new sum. When our loop has reached our desired fifteen index, we can return whatever the new sum value is.
92 |
93 | Now let’s take a look at the recursive version of this.
94 |
95 | ```javascript
96 | var recursive = function(n) {
97 | if(n <= 2) {
98 | return 1;
99 | } else {
100 | return recursive(n - 1) + recursive(n - 2);
101 | }
102 | };
103 | ```
104 | Recursion can be a little tricky to wrap your head around. In the above code, we are going to plan on receiving the sequence value at index five because anything larger is going to be rough for me to type out. You can break this down like the following:
105 |
106 | ```javascript
107 | recursive(4) + recursive(3)
108 | (recursive(3) + recursive(2)) + (recursive(2) + recursive(1))
109 | ((recursive(2) + recursive(1)) + 1) + (1 + 1)
110 | ((1 + 1) + 1) + (1 + 1)
111 | 5
112 | ```
113 | You can see above that on every line the function is one further iteration through the recursive process. Based on our function logic, as soon as n <= 2 then we just return a value of one. At the furthest breakdown, our sum turns into five which is the Fibonacci number at index five.
114 |
115 | Example Kata -> [Fibonacci Reloaded](http://www.codewars.com/kata/fibonacci-reloaded) & [Complete Fibonacci Series](http://www.codewars.com/kata/complete-fibonacci-series).
116 |
117 |
118 | ## Drawbacks
119 | Recursive functions have two main drawbacks. One is that repeatedly calling a function is less efficient when a standard ```for``` or ```while``` loop will do the job. The other is that each recursive call adds another function to the stack, consuming more and more memory each time. Calling ```sum``` from Example 2 like this: ```sum(9,100000);``` would result in a 'Range' or 'Too much recursion' error as the stack would overflow.
120 |
121 | Consult the links below for a tutorial on *Tail Call Optimisation* for further information.
122 |
123 |
124 | ##Related
125 |
126 | * [Linked Lists](http://codingforeveryone.foundersandcoders.org/JavaScript/linked-list.html)
127 |
128 | ## References
129 | * [Understanding recursion in functional JavaScript Programming](http://www.integralist.co.uk/posts/js-recursion.html) TCO using *Trampolining*
130 | * [Wikipedia entry on the call stack](https://en.wikipedia.org/wiki/Call_stack)
131 | * [Wikipedia entry on stack overflow](https://en.wikipedia.org/wiki/Stack_overflow)
132 |
--------------------------------------------------------------------------------
/JavaScript/replace-method.md:
--------------------------------------------------------------------------------
1 | #String `replace()` Method
2 |
3 | ###Introduction
4 |
5 | Sometimes in JavaScript we may want to replace all or part of a string with something else. We can do this with the `replace()` method, which searches a string for a specified pattern, and returns a new string that has had the matches substituted with a replacement.
6 |
7 | ###Syntax
8 |
9 | The syntax of the `replace()` method is as follows:
10 |
11 | ``` javascript
12 | str.replace(regexp|substr, newSubStr|function)
13 | ```
14 |
15 | In other words, the pattern can be either a regular expression or a specific string, and the replacement can be either a string or a function.
16 |
17 | Note that `replace()` does **not** change the original string.
18 |
19 | ###Simple strings
20 |
21 | In this example, we replace a specific string ('yellow') with a replacement string ('red'):
22 |
23 | ```javascript
24 | var greeting = 'Hello, do you like yellow?';
25 | var myString = greeting.replace('yellow', 'red');
26 |
27 | console.log (myString);
28 | // 'Hello, do you like red?'
29 | ```
30 |
31 | ###Specifying a string as a parameter
32 |
33 | The replacement string can include a number of replacement patterns:
34 |
35 | Pattern | Effect
36 | --- | --- | ---
37 | $& | Inserts the matched substring
38 | $` | Inserts the portion of the string that precedes the matched substring
39 | $' | Inserts the portion of the string that follows the matched substring
40 |
41 | Note that the special character `$` can be escaped using `$$`.
42 |
43 | Example:
44 |
45 | ```javascript
46 | var greeting = 'Hello, do you like yellow?';
47 | var myString = greeting.replace('yellow', 'the colour $&');
48 |
49 | console.log (myString);
50 | // 'Hello, do you like the colour yellow?'
51 | ```
52 |
53 | ###Regular expressions
54 |
55 | Using `replace()` with specific strings, we can only replace a single occurrence of the target string, and we cannot match in a case-independent manner. Both of these shortcomings can be solved using regular expressions.
56 |
57 | ```javascript
58 | var sentence = 'I do like yellow; YELLOW is my favourite colour.';
59 | var myString = sentence.replace(/yellow/gi, 'red');
60 |
61 | console.log (myString)
62 | // 'I do like red; red is my favourite colour.'
63 | ```
64 |
65 | Regular expressions allow more sophisticated replacements. In the following example, we replace each 'inner' character of each word with an asterisk.
66 |
67 | ```javascript
68 | var sentence = 'Hello, do you like yellow?';
69 | var myString = sentence.replace(/\B.\B/g, '*');
70 |
71 | console.log (myString);
72 | // 'H***o, do y*u l**e y****w?'
73 | ```
74 |
75 | ###Using captured groups
76 |
77 | In the case of regular expressions, different portions of the matched pattern can be referred to using replacement patterns. The notation here is `$n` or `$nm`, where `n` and `nm` are decimal digits and refer to the `n`th (or `nm`th) captured group (submatch) in the regular expression.
78 |
79 | In the following example, we use replacement patterns to swap the words 'you' and 'do':
80 |
81 | ```javascript
82 | var sentence = 'Hello, you do like yellow?';
83 | var myString = sentence.replace(/(you)\s(do)/, '$2 $1');
84 |
85 | console.log (myString);
86 | // 'Hello, do you like yellow?'
87 | ```
88 |
89 | ###Using inline functions
90 |
91 | In addition to using a specific string or a replacement pattern, the second parameter of the `replace()` method can also be a function. In this case, the function's return value will be used as the replacement string. This allows the `replace()` method to be integrated with various other JavaScript features, which can be very powerful.
92 |
93 | The function takes in the following arguments:
94 |
95 | Name | Supplied value
96 | --- | --- | ---
97 | match | The matched substring
98 | p1, p2 etc. | The nth captured group (submatch)
99 | offset | The offset of the matched substring
100 | string | The whole string being examined
101 |
102 | In the following example, we use an inline function to implement the method `.toLowerCase()` within a call to `replace()`. We apply the method to all the characters except for the first character in the string, by specifying an appropriate regular expression:
103 |
104 | ```javascript
105 | var sentence = 'HELLO, DO YOU LIKE YELLOW?';
106 | var myString = sentence.replace(/(?!^).*/, x => x.toLowerCase());
107 |
108 | console.log (myString);
109 | // 'Hello, do you like yellow?'
110 | ```
111 |
112 | ###Related
113 | - [String dissection and manipulation](http://codingforeveryone.foundersandcoders.org/JavaScript/string-dissection-and-manipulation.html)
114 | - [Regular Expression Beginners' Guide](http://codingforeveryone.foundersandcoders.org/JavaScript/regular-expressions-beginners-guide.html)
115 |
116 | ###References
117 |
118 | - [W3Schools](http://www.w3schools.com/jsref/jsref_replace.asp)
119 | - [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)
120 | - [Using string replace in Javascript](https://davidwalsh.name/string-replace-javascript)
121 |
--------------------------------------------------------------------------------
/JavaScript/scope-and-hoisting.md:
--------------------------------------------------------------------------------
1 | #Variable scope and hoisting
2 |
3 | -
4 |
5 | Variable scope is the context where the variable is accessible from, or also, where it is visible.
6 |
7 | Variables have local scope or global scope and all variables declared outside of a function are in the global scope. This means they are available everywhere.
8 |
9 | Unlike most languages which have block-level scope, JavaScript has what is called function-level scope. Variables which are declared inside a function are local to the function they are declared in. These variables are only accessible inside that function, or to a function inside that function.
10 |
11 | -
12 |
13 | 
14 |
15 | ###Function level scope
16 |
17 | ```javascript
18 | var myName = "Marty McFly";
19 |
20 | function printName(name) {
21 | var myName = "Biff Tannen";
22 | console.log(myName);
23 | }
24 |
25 | printName(); // logs Biff Tannen
26 |
27 | console.log(myName); // logs Marty McFly
28 | ```
29 |
30 | Only inside of the function are we able to access the value `Biff Tannen`, as it is in the local scope of the `printName` function, and not visible anywhere else but in that function.
31 |
32 | -
33 |
34 | ###No block-level scope
35 |
36 | ```javascript
37 | var name = "Chunk";
38 |
39 | if (name) {
40 | var name = "Mouth";
41 | console.log(name); // logs Mouth
42 | }
43 |
44 | console.log(name) // logs Mouth
45 | ```
46 |
47 | We don't create a local context for the variable `name` inside the `if` statement. Javascript only does this with _functions_. When we `console.log(name)` it is still the global variable but we have re-assigned the value of `Mouth` to it inside of the `if` statement.
48 |
49 | -
50 |
51 | ###Not declaring variables
52 |
53 | 
54 |
55 | If we don't declare variables with the `var` keyword, and there is a global variable of the same name, then it is assumed you are referring to the global variable.
56 |
57 | ```javascript
58 | var name = "E.T";
59 |
60 | function printAlienName() {
61 | console.log(name);
62 | }
63 |
64 | function printPersonName() {
65 | name = "Elliot";
66 | console.log(name);
67 | }
68 |
69 | printAlienName(); // logs E.T
70 |
71 | printPersonName(); // logs Elliot
72 |
73 | printAlienName(); // logs Elliot
74 | ```
75 | Here, when we use `name = "Elliot"` inside of the function, we re-assign the global variable to `Elliot`. To avoid this all we need to do is declare the variable inside `printPersonName()` like this:
76 |
77 | ```javascript
78 | var name = "Elliot";
79 | ```
80 |
81 | -
82 |
83 | ###Local variables have priority over global variables in functions
84 |
85 | If we declare both a local and global variable with the same name, the local variable will always have priority when used inside the function.
86 |
87 | ```javascript
88 | var name = "Han Solo"
89 |
90 | function printName(){
91 | var name = "R2-D2";
92 | console.log(name);
93 | }
94 |
95 | printName(); // logs R2-D2
96 | ```
97 |
98 | When we run `printName` the search for `name` starts inside of the function. When a match is found within the function, the search completes there.
99 |
100 | -
101 |
102 | We should always do what we can to keep global variables to an absolute minimum and avoid the following.
103 |
104 | ```javascript
105 | var firstName = "Indiana";
106 | var lastName = "Jones";
107 |
108 | function printFullName() {
109 | console.log(firstName + " " + lastName);
110 | }
111 | ```
112 |
113 | In keeping them as local variables we can make sure they don't get reassigned down the track and cause unexpected results.
114 |
115 | This is how we should run the same code:
116 |
117 | ```javascript
118 | function printFullName(){
119 | var firstName = "Indiana";
120 | var lastName = "Jones";
121 |
122 | console.log(firstName + " " + lastName);
123 | }
124 | ```
125 | -
126 |
127 | ###Variable Hoisting
128 |
129 | 
130 |
131 | Variable declarations inside of a function are hoisted and delared at the top of the function.
132 |
133 | ```javascript
134 | function printName() {
135 | console.log("First Name: " + name);
136 | var name = "Miyagi";
137 | console.log("Last Name:" + name);
138 | }
139 |
140 | printName();
141 | // First Name: undefined
142 | // Last Name: Miyagi
143 | ```
144 |
145 | The variable `name` gets hoisted to the top of the function. It's as if the code had been written like this:
146 |
147 | ```javascript
148 | function printName() {
149 | var name;
150 | console.log("First Name: " + name);
151 | var name = "Miyagi";
152 | console.log("Last Name:" + name);
153 | }
154 | ```
155 |
156 | The variable `name` is hoisted but without the value assigned to it, which is why we get a `First Name: undefined`. Then the value is assigned when we declare the variable `name` and `Last Name: Miyagi` is printed.
157 |
158 | ###Function declaration takes precedence over variable declaration
159 |
160 | Lets first remember that neither variable nor function assignments (_values_) are hoisted, only variable and function _declarations_. A function declaration overrides a variable declaration.
161 |
162 | Let's now take a look at how function declaration takes precedence.
163 |
164 | ```javascript
165 | function characterName() {
166 | console.log("Daniel");
167 | }
168 |
169 | var characterName;
170 |
171 | console.log(typeof characterName); // logs function
172 | ```
173 |
174 | Although if we were to assign a value to the variable (variable assignment) then this would take precedence.
175 |
176 | ```javascript
177 | var characterName = "Falkor";
178 |
179 | function characterName() {
180 | console.log("Bastian");
181 | }
182 |
183 | console.log(typeof characterName) // logs string
184 | ```
185 |
--------------------------------------------------------------------------------
/JavaScript/shortcuts.md:
--------------------------------------------------------------------------------
1 | #JavaScript shortcuts
2 |
3 | In this topic we're going to cover a few simple JavaScript shortcuts. Consider this code:
4 |
5 | ```javascript
6 | function userName(name) {
7 | if (!name) {
8 | name = "Not applicable";
9 | }
10 |
11 | return name;
12 | }
13 |
14 | console.log(userName("")); // Not applicale
15 | console.log(userName("Humphrey Bogart")); // Humphrey Bogart
16 | ```
17 |
18 | This function checks to see if the value of `name` is _falsy_. If it is, it then assigns the value `Not applicable` before it returns. If it isn't, we return the passed value `name`.
19 |
20 | Here's a recap of truthy and falsy values:
21 |
22 | _Falsy_ values:
23 |
24 | - `false`
25 | - `undefined`
26 | - `null`
27 | - `NaN`
28 | - `0`
29 | - `""`
30 |
31 | _Truthy_ values:
32 |
33 | - `true`
34 | - `{}`
35 | - `[]`
36 | - `89`
37 | - `-5`
38 | - `"string"`
39 | - `new Date()`
40 |
41 | **Shortcut:**
42 |
43 | This much shorter code does the same as the example above:
44 |
45 | ```javascript
46 | function userName(name) {
47 | name = name || "Not applicable";
48 |
49 | return name;
50 | }
51 |
52 | console.log(userName("")); // Not applicable
53 | console.log(userName("James Stewart")); // James Stewart
54 | ```
55 |
56 | - The `||` operator first checks the left to see wether the value of `name` is _truthy_.
57 | - If `name` is _truthy_ then it returns the passed value `name`.
58 | - If `name` is _falsy_ it gets assigned the value to the right (`Not applicable`) and returns that _value_.
59 |
60 | -
61 | **Even Shorter Shortcut using default values/parameters**
62 |
63 | ```javascript
64 | function userName(name = "Not applicable") {
65 | return name;
66 | }
67 | //Attention!
68 | console.log(userName("")); // returns ""
69 | console.log(userName()); // returns "Not applicable"
70 | console.log(userName("James Stewart")); // James Stewart
71 | ```
72 | - Default function parameters allow formal parameters to be initialized with default values if no value (at all) or _undefined_ is passed.
73 |
74 | 
75 |
76 | In this `if` statement we check if `driversLicense` is _truthy_, if it is it calls the `registerDriver` function and passes `driversLicense` as a parameter. If `driversLicense` does not evaluate to _truthy_, it calls the `declineDriver` function and passes in the `driverLicense` parameter.
77 |
78 | ```javascript
79 | if (driversLicense) {
80 | registerDriver(driversLicense);
81 | }
82 | else {
83 | declineDriver(driversLicense);
84 | }
85 | ```
86 |
87 | **Shortcut:**
88 |
89 | ```javascript
90 | driversLicense && registerDriver(driversLicense) || declineDriver(driversLicense);
91 | ```
92 |
93 | - It first checks the left to see if `driversLicense` is _truthy_ and if it is it then calls `registerDriver` with `driversLicense` passed as a paramater.
94 | - If `driversLicense` is _falsy_ it moves to the right and calls the `declineDriver` function with `driversLicense` passed as a paramater.
95 |
--------------------------------------------------------------------------------
/JavaScript/synchronous-and-asynchronous.md:
--------------------------------------------------------------------------------
1 | # Synchronous and asynchronous in Javascript
2 |
3 | ##Introduction
4 |
5 | One source of bugs when writing my first Javascript was failing to understand when I was using an **asynchronous** (async for short) instead of a **synchronous** (sync) function, and what the difference implies. Here I provide a conceptual overview of the distinction and a few tips on usage. On the way, we'll grapple with some other jargon: "call stack", "callback", "event queue" and "event loop".
6 |
7 | ## Sync
8 |
9 | Confusingly, "synchronous" in Javascript means exactly the opposite of its non-technical meaning of "at the same time". In Javascript, synchronous means that each line of code will be executed only after the previous line has finished. For example, in the code below, `newVal` is printed only after the `sync` function has reached the end of its loop and returned the new value. That could take a bit of time, since it's a very long loop!
10 |
11 | ```javascript
12 | function sync(val){
13 | while (val < 999999999999999999)
14 | val++;
15 | }
16 | return val;
17 | }
18 | var input = 0;
19 | var newVal = sync(input);
20 | console.log(newVal);
21 | ```
22 |
23 | We can visualise synchronous code as a queue, where only the first person is served. The series of commands in our program form a queue, and only the command at the front of the queue is executed. Synchronous code is said to be "blocking" because the currently executing command blocks the execution of everything behind it in the queue.
24 |
25 | You may have heard the term "call stack". If we think of each function as its own little queue of commands, the call stack is the queue of such queues or "execution contexts". At the bottom or end of the call stack is always the main (or "global") execution context, and at the top or front is the function most recently called.
26 |
27 | ## Async
28 |
29 | If all your code were executed synchronously, web browsing would be a painful experience. Imagine you have a function that requests information from a server, waits for it to be received, and then does something with that information (like renders it on a webpage). If the entire function executed synchronously, the browser would freeze ("block") for the whole time the information was downloading.
30 |
31 | One solution to the problem of blocking would be to execute different pieces of code simultaneously on different "threads" of the processor. But the Javascript engine was designed to work only on a single thread, so it has a different solution. It makes use of asynchronous "callback" functions, together with events and something called an "event queue".
32 |
33 | Consider again the example of requesting data from a server. Instead of holding up the call stack until the information is received, we make the request and Javascript tells other processes (not the Javascript engine itself, but maybe other threads within the web-browser) to take care of carrying it out. Then it is free to carry on processing the call stack. When the download is complete, an event is triggered and sent back to Javascript, telling it that it can perform an action on the data (render it to the webpage). This action we will have specified in advance using a "callback" (which means simply a function passed to another function) as in the example below:
34 |
35 | ```javascript
36 | function request_data(callback_function){
37 | //request data
38 | //on response event, execute callback_function(data)
39 | }
40 | function callback_function(data){
41 | //render data
42 | }
43 | ```
44 |
45 | You might sometimes see the whole function `request_data` referred to as asynchronous. That's a bit misleading because in fact that function is executed synchronously within the call stack. It is the `callback_function` that is asynchronous. This will be executed only after the response event.
46 |
47 | ## Event queue and event loop
48 |
49 | Wait! What if Javascript is still processing commands on the call stack when the response event is received? What if we are inundated with several such responses? Well, Javascript has another queue for this, the "event queue". When a callback is triggered, it will not be executed straight away, but will be added to the event queue and executed only when:
50 |
51 | 1. All synchronous code in the call stack has finished
52 | 2. All code previously placed on the event queue has finished
53 |
54 | So the Javascript engine has two kinds of queue – the main sequence of synchronous code (the "call stack"), and a secondary "event queue". Whenever the main queue / call stack is empty, the function at the front of the secondary queue / event queue will be shunted onto the call stack and executed. The process which checks if the call stack is empty and does the shunting is called the "event loop".
55 |
56 | Note that the behaviour of the event queue itself is not "asynchronous". Even though functions on the event queue will wait until the call stack is empty, the queued async functions are transferred to the call stack one by one and executed synchronously when they arrive. If a function like the long while loop in `sync` were added to the event queue, it would still end up crashing the user interface whenever it came to be executed.
57 |
58 | ## Hazards and benefits
59 |
60 | It is important to be aware when callbacks will be executed asynchronously and when not. This is usually predetermined within the Javascript function invoking the callback, but is sometimes settable by a property (for example, jQuery's `ajax()` request function has a property `async` that can be set to true or false). Sometimes, you may want to wrap a function that normally calls a callback asynchronously in your own blocking function, to ensure that the program waits for the function to complete before moving on (for example, if you wish to not issue too many data requests at once). If requesting data with an asynchronous callback, you must make sure that you manipulate that data entirely within the callback, or you will end up attempting to perform actions on data that has not yet been received.
61 |
62 | Another area where it pays to be aware of asynchronous behaviour is Javascript's timer functions. Consider `setTimeout()`, which takes a callback and a delay as arguments, and executes the callback asynchronously after the delay. Because the callback passed to `setTimeout()` is taken out of the main program flow, the timer is not perfectly accurate. The callback will be added to the event queue after the delay has elapsed, but if the call stack or event queue are not empty, its execution will be further delayed until they are. This quirk does, however, have a useful side effect: we can call `setTimeout()` with 0 delay to ensure that the stack has cleared before we execute a function. Using this technique, we could regularly interrupt the massive loop in our earlier `sync` function and keep the user interface responsive while we execute it.
63 |
64 | Here's an interesting exercise, maybe: write a function which takes a callback and chops any loops above a certain length in the callback into chunks wrapped in `setTimeout()`. What other dangers, besides long loops, could we check for and address within the function?
65 |
66 | ##Related
67 |
68 | [HTTP requests](#tobeadded)
69 |
70 | [Timers](#tobeadded)
71 |
72 | ## References
73 | * [John Resig on Javascript timers.](http://ejohn.org/blog/how-javascript-timers-work/)
74 | * [Asynchronous and synchronous stackoverflow thread.](http://stackoverflow.com/questions/748175/asynchronous-vs-synchronous-execution-what-does-it-really-mean)
75 | * [Philip Roberts' great talk on the event loop.](http://2014.jsconf.eu/speakers/philip-roberts-what-the-heck-is-the-event-loop-anyway.html)
76 |
--------------------------------------------------------------------------------
/JavaScript/writable-enumerable-configurable.md:
--------------------------------------------------------------------------------
1 | #Javascript Object Property Attributes - Writable, Enumerable, Configurable
2 |
3 |
4 | Objects are collections of `name – value` pairs. For example:
5 |
6 | ```javascript
7 | var boy = {
8 | name: 'Bart',
9 | last: 'Simpson',
10 | enemy: 'Lisa'
11 | }
12 | ```
13 |
14 | However, there is more to the properties of an object than just a name and value. Properties also have the following attributes: `writable`, `enumerable` and `configurable`. To display, for instance, the attributes of the `name: 'Bart'` property, we can type the following code:
15 |
16 | ```javascript
17 | console.log(Object.getOwnPropertyDescriptor(boy, 'name'))
18 | ```
19 |
20 | This will be displayed:
21 |
22 | ```javascript
23 | {
24 | value: 'Bart',
25 | writable: true,
26 | enumerable: true,
27 | configurable: true
28 | }
29 | ```
30 |
31 | We can see that all three are set to `true` by default. Please remember that we are examining only the `name` here in our `boy` object.
32 |
33 | But what do they do? Let’s examine each one separately.
34 |
35 | ###Writable:
36 |
37 | The `writable` attribute determines whether we can change a property from its current value. Our initial value of `name` is `'Bart'`.
38 |
39 | So long as `writable` is set to `true`, we can change `name` as normal:
40 |
41 | ```javascript
42 | boy.name = 'Leonard';
43 | ```
44 |
45 | However, let’s set `writable` to `false`:
46 |
47 | ```javascript
48 | Object.defineProperty(boy, 'name', { writable: false });
49 | ```
50 |
51 | If we now examine our `name` with the same code as before:
52 |
53 | ```javascript
54 | console.log(Object.getOwnPropertyDescriptor(boy, 'name'))
55 | ```
56 |
57 | The following will be displayed:
58 |
59 | ```javascript
60 | {
61 | value: 'Bart',
62 | writable: false,
63 | enumerable: true,
64 | configurable: true
65 | }
66 | ```
67 |
68 | Once the `writable` attribute of the `name` property has been set to `false`, then trying to change the value of `name` will result in `name` still being set to `'Bart'`. An error is only thrown in strict mode, otherwise the assignment will fail silently. Strict mode error:
69 |
70 | ```javascript
71 | boy.name = 'Leonard'
72 | ^
73 |
74 | TypeError: Cannot assign to read only property 'name' of #