├── .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 | ![oop in js](http://www.newthinktank.com/wp-content/uploads/2015/09/Object-Oriented-JavaScript.png) 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 | ![map() method](/images/Array.map.png) 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 | ![Transpose 2D Array](/images/transpose2dArray.gif) 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 | ![Javascript output](/images/ClassesExample.png) 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 | ![Javascript output](/images/objprop1.png) 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 | ![Javascript output](/images/objpropproto.png) 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 | ![Javascript output](/images/protochain.png) 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 | ![Javascript output](/images/twoobjectschain.png) 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 | ![pic](http://eloquentjavascript.net/img/linked-list.svg) 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 | ![Remainder of division](/images/remainder.png) 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: ![factorial](https://upload.wikimedia.org/math/9/3/9/939c013423574cad70f33eaa7dd68f0c.png) 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 | ![Javascript Hoisting](http://captivatedev.com/wp-content/uploads/2011/04/VariableScope_thumb1.jpg) 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 | ![Javascript Hoisting](https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcS4RTdLDeAdSU3zqbT8LoCm2dYPCqIZzxmlKCSePWursKYl-sh-) 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 | ![Javascript Hoisting](http://www.codingtutes.com/wp-content/uploads/2016/03/1456827053_maxresdefault-205x130.jpg) 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 | ![Javascript shortcuts](http://wersm.com/wp-content/uploads/2013/01/shortcut-keyboard-howztech.jpg) 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 # 75 | ``` 76 | 77 | Of course, if the `name` property was changed before `writable` was set to `false`, then that second name will be the one that is ‘unchangeable’. 78 | 79 | **Warning** - We have to be very careful now because if the value of `name` is another object (not a primitive like a string), for example: 80 | 81 | ```javascript 82 | name: { first: 'Bart', nickname: 'Bandit' } 83 | ``` 84 | 85 | Setting `writable` to `false` wouldn’t prevent us from being able to change either `first` or `nickname`. 86 | 87 | In this case, a different approach is needed, we have to 'freeze' it: 88 | 89 | ```javascript 90 | Object.freeze(boy.name) 91 | ``` 92 | 93 | Now the whole `name` object is frozen and we are unable to change anything in it. 94 | 95 | 96 | ###Enumerable: 97 | 98 | We can display names in an object by using [`for...in`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...in) loop: 99 | 100 | ```javascript 101 | for (x in boy) { 102 | console.log(x); 103 | } 104 | //-----> name 105 | //-----> last 106 | //-----> enemy 107 | ``` 108 | 109 | However, let’s set `enumerable` to `false`: 110 | 111 | ```javascript 112 | Object.defineProperty(boy, 'name', { enumerable: false }); 113 | ``` 114 | 115 | If we now use the `for...in` loop again, we get the following result: 116 | 117 | ```javascript 118 | //-----> last 119 | //-----> enemy 120 | ``` 121 | 122 | Similarly, if we try to see object keys: 123 | 124 | ```javascript 125 | console.log(Object.keys(boy)) //-----> [ ‘last’, ‘enemy’ ] 126 | ``` 127 | 128 | We can see that `name` is missing. 129 | 130 | Similarly, JSON serialization is also affected: 131 | 132 | ```javascript 133 | console.log(JSON.stringify(boy)); //----->{"last":"Simpson","enemy":"Lisa"} 134 | ``` 135 | 136 | However, just because it is rendered ‘not-enumerable’ doesn’t mean it has disappeared into thin air, that is, it hasn't been deleted. 137 | 138 | We can still retrieve it, for example by running: 139 | 140 | ```javascript 141 | console.log(boy.name); //-----> ‘Bart’ 142 | ``` 143 | 144 | ###Configurable: 145 | 146 | ```javascript 147 | Object.defineProperty(boy, 'name', { configurable: false }); 148 | ``` 149 | 150 | First of all, once a property is made non-configurable, that is `configurable` is set to `false`, it cannot be changed back to `true`, that is, it can’t be made configurable again. 151 | 152 | But what does setting `configurable` to `false` do? 153 | 154 | Once set to `false` it prevents us from being able to change the `enumerable` attribute. If we, for instance were to try to change `enumerable` from `true` to `false`, we wouldn't be able to. 155 | 156 | It also prevents us from being able to `delete` a property: 157 | 158 | ```javascript 159 | delete boy.name //-----> error 160 | ``` 161 | 162 | Finally, setting `configurable` to `false` does not prevent us from being able to change the `writable` attribute. 163 | 164 | As we can see, the properties of an object can be a lot more fun than we may have thought at first glance! 165 | -------------------------------------------------------------------------------- /JavaScript/xhr.md: -------------------------------------------------------------------------------- 1 | # XMLHttpRequest 2 | 3 | ## Introduction 4 | 5 | Clicking a link on a webpage will cause your browser to load data from the website's server. But what if you want your webpage to load data without the user having to click anything? For example, you might want to update a data feed at a regular interval or speed up your webpage's performance by preemptively loading data before the user requests it. In order to make requests programmatically via JavaScript you use the _XMLHttpRequest_ (XHR) API. 6 | 7 | The XHR API can be used to transfer data between a webpage and its web server. The API is somewhat poorly named, as it can transfer more than just XML data (e.g. JSON or plain text) and does not necessarily need to use the HTTP protocol. XHR initially became popular around 2004/5, when it formed a key part of the Web 2.0 technology _Ajax_. This allowed for much more dynamic and responsive websites that changed without the user having to click links. 8 | 9 | ## Usage 10 | 11 | This README will not give a comprehensive account of the full API, but will give an introduction to its common uses. Full details can be found in the reference section. 12 | 13 | ### Create the XMLHttpRequest object 14 | 15 | ```javascript 16 | var xhr = new XMLHttpRequest(); 17 | ``` 18 | 19 | ### Open the request 20 | 21 | ```javascript 22 | xhr.open("GET", "/path/to/resource", [true, user, password]); 23 | ``` 24 | 25 | The `open` method specifies the request details. The first parameter is the request method (e.g. "GET" or "POST") and the second is the path to the requested resource. 26 | 27 | XMLHttpRequest follows the [same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy), which means that only requests to the same origin as the web application are allowed. 28 | 29 | The third specifies whether the request is asynchronous. This is `true` by default so the parameter is optional. It is unlikely that you would want to make a synchronous request anyway, as this would hold up the rest of the script waiting for the request to complete. 30 | 31 | A username and password can also optionally be provided if you are trying to access a resource that requires authentication. 32 | 33 | ### Handle the response 34 | 35 | If you are sending an asynchronous request, you must define a handler on the `onreadystatechange` method that will be called every time the `readyState` of the XMLHttpRequest (see below) changes. 36 | 37 | ```javascript 38 | xhr.onreadystatechange = function() { 39 | if (xhr.readyState == 4 && xhr.status == 200) { 40 | document.getElementById("content").innerHTML = xhr.responseText; 41 | } 42 | }; 43 | ``` 44 | The `readyState` property holds the current state of the request and will be one of the following: 45 | 46 | 0 - request not initialised 47 | 48 | 1 - server connection established 49 | 50 | 2 - request received 51 | 52 | 3 - processing request 53 | 54 | 4 - request received and response ready 55 | 56 | More information on `readyState` is available [here](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState). 57 | 58 | The `status` property holds the status of the HTTP response (e.g. `200 OK`, `404 Not Found`). If the `readyState` is 4 and the `status` is 200 you can be confident that the response is ready and correct. 59 | 60 | The `responseText` property stores the server's response as a string. This means that if the server has provided structured text such as JSON the client is responsible for parsing and handling the string appropriately. 61 | 62 | ### Send the request 63 | 64 | ```javascript 65 | xhr.send(); 66 | ``` 67 | 68 | If you are making a POST request you can also provide a string to the `send` method that will be sent to the server. You should use the `setRequestHeader` method to specify the content type in the request header: 69 | 70 | ```javascript 71 | xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 72 | xhr.send("name=CodingForEveryone&location=London"); 73 | ``` 74 | ## Fetching binary data 75 | 76 | You might be wondering how to request non-textual data such as images. The XHR API can be used to send binary data, but it requires a slightly hacky overriding of the MIME type: 77 | 78 | ```javascript 79 | xhr.open("GET", "/image.jpg"); 80 | xhr.overrideMimeType("text/plain; charset=x-user-defined"); 81 | ``` 82 | 83 | ## Event handlers 84 | 85 | You can use the `addEventListener` method to add a handler for any of the events specified [here](https://xhr.spec.whatwg.org/#event-handlers) e.g.: 86 | 87 | ```javascript 88 | xhr.addEventListener("error", function(event) { console.log("Error"); }); 89 | xhr.addEventListener("progress", function(event) { 90 | if(event.lengthComputable) { 91 | var percentComplete = event.loaded / event.total; 92 | } 93 | }); 94 | ``` 95 | 96 | Note that event handlers should be defined before calling `open` on the XHR object. 97 | 98 | ## Related 99 | 100 | XMLHttpRequest can be used as part of Ajax to create much more dynamic websites. [This guide](https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started) is a useful introduction. 101 | 102 | [This article](http://www.peej.co.uk/articles/rich-user-experience.html) covers using XHR with REST. 103 | 104 | You might prefer to use the slightly simpler interface provided by libraries such as jQuery. You can read more about jQuery's `.ajax` method [here](http://api.jquery.com/jquery.ajax/). 105 | 106 | ## References 107 | 108 | [A short introduction to XHR](http://www.tutorialspoint.com/ajax/what_is_xmlhttprequest.htm) 109 | 110 | [MIME types](https://en.wikipedia.org/wiki/Media_type) 111 | 112 | [How to use the API](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest) 113 | 114 | [MDN reference](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # READMEs 2 | 3 | [![Join the chat at https://gitter.im/codingforeveryone/READMEs](https://badges.gitter.im/codingforeveryone/READMEs.svg)](https://gitter.im/codingforeveryone/READMEs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) 4 | 5 | ##Introduction 6 | This is a place for creating, editing and using tutorials (READMEs). The idea is to help build a collection of tutorials as a way to consolidate your own learning and to help others. There are two ways to contribute: 7 | 8 | 1. Improve the existing tutorials. 9 | 2. Add a new tutorial. 10 | 11 | But first you need to understand a bit about GitHub! 12 | 13 | ##Using GitHub 14 | 15 | GitHub can be confusing at first. You need to understand at least the meaning of the terms *branch*, *master*, and *pull request* before you will be able to contribute. Check out the README on the [Contributor workflow](https://github.com/codingforeveryone/READMEs/blob/master/contribution-workflow.md) for more information. 16 | 17 | Note that the existing READMEs are available at two locations, the [repository](https://github.com/codingforeveryone/READMEs) from where you can edit them and add new ones, and the [GitBook](http://codingforeveryone.foundersandcoders.org/index.html) which represents the files in a more convenient form for browsing. Cross-references within READMEs should point to the files in the GitBook, not the repository. 18 | 19 | GitHub READMEs are written using a markup language called Markdown. You can familiarise yourself with Markdown using the [Markdown Cheat Sheet](http://codingforeveryone.foundersandcoders.org/programmer-skills/markdown-cheat-sheet.html). 20 | 21 | ##Improving the existing tutorials 22 | 23 | This is the most important way to contribute to the READMEs as it helps to assure the quality of the content. It is also easier for others to make more insightful contributions to high quality content than if the content was lower and more disorganised. You should familiarise yourself with the existing content and consider how to improve it before attempting to write a new README. 24 | 25 | ###Editing 26 | Do not be shy about suggesting changes to other people's work. The [Contributor workflow](https://github.com/codingforeveryone/READMEs/blob/master/contribution-workflow.md) ensures that authors have a chance to look over the changes you suggest and reject them if they do not feel they are appropriate. 27 | 28 | You will see in the [Contributor workflow](https://github.com/codingforeveryone/READMEs/blob/master/contribution-workflow.md) that different kinds of changes should be labelled differently when you submit them. Some basic kinds of change and the branch names you should use for them are below: 29 | 30 | 31 | |Type of correction|Branch name| 32 | |----------------|:-------------:| 33 | |Correcting grammatical mistakes or typos|*/correct*| 34 | |Reorganising or clarifying material|*/enhance*| 35 | |Adding new sections|*/add*| 36 | 37 | You can make up your own name if these do not seem appropriate! 38 | 39 | ##Adding a new tutorial 40 | 41 | ###General guidelines 42 | Make sure the topic is not already covered in other READMEs. Note that another README may cover your topic of interest despite having another title, as programming topics often overlap. You will need to become familiar with the content of the other READMEs before writing a new one. Keep the topic small, and aim to be simple and brief. Do not feel you need to write at length if an external resource has done it well: just summarise and link to it. In any case, your README should contain at least: 43 | 44 | ###Essential 45 | 1. An **Introduction** providing a single paragraph on the what, why and how of the topic. 46 | 2. A section called **Related**, listing related topics and linking to existing READMEs in the GitBook where appropriate. The 'Related' section **must** outline a related topic that is not covered in yours or other existing READMEs, or a suggesion on how the topic of your README could be extended. You should also raise your related topic as an issue and mention it on Gitter. This will help other users to get ideas on what to write about. 47 | 3. A final section called **References**, linking to other helpful resources on the topic. 48 | 49 | If you cannot fulfill all of the above requirements including the general guidelines, your README may not be merged into the master branch of this repository. If you are just looking to share a quick tip you learned, consider contributing it to the [Today I Learned](https://github.com/codingforeveryone/today-i-learned) repository. If you want to write about the subject anyway, to improve your own understanding, you may consider writing a blog post or an article on your own website if you have one, which you can link in the Gitter rooms. 50 | 51 | Make sure you give your file a sensible name: sensible filenames are all lower-case, do not have spaces or non-ASCII characters and end with the .md file extension. Some further notes: 52 | 53 | ###Optional 54 | 4. If you think the topic can be clarified with a Code Wars kata, then create one and link to it. 55 | 5. Consider adding a nice illustrative diagram or screenshot. 56 | 6. **Bonus**: If you are feeling adventurous, create a screencast to accompany your README. 57 | 58 | ###Submitting a pull request 59 | 60 | Before you submit a pull request for a new README, please make sure you have created it in the appropriate folder and added a link to it in SUMMARY.md. Submit the new file and revised SUMMARY.md as part of a single pull request. If you are unsure how to do this, consult the [Contributor workflow](https://github.com/codingforeveryone/READMEs/blob/master/contribution-workflow.md) README. 61 | 62 | ###Maintaining the GitBook 63 | 64 | Files are placed in the wrong location and need moving, links are inaccurate or go out of date...If you see something that looks wrong, change it! 65 | 66 | |Type of correction|Branch name| 67 | |----------------|:-------------:| 68 | |Maintenance|*/maintenance*| 69 | -------------------------------------------------------------------------------- /SUMMARY.md: -------------------------------------------------------------------------------- 1 | # Summary 2 | 3 | * [Introduction](README.md) 4 | 5 | * [JavaScript](/gitbook-chapter-headers/js.md) 6 | * [ECMAScript 6](/JavaScript/ECMAScript 6.md) 7 | * [String Dissection and Manipulation](/JavaScript/string-dissection-and-manipulation.md) 8 | * [String Replace](/JavaScript/replace-method.md) 9 | * [Arrays](/gitbook-chapter-headers/arrays.md) 10 | * [Array Methods Overview](/JavaScript/array-methods-overview.md) 11 | * [Array Map](/JavaScript/array-map.md) 12 | * [Array Reduce](/JavaScript/array-reduce.md) 13 | * [Numbers](/gitbook-chapter-headers/numbers.md) 14 | * [Arithmetic with large numbers](/JavaScript/large-numbers-in-js.md) 15 | * [Math Object Beginner Guide](/JavaScript/math-object-beginner-guide.md) 16 | * [Modulo Operator](/JavaScript/modulo-operator.md) 17 | * [Variable Scope and Hoisting](/JavaScript/scope-and-hoisting.md) 18 | * [Hoisting](/JavaScript/hoisting.md) 19 | * [Javascript Scope](/JavaScript/JavaScript-Scope.md) 20 | * [Closures](/JavaScript/Closures.md) 21 | * [Regular Expressions Beginner Guide](/JavaScript/regular-expressions-beginners-guide.md) 22 | * [Regular Expressions - Lookaheads](/JavaScript/regular-expressions-lookaheads.md) 23 | * [Recursion](/JavaScript/recursive-function.md) 24 | * [Objects](/JavaScript/Objects.md) 25 | * [Inheritance and Javascript](/JavaScript/inheritance-and-javascript.md) 26 | * [More on prototypes](/JavaScript/prototypes-more.md) 27 | * [Linked list](/JavaScript/linked-list.md) 28 | * [Basic Performance Testing](/JavaScript/basic-performance-testing.md) 29 | * [Exceptions handling](/JavaScript/raising-exceptions.md) 30 | * [Best JS Resources](/JavaScript/best-js-resources.md) 31 | * [JavaScript Shortcuts](/JavaScript/shortcuts.md) 32 | * [Synchrous and Asynchronous](/JavaScript/synchronous-and-asynchronous.md) 33 | * [Conditional Operator](/JavaScript/conditional-operator.md) 34 | * [Using the XMLHttpRequest API](/JavaScript/xhr.md) 35 | 36 | * [HTML and CSS](/gitbook-chapter-headers/html-css.md) 37 | * [Choosing a CSS Framework](/html-css/choosing-a-css-framework.md) 38 | * [CSS Centering](/html-css/css-centering.md) 39 | * [Document Object Model](/html-css/document-object-model.md) 40 | * [Manipulating Inline Styles](/html-css/manipulating-inline-styles.md) 41 | * [Laying Out Content with Flexbox](/html-css/laying-out-content-with-flexbox.md) 42 | * [Programmer Skills](/gitbook-chapter-headers/programmer-skills.md) 43 | * [Debugging Javascript](/programmer-skills/Debugging-Javascript.md) 44 | * [Git Basics](/programmer-skills/git-basics.md) 45 | * [Git Flow](/programmer-skills/git-flow.md) 46 | * [Hosting on GitHub](/programmer-skills/hosting-on-github-gh-pages.md) 47 | * [Markdown Cheat-Sheet](/programmer-skills/markdown-cheat-sheet.md) 48 | * [Mutable vs Immutable](/programmer-skills/mutable-vs-immutable.md) 49 | * [Start Developing with JavaScript](/programmer-skills/start-to-develop-js.md) 50 | * [Command Line](/programmer-skills/command-line.md) 51 | * [Setting Up a Local Server](/programmer-skills/setting-up-a-local-server.md) 52 | * [Setting Up Your Development Environment](/programmer-skills/setting-up-your-development-environment.md) 53 | * [Online Console Options](/programmer-skills/online-console-options.md) 54 | * [Getting Started with TypeScript](/programmer-skills/typescript_get_started.md) 55 | 56 | * [Codewars](/gitbook-chapter-headers/codewars.md) 57 | * [Codewars](/codewars/codewars.md) 58 | * [Writing Your Own Kata](/codewars/writing-your-own-kata.md) 59 | * [Random Test Cases for Complete Beginners](/codewars/random-test-cases-for-complete-beginners.md) 60 | 61 | * [Notes for Online Courses](/gitbook-chapter-headers/courses-notes.md) 62 | * [JavaScript: The Good Parts by Douglas Crockford](/notes-for-online-courses/javascript-the-good-parts-by-douglas-crockford.md) 63 | * [CS50: Introduction to Computer Science](/notes-for-online-courses/CS50-Videos.md) 64 | -------------------------------------------------------------------------------- /codewars/random-test-cases-for-complete-beginners.md: -------------------------------------------------------------------------------- 1 | # Random Test Cases for Complete Beginners 2 | 3 | If you are having to create your very first random test cases for your kata and have not any idea of what they are or how to produce 4 | them, this document might help you. 5 | 6 | ![Imgur](http://i.imgur.com/g4hUKdO.png?1) 7 | 8 | Random test cases are what it says on the tin – the user’s solution will be tested against a randomly generated input several times. 9 | Suppose we have made a kata asking the user to add a number `a` to a number `b`. His or her solution may be this: 10 | 11 | ```javascript 12 | function add(a, b){ 13 | return a+b; 14 | } 15 | ``` 16 | 17 | We now need to generate random test cases to test if the user’s solution returns the correct output. In this case, we need to generate 18 | a random number for argument `a` and another random number for argument `b`. 19 | 20 | Step by step: 21 | 22 | 1. First of all, just copy and paste your own solution into the ‘Test cases’ tab and slightly modify its name. For instance instead of 23 | `add`, name it `addCheck`. 24 | 25 | 2. Then, below your `addCheck` function, you will need a regular ‘for loop’. You will need this to regulate how many times the random 26 | tests will be performed. For example the following ‘for loop’ will perform them 200 times. 27 | 28 | ```javascript 29 | for(var i = 0; i < 200; i++){ 30 | //tests here 31 | } 32 | ``` 33 | 34 | Let’s now concentrate on the ‘//tests here’ part in the above ‘for loop’. 35 | 36 | 3. You will almost certainly need to know how to generate a random number before you attempt anything else. A random number in 37 | JavaScript can be generated thus: 38 | 39 | ```javascript 40 | var random = Math.random(); 41 | ``` 42 | 43 | The variable random will now be a random number between 0 and 1, for example: 0.03526814002543688. `Math.random()` can be equal to 0, but cannot be equal to 1. 44 | 45 | If you do `Math.random() * 100`, you will get 3. 526814002543688 instead of the number above. 46 | If you do `Math.round(Math.random() * 100)`, you will get `4` instead of the number above, as `3.5…`. will be rounded to `4`. 47 | 48 | So the code in our ‘for loop’ could look like this (pay attention to the last line): 49 | 50 | ```javascript 51 | for(var i = 0; i < 200; i++){ 52 | var random1 = Math.round(Math.random() * 10); //this might produce 7 53 | var random2 = Math.round(Math.random() * 10); // this might produce 5 54 | Test.assertEquals(add(random1, random2), addCheck(random1, random2)) 55 | } 56 | ``` 57 | 58 | Now, i = 0 and our loop runs for the first time. Variable `random1` is number **7** and variable `random2` is number **5**. Therefore, 7 and 5 59 | are placed as arguments to `add`, as well as arguments to `addCheck`. If both functions return the same result, in our 60 | case `12 (5 + 7 = 12)`, then we passed the first of the 200 tests. Our loop will run 199 times more, generating random numbers, 61 | passing them as argumenst to `add` and `addCheck` and comparing the two outputs. 62 | 63 | You might be thinking that if you only slightly changed the function’s name (from `add` to `addCheck`) and nothing else, 64 | then it is obvious that they will produce exactly the same results and therefore pass all the tests, since they are exactly the same 65 | except the name. Well, don’t forget that the `addCheck` function’s output will be compared not against your output, but against the 66 | user’s output. 67 | 68 | Obviously, 69 | you will not always need to generate random numbers. Sometimes you will need to generate strings, arrays and so on and so forth. 70 | 71 | I sometimes felt that generating these random test cases was a kata to solve in itself. 72 | 73 | I hope this short introduction gave you an idea of what random test cases are, and how and where to create them. Please note that I 74 | will update this document as time goes on. 75 | 76 | ## Further Random Number Examples 77 | 78 | Are you looking to generate a random integer greater than 0 and less than but not including `x`? Try `Math.floor(Math.random() * x)`. 79 | 80 | *For integers `0 <= x < 100`, use `Math.floor(Math.random() * 100)`.* 81 | 82 | Are you looking to generate a random integer greater than or equal to `x` but less than `y`? Try adding the lower bound `x` to a random object generating the remaining variable number (which is equal to `y - x`) e.g. `Math.floor(Math.random() * (y - x)) + x`. 83 | 84 | *For integers `40 <= x < 100`, use `Math.floor(Math.random() * 60) + 40`.* 85 | 86 | N.B. If you are wondering why we use floor here instead of round, it is because it assures that each result is equally likely to occur. Although this is often not important for kata random test cases, it is more standard to require a random variable which is uniformally distributed (i.e. an equal chance of getting any of the possibilities). 87 | 88 | ## Generating Random Strings 89 | 90 | The following function generates a random string 5 characters long. 91 | 92 | ```javascript 93 | function makestring() { 94 | var array = []; 95 | var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; 96 | for( var i=0; i < 5; i++ ) { 97 | array.push(possible[(Math.floor(Math.random() * possible.length))]); 98 | } 99 | return array.join(""); 100 | } 101 | ``` 102 | 103 | you can generate random strings within a range by adding a length variable and using that in place of the 5 in the for loop. The following code generates a random string of a length between 1 and 10 characters: 104 | 105 | ```javascript 106 | function makestring() { 107 | var array = []; 108 | var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; 109 | var length = Math.ceil(Math.random() * 10) 110 | 111 | for( var i=0; i < length; i++ ) { 112 | array.push(possible[(Math.floor(Math.random() * possible.length))]); 113 | } 114 | 115 | return array.join(""); 116 | } 117 | ``` 118 | 119 | You will probably want to set a minimum value as well and pass the maximum and minimum values in to the string generator as arguments: 120 | 121 | ```javascript 122 | function makestring(min, max) { 123 | var array = []; 124 | var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; 125 | var length = Math.ceil((Math.random() * max) + min) 126 | 127 | if (max < min) return "Maximum argument should be greater than minimum!"; 128 | 129 | for( var i=0; i < length; i++ ) { 130 | array.push(possible[(Math.floor(Math.random() * possible.length))]); 131 | } 132 | 133 | return array.join(""); 134 | } 135 | ``` 136 | 137 | You can of course, use the random number generators above to generate random integers to be passed in to the makestring function. 138 | 139 | ## Random Tests - Codewars - A Full Example 140 | 141 | In the following snippet, you can see how you can add a random test for your kata. Assuming the user solution to your kata is as follows: 142 | 143 | ```javascript 144 | function sumUser(a, b) { 145 | return a + b; 146 | } 147 | ``` 148 | 149 | Then you would add the following code block under "Test Cases": 150 | 151 | ```javascript 152 | // Your predefined solution: 153 | function sumKataAuthor(a, b) { 154 | return a + b; 155 | } 156 | 157 | // A function generating a random number in a range between min and max: 158 | function getRandomNumber(min, max) { 159 | return Math.floor(Math.random() * (max + 1 - min) + min); 160 | } 161 | 162 | // Run test 10 times (or as many times as you like!): 163 | for (var i = 0; i < 10; i++) { 164 | 165 | // Generate random input numbers between 0 and 100 for each test: 166 | var a = getRandomNumber(0, 100); 167 | var b = getRandomNumber(0, 100); 168 | 169 | // Adding console.log of the inputs used in the test may help 170 | // the user understand and debug their solution: 171 | console.log('input a was:', a,', input b was:', b); 172 | 173 | // Compare user's function with a working solution: 174 | Test.assertEquals(sumUser(a, b), sumKataAuthor(a, b)); 175 | } 176 | ``` 177 | -------------------------------------------------------------------------------- /gitbook-chapter-headers/arrays.md: -------------------------------------------------------------------------------- 1 | #Arrays 2 | 3 | This section contains articles specific to Javascript arrays. 4 | -------------------------------------------------------------------------------- /gitbook-chapter-headers/codewars.md: -------------------------------------------------------------------------------- 1 | # Codewars 2 | 3 | This section has articles specific to competitive coding with [Codewars](http://www.codewars.com). 4 | -------------------------------------------------------------------------------- /gitbook-chapter-headers/courses-notes.md: -------------------------------------------------------------------------------- 1 | #Notes for Online Courses 2 | 3 | This section contains classroom notes for coding-related online courses and tutorials. 4 | -------------------------------------------------------------------------------- /gitbook-chapter-headers/html-css.md: -------------------------------------------------------------------------------- 1 | #HTML and CSS 2 | 3 | This section pertains to HTML, CSS, and interacting with them via Javascript. 4 | -------------------------------------------------------------------------------- /gitbook-chapter-headers/js.md: -------------------------------------------------------------------------------- 1 | # JavaScript 2 | 3 | This section deals with built-in objects of the JavaScript (JS) language and their methods, as well as techniques and theory 4 | relevant to programming with JS. 5 | -------------------------------------------------------------------------------- /gitbook-chapter-headers/numbers.md: -------------------------------------------------------------------------------- 1 | #Number 2 | 3 | This section contains articles specific to Javascript numbers. 4 | -------------------------------------------------------------------------------- /gitbook-chapter-headers/programmer-skills.md: -------------------------------------------------------------------------------- 1 | # Programmer Skills 2 | 3 | This section contains READMEs concerning Git, Markdown, command-line usage, and topics relevant to code editors and development with JS. 4 | -------------------------------------------------------------------------------- /html-css/choosing-a-css-framework.md: -------------------------------------------------------------------------------- 1 | # Choosing a CSS Framework 2 | 3 | CSS frameworks are great! They let you get off to the best start when building a new website, giving you standardised code that'll make sure your site is responsive, cohesive, and functional, with minimum effort. Bootstrap's status as the most popular and well-known CSS framework out there means it often gets chosen for a project without much consideration. However, Bootstrap isn't always the most appropriate choice. It became the most used framework because it can do pretty much everything - while that's useful, you probably don't need everything! 4 | 5 | This guide will help you think about what functionality you actually need from a framework for your project, and help you choose one (or more) based on this criteria. So, let's get started: 6 | 7 | (NOTE: The recommendations given here are based on what I've personally used. There are countless frameworks out there, and you don't have to stick to the ones I've listed!) 8 | 9 | ## The Basics 10 | 11 | These frameworks are as minimal as possible - they'll do one job, and they'll do it well. 12 | 13 | ### The Grid 14 | Modern web design is based around the grid. [CreativeBloq have written a good beginners guide to grid theory](http://www.creativebloq.com/web-design/grid-theory-41411345), but you can think about it as the arrangement of columns that make up most of the websites you visit - ads, navigation, main content, etc. Pretty much every site is based around this system, and unless you like tedious calculations, you'll want a framework to set it up for you. It might be that this is all you need! For instance, if you already have a detailed design laid out for your site, just using a grid will let you implement the design without having to wrestle with pre-set CSS. 15 | 16 | Grid-only frameworks are best for experienced designers who want to implement their vision with minimal fuss, and are willing to do a lot of work themselves. 17 | 18 | #### What should I choose? 19 | [Toast](https://daneden.github.io/Toast/) is one of the most simple frameworks out there - it'll give you a responsive grid, and that's pretty much it. That makes it really easy to use, maximising browser compatibility and minimising the risk of conflicts with your design. However, the alternative CSS-based grid Flexbox has become a popular choice for web layout, making Toast seem outdated in comparison; [Flexbox Grid](http://flexboxgrid.com/) is a more modern alternative. 20 | 21 | ### Reset 22 | A reset framework eliminates inconsistencies between browsers so all your users will (hopefully) see exactly what you intended. It's a good idea to implement one into any project that you expect will reach a fair number of users, so you don't end up spending hours squashing browser specific bugs down the line. 23 | 24 | #### What should I choose? 25 | [Normalize.css](https://necolas.github.io/normalize.css/) is by far the most popular reset framework, and even comes included in more heavy-duty frameworks like Bootstrap or Boilerplate. While you may run into problems when designing on top of it, its extensive documentation means you shouldn't be stuck for long. 26 | 27 | ### Typography 28 | 29 | Great web typography doesn't just involve picking a nice font family and calling it a day; a typographic framework will do the fine-tuning for you. A typical typographic framework will create a fixed line height, standardise element padding and ensure your headings are responsive at least. More complex frameworks will choose fonts and styling for you, which is a great time-saver. 30 | 31 | #### What should I choose? 32 | If you want to choose your own fonts, [Typebase.css](https://devinhunt.github.io/typebase.css/) provides a framework that ensures readability without interfering with design. If, however, you want typography entirely styled for you, you'll want to choose a heavier framework that includes typesetting in its features. 33 | 34 | 35 | ## Lightweight 36 | 37 | These combine the functionality of multiple one-job frameworks into one package. They may use a grid, style typography and include some basic style elements like buttons or forms. However, they won't include a full UI framework or the extensive functionality of heavier frameworks. Lightweight frameworks are best for small-scale projects or developers who don't want to rely on stock design elements. Their main benefit is in their simplicity - by using a lightweight framework, you know you're not including potentially redundant or even conflicting code in your project. 38 | 39 | #### What should I choose? 40 | There are hundreds of lightweight frameworks out there, but my favourite is [Skeleton](http://getskeleton.com/). In less than 400 lines of code, it'll give you a grid, nicely styled typography, buttons, forms, lists and tables, as well as a convenient list of media queries. Combine it with Normalize if you like and, for a lot of projects, this will be more than enough to get started. 41 | 42 | ## Heavyweight 43 | 44 | Lightweight frameworks will set up a canvas for you to work on. Sometimes, though, you want it to resemble Lego - components that you can fit together to produce something quickly and easily. Heavier frameworks can be great for beginner developers, particularly those who aren't confident in their design skills, as they'll give you an entire suite of components and functionality you can fit together to realise a project without having to make everything from scratch. However, this also means including a lot of stuff you probably won't need, which can create problems both through creating unnecessary bloat in your project and potentially causing conflicts with code that you write. Many feature-rich frameworks try to combat this by being modular, allowing you to pick and choose the components to install. 45 | 46 | Before choosing a heavier framework, think carefully about what functionality your project does and doesn't need. They can also be quite complex, so make sure to read the documentation! 47 | 48 | #### What should I choose? 49 | [Bootstrap](https://getbootstrap.com/) and [Foundation](http://foundation.zurb.com/) are two of the biggest names when it comes to CSS frameworks. Foundation can be used for pretty much everything - it even has versions specifically designed for use in emails and apps. However, that wide functionality comes at a cost, and it can be hard to get to grips with, especially if you're used to working in plain CSS rather than in Sass (a CSS-based extension). To their credit, ZURB (Foundation's creators) have tried to combat this by offering tutorials, excellent documentation and even paid-for online classes. For most projects, though, you're better off looking elsewhere, particularly if you're just starting out. 50 | 51 | If you're in need of a framework with everything built in, then, Bootstrap is probably the way to go. By default, it comes with pretty much everything you could ever need. It's relatively easy to learn and its popularity means there's weeks worth of content written on using it. Do beware though - once you learn to recognise a website built in Bootstrap, you can never unsee it. 52 | 53 | * * * 54 | 55 | There's nothing worse than getting weeks into working on a project and realising that the framework you've built it on just isn't suitable. By following this guide and taking the time to think about what framework would be the best before you get started, you'll be able to work faster, spend less time squashing bugs, and produce better code with ease. 56 | -------------------------------------------------------------------------------- /html-css/laying-out-content-with-flexbox.md: -------------------------------------------------------------------------------- 1 | # Visual guide to laying out your content with the CSS flexbox 2 | 3 | Introduction: Flexbox provides a very easy and efficient way to lay out, align and distribute content on your page - often with much less effort and sweat than with older methods (e.g. using floats). Flexbox is also highly suited for coding pages that will be displayed on various screen sizes. 4 | In this article we will present the different ways that flexbox layout can be used to structure a page that displays well on different screen sizes and devices. 5 | 6 | A flexbox can be thought of as an elastic container that holds its elements inside and responds to screen size changes by shuffling its contents about in a predictable way. We use CSS to control how the layout of our page elements will change when the viewing screen size is changed. 7 | 8 | A flexbox layout is defined by adding the following CSS rule to the element containing the items that you wish to display flexibly. In the examples below, we have used an id tag, called "container", to identify the containing element, which holds three elements (or items) within it. 9 | 10 | ```css 11 | #container { 12 | display: flex; 13 | } 14 | ``` 15 | 16 | ## Arranging items horizontally or vertically with flex-direction 17 | The `flex-direction` property determines the direction of the **main axis** and **cross axis**, thus defining the direction in which the flex items are stacked. You can think of flex items wanting to arrange themselves either horizontally in a row, or vertically in a column. 18 | 19 | In the example below, our *flexbox container* is turquoise and contains several *flex elements* which are displayed in white. These white boxes are called *flex elements* because they are confined to the turquoise *flex container*; and they will rearrange themselves inside the flex container as the screen size is changed and the flex container expands or contracts in response to the change. 20 | 21 | The default behaviour is for flex elements to arrange themselves from left-to-right, or from top-to-bottom, depending on the specified direction of the main-axis. The main-axis is horizontal if you define it as such with `flex direction: row` or vertical if you define it as such with `flex direction: column`. 22 | 23 | ### Row layout 24 | ```css 25 | #container { 26 | flex-direction: row; 27 | } 28 | ``` 29 | 30 | 31 | ### Column layout 32 | ```css 33 | #container { 34 | flex-direction: column; 35 | } 36 | ``` 37 | 38 | 39 | ## Distributing content along the main axis with justify-content 40 | By default, flex elements stack themselves one right next to another, from start to end along the main axis. The `justify-content` property allows us to more meaningfully distribute the flex items along the **main-axis**. Bear in mind that the main axis runs horizontally or vertically depending on the flex-direction you specify, so `justify-content` will distribute items horizontally in row layout, and vertically in column layout. 41 | 42 | ### justify-content (in row layout) 43 | 44 | 45 | ### justify-content (in column layout) 46 | 47 | 48 | ## Aligning content along the cross axis with align-items 49 | 50 | ### align-items (in row layout) 51 | 52 | 53 | ## Distributing content along one or multiple lines with flex-wrap 54 | 55 | ###flex-wrap 56 | The `flex-wrap` property defines whether the flex items are forced in a single line or can be flowed into multiple lines. It also defines the cross-axis, which determines the direction the new lines are stacked in. 57 | 58 | The `flex-wrap` property accepts 3 different values: 59 | 60 | `flex-wrap:nowrap` – this is the default value where the flex items are forced in a single line and this may cause the container to overflow 61 | 62 | `flex-wrap:wrap` – items are flowed into multiple lines and the direction of the lines is determined by the flex-direction (which takes a value of either row or column) 63 | 64 | `flex-wrap:wrap–reverse` – items are flowed in multiple lines and the direction is opposite to the flex-direction(which takes a value of either row or column) 65 | 66 | ## Aligning multiple lines of content with align-content 67 | 68 | ### align-content (in row layout) 69 | 70 | -------------------------------------------------------------------------------- /images/Array.map.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/Array.map.png -------------------------------------------------------------------------------- /images/ClassesExample.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/ClassesExample.png -------------------------------------------------------------------------------- /images/Debugging-img-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/Debugging-img-1.png -------------------------------------------------------------------------------- /images/Debugging-img-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/Debugging-img-2.png -------------------------------------------------------------------------------- /images/Debugging-img-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/Debugging-img-3.png -------------------------------------------------------------------------------- /images/Debugging-img-4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/Debugging-img-4.png -------------------------------------------------------------------------------- /images/Debugging-img-5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/Debugging-img-5.png -------------------------------------------------------------------------------- /images/Debugging-img-6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/Debugging-img-6.png -------------------------------------------------------------------------------- /images/Debugging-img-7.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/Debugging-img-7.png -------------------------------------------------------------------------------- /images/Debugging-img-8.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/Debugging-img-8.png -------------------------------------------------------------------------------- /images/OnlineConsoleOptions__codepen_io.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/OnlineConsoleOptions__codepen_io.png -------------------------------------------------------------------------------- /images/OnlineConsoleOptions__jsbin_com.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/OnlineConsoleOptions__jsbin_com.png -------------------------------------------------------------------------------- /images/OnlineConsoleOptions__jsfiddle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/OnlineConsoleOptions__jsfiddle.png -------------------------------------------------------------------------------- /images/OnlineConsoleOptions__jshint_com.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/OnlineConsoleOptions__jshint_com.png -------------------------------------------------------------------------------- /images/OnlineConsoleOptions__repl_it.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/OnlineConsoleOptions__repl_it.png -------------------------------------------------------------------------------- /images/array.reduce1.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/array.reduce1.gif -------------------------------------------------------------------------------- /images/array.reduce2.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/array.reduce2.gif -------------------------------------------------------------------------------- /images/array.reduce3.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/array.reduce3.gif -------------------------------------------------------------------------------- /images/array.reduce4.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/array.reduce4.gif -------------------------------------------------------------------------------- /images/brackets_alert.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/brackets_alert.png -------------------------------------------------------------------------------- /images/brackets_code_errors.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/brackets_code_errors.png -------------------------------------------------------------------------------- /images/brackets_first_run.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/brackets_first_run.png -------------------------------------------------------------------------------- /images/brackets_live_preview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/brackets_live_preview.png -------------------------------------------------------------------------------- /images/brackets_live_preview_button.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/brackets_live_preview_button.png -------------------------------------------------------------------------------- /images/brackets_live_preview_changes.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/brackets_live_preview_changes.png -------------------------------------------------------------------------------- /images/brackets_warning_button.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/brackets_warning_button.png -------------------------------------------------------------------------------- /images/developer_tool_js_output.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/developer_tool_js_output.png -------------------------------------------------------------------------------- /images/developer_tool_js_output_hello.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/developer_tool_js_output_hello.png -------------------------------------------------------------------------------- /images/dom/document-child-child.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/dom/document-child-child.png -------------------------------------------------------------------------------- /images/dom/document-childnode.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/dom/document-childnode.png -------------------------------------------------------------------------------- /images/dom/document.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/dom/document.png -------------------------------------------------------------------------------- /images/dom/dom-tree-small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/dom/dom-tree-small.png -------------------------------------------------------------------------------- /images/dom/dom-tree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/dom/dom-tree.png -------------------------------------------------------------------------------- /images/dom/get-by-classname.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/dom/get-by-classname.png -------------------------------------------------------------------------------- /images/dom/get-by-id.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/dom/get-by-id.png -------------------------------------------------------------------------------- /images/dom/get-by-tag.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/dom/get-by-tag.png -------------------------------------------------------------------------------- /images/dom/get-option.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/dom/get-option.png -------------------------------------------------------------------------------- /images/dom/her-homepage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/dom/her-homepage.png -------------------------------------------------------------------------------- /images/dom/manipulate-after.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/dom/manipulate-after.png -------------------------------------------------------------------------------- /images/dom/manipulate-before.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/dom/manipulate-before.png -------------------------------------------------------------------------------- /images/dom/parent-node.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/dom/parent-node.png -------------------------------------------------------------------------------- /images/dom/visual-dom-tree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/dom/visual-dom-tree.png -------------------------------------------------------------------------------- /images/flexbox-flex-direction-column-justify-content.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/flexbox-flex-direction-column-justify-content.jpg -------------------------------------------------------------------------------- /images/flexbox-flex-direction-column.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/flexbox-flex-direction-column.jpg -------------------------------------------------------------------------------- /images/flexbox-flex-direction-row-align-content.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/flexbox-flex-direction-row-align-content.jpg -------------------------------------------------------------------------------- /images/flexbox-flex-direction-row-align-items.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/flexbox-flex-direction-row-align-items.jpg -------------------------------------------------------------------------------- /images/flexbox-flex-direction-row-justify-content.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/flexbox-flex-direction-row-justify-content.jpg -------------------------------------------------------------------------------- /images/flexbox-flex-direction-row.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/flexbox-flex-direction-row.jpg -------------------------------------------------------------------------------- /images/includes.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/includes.png -------------------------------------------------------------------------------- /images/jsbin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/jsbin.png -------------------------------------------------------------------------------- /images/jsbin_choose_lang.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/jsbin_choose_lang.png -------------------------------------------------------------------------------- /images/jsbin_code.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/jsbin_code.png -------------------------------------------------------------------------------- /images/jsbin_errors.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/jsbin_errors.png -------------------------------------------------------------------------------- /images/jsbin_fix.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/jsbin_fix.png -------------------------------------------------------------------------------- /images/jsbin_panels.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/jsbin_panels.png -------------------------------------------------------------------------------- /images/jsbin_run.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/jsbin_run.png -------------------------------------------------------------------------------- /images/jsbin_share.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/jsbin_share.png -------------------------------------------------------------------------------- /images/liquid.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/liquid.png -------------------------------------------------------------------------------- /images/objprop1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/objprop1.png -------------------------------------------------------------------------------- /images/objpropproto.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/objpropproto.png -------------------------------------------------------------------------------- /images/package-control.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/package-control.png -------------------------------------------------------------------------------- /images/protochain.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/protochain.png -------------------------------------------------------------------------------- /images/remainder.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/remainder.png -------------------------------------------------------------------------------- /images/s1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/s1.png -------------------------------------------------------------------------------- /images/s2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/s2.png -------------------------------------------------------------------------------- /images/s3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/s3.png -------------------------------------------------------------------------------- /images/s4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/s4.png -------------------------------------------------------------------------------- /images/s5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/s5.png -------------------------------------------------------------------------------- /images/s6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/s6.png -------------------------------------------------------------------------------- /images/setting-up-a-local-server.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/setting-up-a-local-server.png -------------------------------------------------------------------------------- /images/transpose2dArray.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/transpose2dArray.gif -------------------------------------------------------------------------------- /images/tsc_options.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/tsc_options.png -------------------------------------------------------------------------------- /images/tsc_sublime_view.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/tsc_sublime_view.png -------------------------------------------------------------------------------- /images/twoobjectschain.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/twoobjectschain.png -------------------------------------------------------------------------------- /images/typescript_venn_small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforeveryone/READMEs/a3226dcfef35f14e539c6305e58db46a1b7b8c9f/images/typescript_venn_small.png -------------------------------------------------------------------------------- /notes-for-online-courses/CS50-Videos.md: -------------------------------------------------------------------------------- 1 | # CS50 Video Notes 2 | 3 | ## [HTTP](https://youtu.be/KWxwYbaAWxs?t=55m8s) (55:08-1:04:40) 4 | 5 | #### HTTP 6 | - HTTP = Hypertext Transfer Protocol 7 | - This is the language / protocol that web browers and web servers speak (a "protocol" just refers to a set of conventions) 8 | - GET is a word stored inside the envelope – a request might look like: 9 | ``` 10 | GET / HTTP/1.1 11 | Host: www.google.com 12 | ... 13 | ``` 14 | - The first line tells us to get the default page, and that the language is HTTP version 1.1 15 | - The second is a specification to the recipient of the website being requested 16 | - The response might look something like: 17 | ``` 18 | HTTP/1.1 200 OK 19 | Content-Type: text/html 20 | ... 21 | ``` 22 | - The first line confirms that the website speaks that HTTP version also -> 200 is a status code which means "OK" 23 | - The second line specifies what content the user will be receiving 24 | 25 | #### Other Status Codes 26 | - 200 = OK 27 | - 301 = Moved Permanently (most browsers automatically redirect) 28 | - 302 = Found (page at a new location temporarily) 29 | - 401 = Unauthorized (typically requires login) 30 | - 403 = Forbidden (the resource is found, but you are not allowed access) 31 | - 404 = Not Found 32 | - 500 = Internal Server Error 33 | 34 | 35 | - 301 and 302 mean redirect -> whenever you're redirected from an address you type in, this is because the browser has received an envelope containing 301 or 302 and a URL 36 | - 500 generally means there's a bug in the code and the server can't handle it 37 | 38 | #### Query Strings 39 | - Web servers typically take input through the URL – any time you do anything interactive with a webpage (searching, logging in etc.) you're effectively submitting a form that sends info from you to the server -> the server then parses this URL by character 40 | - Question marks in URLs are followed by key value pairs (separated by ampersands) 41 | ``` 42 | GET /search?q=cats HTTP/1.1 43 | Host: www.google.com 44 | ... 45 | ``` 46 | 47 | #### POST 48 | - If the info being entered always ended up in the URL this would cause problems, particularly with sensitive info like passwords -> instead this is can be sent using POST, which is also used to submit non-text info like images 49 | ``` 50 | POST /login.php HTTP/1.1 51 | Host: www.facebook.com 52 | ... 53 | email=malan@harvard.edu&password=12345 54 | ``` 55 | - The first line sends you to a file called "login.php" which allows users to login 56 | - The additional input, rather than going immediately after the filename, is located lower in the request (deeper in the envelope) where no one can see it and it isn't remembered 57 | - Additionally, if the website is using HTTPS, this will all be encrypted so that no one can actually see the request at all 58 | 59 | 60 | ## [AJAX](https://www.youtube.com/watch?v=FtefVGIgAfA) (0:00-10:49) 61 | 62 | - AJAX = Asynchronous JavaScript and XML (XML is another markup language) 63 | - This allows us to update a page's content dynamically by **requesting more information from the server** without having to reload the page 64 | 65 | #### JavaScript Object: XMLHttpRequest 66 | - To do this we first need to create a special JS object called an XMLHttpRequest: 67 | ``` 68 | var xhttp = new XMLHttpRequest(); 69 | ``` 70 | - We then need to define this object's *onreadystatechange* behaviour - when a request is made to a webpage, it goes through a number of 'states': 71 | - Request not yet sent 72 | - Request sent, but not acted upon 73 | - Request acted upon 74 | - Request sent back to you 75 | - Request fully loaded in your page 76 | - This behaviour will typically be assigned to an anonymous function that is called when the asynchronous HTTP request has **completed** 77 | - We check for completion using the XMLHttpRequest's *readyState* property, which changes from 0 (request not yet initialised) to 1, 2, 3, and finally 4 (request finished, response ready), and also the *status* property 78 | - If the readyState property is 4, and the status property is 200 (OK) we will be able to asynchronously update the page with new data from the server, without having to reload its entire content 79 | 80 | #### Opening and Sending 81 | - This request then needs to be opened up and sent 82 | - Posting involves making an HTTP request programmatically (instead of through the web browser), which will retrieve data from the requested URL 83 | 84 | #### Complete Example 85 | ``` 86 | function ajax_request(name) 87 | { 88 | var aj = new XMLHttpRequest(); 89 | 90 | aj.onreadystatechange = function() { 91 | if (aj.readystate == 4 && aj.status == 200) { 92 | $('#infodiv').html(aj.responseText); 93 | } 94 | }; 95 | 96 | aj.open('GET', name + '.html', true); 97 | aj.send(); 98 | } 99 | ``` 100 | -------------------------------------------------------------------------------- /programmer-skills/big-O-notation.md: -------------------------------------------------------------------------------- 1 | #Big-O notation explained 2 | 3 | ###Introduction 4 | 5 | Imagine that you are building a website for the BBC. 6 | During an important event, such as the Olympic games, a Formula-1 race, or an important news event, millions of people try to visit the BBC site within a few minutes. You don't want your site to crash under high demand. 7 | You need to know how your site will respond to the enormous number of users, so it is of great importance to know how your algorithms scale, and how long they will take to handle those requests. 8 | There is one more problem, in real life you never know the exact number of people visiting your site (the number of inputs). Thus, you need a way to measure and compare the growth rate of an algorithm, known as ‘asymptotic notation’. 9 | What you need is the big-O notation. 10 | 11 | The Big-O notation is used to classify algorithms based on how their runtime grows relative to the input size, when the input gets arbitrarily large. 12 | 13 | #####Formal Big-O notation definition from [wikipedia](https://en.wikipedia.org/wiki/Big_O_notation) 14 | 15 | >Let f and g be two functions defined on some subset of the real numbers. One writes 16 | >f(x)=O(g(x)) as x→∞, 17 | >if and only if there is a positive constant M such that for all sufficiently large values of x, 18 | >the absolute value of f(x) is at most M multiplied by the absolute value of g(x). That is, f(x) = O(g(x)) 19 | >if and only if there exists a positive real number M and a real number x0 such that 20 | > |f(x)|≤M|g(x)| for all x≥ x0. 21 | 22 | 23 | Let's discuss the big-O notation through several examples. 24 | 25 | ###O(1) 26 | 27 | O(1) represents an algorithm that has the same runtime regardless of the size of the input data set. 28 | 29 | An easy example is when we check whether the first element of the array is null. The algorithm always checks 30 | the first element in the array, regardless of the array's size. 31 | 32 | ```javascript 33 | function isFirstItemNull(array) 34 | { 35 | return array[0] === null; 36 | } 37 | ``` 38 | 39 | 40 | ###O(log N) 41 | O(log N) algorithms are highly efficient for handling huge data sets. It has little effect on the runtime whether the data set has a 1000 or 10,000 entries. 42 | 43 | A well known example of O(log N) algorithms is binary search, it is used to find items 44 | in already sorted data sets. Binary search is a good algorithm for finding 45 | names in the phone book, or for the egg dropping problem. (There is a building of 100 floors. If an egg is dropped from the Nth floor or above it will break. 46 | If it’s dropped from any floor below, it won't break. Find N!). 47 | 48 | Binary search looks for a target value by comparing the middle item of an array. 49 | 50 | Binary search algorithm: 51 | 1. find the middle element, 52 | 2. if the middle item equals the target value, then stop, 53 | 3. Otherwise: 54 | * if the target value is smaller than the middle element. Repeat from step 1 for the left-subarray, before the middle element, 55 | * if the target value is bigger than the middle element. Repeat from step 1 for the right-subarray, after the middle element. 56 | 57 | 58 | Using binary search we halve the data set in every iteration circle. Thus if one doubles the size of the data set, it has very little effect on the runtime. 59 | Considering worst case scenarios, to find an element 60 | in a twice as big data set as the orignal requires just one more iteration cycle. 61 | 62 | ```javascript 63 | function binarySearch(array, target) 64 | { 65 | var start = 0; 66 | var stop = array.length -1; 67 | var middleIndex; 68 | while (start <= stop) 69 | { 70 | middleIndex = Math.floor( (start+stop)/2 ); 71 | if (array[middleIndex] == target){ 72 | return middleIndex; 73 | } else if (array[middleIndex] > target ) 74 | { 75 | stop = middleIndex-1; 76 | } else 77 | { 78 | start = middleIndex+1; 79 | } 80 | } 81 | return -1; 82 | } 83 | ``` 84 | 85 | ###O(N) 86 | 87 | O(N) describes an algorithm whose runtime will grow linearly and in direct proportion to the size of the input data set. For example if the algorithm includes a single iteration 88 | over the data set, the perfromance is O(N). 89 | 90 | Our test algorithm checks whether an item is in the array or not. 91 | ```javascript 92 | function containsItem(array, item){ 93 | for (var element of array) 94 | { 95 | if (item === array[element]) return true; 96 | } 97 | return false; 98 | } 99 | ``` 100 | 101 | ###O(N2) 102 | The performance is O(N2) when the runtime is directly proportional to the square of the size of the input data set. 103 | Almost every algorithm which includes a nested iteration over the data set has O(N2) performance. 104 | E.g.: bubble sort (worst case), Shell sort, quicksort (worst case), selection sort or insertion sort. 105 | 106 | The everyCombination function lists every possible ordered pair made from the elements of an array. 107 | It iterates through the array and for every element (item) it lists all of the ordered pairs starting with that item, using an inner loop. 108 | 109 | Sample output: If our array is [1,2], then the returned array containing all the possible combinations is [[1,1],[1,2],[2,1],[2,2]]. 110 | 111 | ```javascript 112 | function everyCombination(array) 113 | { 114 | var result = []; 115 | for (var item of array) 116 | { 117 | for (var inner of array) 118 | { 119 | result.push( [array[item], array[inner]] ) 120 | } 121 | } 122 | return result; 123 | } 124 | ``` 125 | Another example of an O(N2) algorithms is when we check whether all items are unique in an array. The number of comparisons is 126 | (N-1) + (N-2) + (N-3)...+ 2+1 = N(N-1)/2. 127 | 128 | ```javascript 129 | function isUnique(array) 130 | { 131 | for (var i = 0; i < array.length-1; i++) 132 | { 133 | for (var j = i+1; j< array.length; j++) 134 | { 135 | if (array[i]==array[j] ) return false; 136 | } 137 | } 138 | return true; 139 | } 140 | ``` 141 | 142 | ###Summary comparison of different runtimes: 143 | 144 | [//]: # (![bigO](![big-O notation](/images/big-o-notation.png)) 145 | ![bigO](http://i.stack.imgur.com/ia6VB.png) 146 | 147 | *Fig. 1. taken from [Stackoverflow](http://stackoverflow.com/questions/4317414/polynomial-time-and-exponential-time) 148 | O(1) is not visible because it is hidden behind O(logn)* 149 | 150 | ###References 151 | 1. [Big-O notation explained](https://justin.abrah.ms/computer-science/big-o-notation-explained.html) 152 | 2. [Big-O notation time and space complexity](https://www.interviewcake.com/article/java/big-o-notation-time-and-space-complexity) 153 | 3. [A beginner's guide to big-O notation](https://rob-bell.net/2009/06/a-beginners-guide-to-big-o-notation/) 154 | 4. [Wikipedia Big-O notation](https://en.wikipedia.org/wiki/Big_O_notation) 155 | 5. [Big-O notations for common data structures and algorithms](http://bigocheatsheet.com/) 156 | -------------------------------------------------------------------------------- /programmer-skills/command-line.md: -------------------------------------------------------------------------------- 1 | ## Command Line 2 | 3 | This is a simple guide to learning Command Line with learn code the hard way. Don’t worry; it’s actually a quite simple and quick guide to get you started on the very important command line used with coding. 4 | 5 | [Here](http://cli.learncodethehardway.org/book/) is the short but very useful guide to try. 6 | 7 | I found it useful to complete the ‘Do More’ section on each page as well as trying out a few things of my own to really get this in your head. I have also currently bookmarked this page to use as a great reference for if I forget anything. I am however, going to search around for a more detailed site to look at and use for future reference for anything else that may be useful. 8 | 9 | You may also find that a couple of times you’re not 100% certain on what is being completed on the task, for instance the ‘Moving a File’ tutorial didn’t fully explain how you could create a file in one folder and completely move it to another folder. I did a bit of extra research on this and found this site: [Macworld](http://www.macworld.com/article/2080814/master-the-command-line-copying-and-moving-files.html) features a handy description further down the page on what parameters need to be passed in. 10 | 11 | ![Macworld](http://i.imgur.com/dBXzqQl.png) 12 | 13 | By source and destination as you can see, it literally means the description you would get it you right clicked on the file and looked under it’s description. 14 | 15 | There is a lot of reading that can be done, if you choose so, with the ‘Getting Command Help’ section as you’ll see, but this is really useful in teaching you beyond the few tasks you’ve already been taught. I’ll be honest, I’ve not really put anything else into practice so far, but I’ve at least had a play around with a few on the command line, so I’d advice giving a few a go yourself just to test out what you’ve already learnt and expand upon those a little. 16 | 17 | Other than this, the quick tutorial is a really useful introduction into the command line and the many things you can do with it and use it for. I’d advise everyone to check it out. There are also cheat sheets available on the ‘Next Steps’ section, use the one that’s right for your system. 18 | 19 | ## Command line in Windows 20 | 21 | Cygwin is an old but usefull tool that allows you to have an Unix enviroment inside a Windows machine. Most of the commands and tools of a typical Linux distribution are available there. It´s a great way to practice and learn. 22 | 23 | [Cygwin](https://www.cygwin.com/). You can download the simple installer there. 24 | 25 | ## Links 26 | 27 | http://cli.learncodethehardway.org/book/ 28 | 29 | http://www.macworld.com/article/2080814/master-the-command-line-copying-and-moving-files.html 30 | 31 | https://www.codecademy.com/learn/learn-the-command-line 32 | 33 | http://linuxcommand.org/learning_the_shell.php 34 | 35 | 36 | -------------------------------------------------------------------------------- /programmer-skills/git-GUI-linux.md: -------------------------------------------------------------------------------- 1 | # Git GUI for Linux 2 | 3 | ### Choosing a GUI 4 | The Github Desktop GUI is not available on Linux so you will need to pick another GUI to install. There are a variety of GUI's you can install which can be found [here](https://git-scm.com/download/gui/linux). 5 | 6 | ### GitKraken 7 | I would recommend the GitKraken GUI which can be downloaded from the [offical page](https://www.gitkraken.com/). It can be run on Windows, Mac and Linux desktop systems. 8 | -------------------------------------------------------------------------------- /programmer-skills/git-basics.md: -------------------------------------------------------------------------------- 1 | # Git Basics 2 | 3 | ## Git and GitHub Summary 4 | ### Version Control and Branches 5 | Git is a tool used for version control: it allows you to store past versions of a project. To store the current state of your work in the project history, you must _commit_ your work. A commit is like a digital snapshot in time of your folders and files. 6 | When working, you may want to add a new feature to your project. _Branches_ are used to safeguard your current code from being broken by that new feature you're adding. Each branch is the sum of the commits that forms it. Branches are timelines of commits that diverge from your _master branch_ (generally speaking, the "main" branch) at a specified point in time. 7 | If your new feature works, then your test branch can be fused into your _master branch_ via a _merge_ command. At that point, the commits from the test branch become an inseparable part of the master branch's history. It is then safe to delete your test branch and continue working on your master branch. 8 | 9 | ### Group Work with GitHub 10 | You can use git commands to _push_ your local work up to GitHub (i.e. "the cloud"), where it can be _cloned_ down to other coders' computers, or _forked_ over to their own GitHub accounts online. Git and GitHub are invaluable tools for working with others on group projects. Individual coders work on their own branches and then submit _pull requests_ to merge their branches into the group project's master branch. Pull requests are used to solicit peer review on proposed branch merges before they are permanently committed into the master branch. 11 | 12 | ## Installing git on Linux 13 | To install git on linux, type the following into terminal. 14 | 15 | Up to Fedora 21: 16 | 17 | $ yum install git 18 | 19 | Fedora 22 and later: 20 | 21 | $ dnf install git 22 | 23 | Debian or Ubuntu: 24 | 25 | $ apt-get install git 26 | 27 | If you get an error, try adding sudo in front as this will give you access to install git. 28 | 29 | To verify which version of git you have installed, type the following into terminal: 30 | 31 | $ git -- version 32 | 33 | 34 | ### Installing git on Mac 35 | If you are on a mac, git may already be installed. To verify type this in the [terminal](https://en.wikipedia.org/wiki/Terminal_(OS_X)): 36 | ```bash 37 | $ git --version 38 | ``` 39 | 40 | If a version is displayed, you have it. If not, proceed to download git from [the official page](http://git-scm.com/downloads). 41 | This will download a DMG file. Double click on it and follow the steps. At the end open a terminal and verify with git --version if it is there. 42 | 43 | Now you need to set the username and user.email associated with git. This is relevant because services like github, or bitbucket will check your user.email, when you push something. If user.email is different from that set on github, you might encounter some problems. 44 | 45 | Username: 46 | ```bash 47 | $ git config --global user.name "your username" 48 | ``` 49 | 50 | User.email: 51 | ```bash 52 | $ git config --global user.email "yourEmailUsedOnGithub@gmail.com" 53 | ``` 54 | 55 | Last step is to set up a ssh key. This is useful because otherwise you will be asked to enter your username and password often in the terminal when you use most git commands. 56 | 57 | The steps are best described [here](https://help.github.com/articles/generating-an-ssh-key/). 58 | 59 | 60 | 61 | ## CHEAT SHEET 62 | 63 | ### Creating or cloning a repository 64 | 65 | Create a new local repository 66 | ```bash 67 | $ git init 68 | ``` 69 | 70 | Clone an existing repository 71 | ```bash 72 | $ git clone http://URL/REPOSITORY.git 73 | ``` 74 | 75 | ### Local changes 76 | 77 | Show changed files 78 | ```bash 79 | $ git status 80 | ``` 81 | 82 | Show changes in tracked files (that haven't been staged yet) 83 | ```bash 84 | $ git diff 85 | ``` 86 | 87 | Add files to your staging area 88 | ```bash 89 | $ git add 90 | ``` 91 | 92 | Add all files from your current directory 93 | ```bash 94 | $ git add . 95 | ``` 96 | 97 | Commit all local changes to the files in your staging area (i.e. files that have already been added) 98 | ```bash 99 | $ git commit -m <"descriptive message"> 100 | ``` 101 | 102 | Add all tracked files to the staging area _and_ commit all local changes to these files 103 | ```bash 104 | $ git commit -a -m <"descriptive message"> 105 | ``` 106 | 107 | Amend changes to your last commit 108 | ```bash 109 | $ git commit --amend 110 | ``` 111 | 112 | ### Commit history 113 | 114 | Show all commits, ordered from newest to oldest 115 | ```bash 116 | $ git log 117 | ``` 118 | 119 | Show all of your commits in a tree-like view 120 | ```bash 121 | $ git log --graph --oneline --all 122 | ``` 123 | 124 | ### Branches 125 | 126 | Create a new branch 127 | ```bash 128 | $ git branch 129 | ``` 130 | 131 | Switch branch 132 | ```bash 133 | $ git checkout 134 | ``` 135 | 136 | Create a new branch and switch to it 137 | ```bash 138 | $ git checkout -b 139 | ``` 140 | 141 | Delete a local branch 142 | ```bash 143 | $ git branch -d 144 | ``` 145 | 146 | ### Update and publish 147 | 148 | List the URLs of all remote repositories 149 | (e.g. the remote repo that you cloned from is called `origin` by default) 150 | ```bash 151 | $ git remote -v 152 | ``` 153 | 154 | Add new remote repository 155 | ```bash 156 | $ git remote add 157 | ``` 158 | 159 | Push committed changes on your local branch up to a remote server 160 | ```bash 161 | $ git push 162 | ``` 163 | 164 | Pull all files from a branch of the remote repository, and merge this into the current local branch 165 | ```bash 166 | $ git pull 167 | ``` 168 | 169 | ### Merge and rebase 170 | 171 | Merge a branch into your current HEAD (commit history will read: commits from checked out branch first, then merged branch commits) 172 | ```bash 173 | $ git merge 174 | ``` 175 | 176 | Rebase a branch into your current HEAD (commit history will read chronologically, regardless of which branch they were from) 177 | ```bash 178 | $ git rebase 179 | ``` 180 | 181 | ### Undo 182 | 183 | Unstages files i.e. resets back to previous commit 184 | ```bash 185 | $ git reset HEAD 186 | ``` 187 | 188 | Discard local changes in a specific file 189 | ```bash 190 | $ git checkout 191 | ``` 192 | 193 | ## Good Resources 194 | 195 | - Ebooks: 196 | - [Git Pro](https://git-scm.com/book/en/v2) 197 | - Online Courses: 198 | - [Try Git](https://www.codeschool.com/courses/try-git) 199 | - [Learn Git Branching](http://pcottle.github.io/learnGitBranching/) 200 | - [Git - The simple guide](http://rogerdudler.github.io/git-guide/) 201 | - [Git workflow to collaborate on open source projects](http://blog.scottlowe.org/2015/01/27/using-fork-branch-git-workflow/) 202 | -------------------------------------------------------------------------------- /programmer-skills/git-flow.md: -------------------------------------------------------------------------------- 1 | Git Flow 2 | =================== 3 | 4 | 5 | Git Flow is both the name of a branching model for git(the git flow) and a software that uses that model. It will most likely make your life easier ! 6 | Before reading this READMEs, you should be familiar with git, as it is basically git, but with a new way of working with it. 7 | If you're not familiar with git, please read [Git Basics](http://codingforeveryone.foundersandcoders.org/programmer-skills/git-basics.html) 8 | ---------- 9 | The Git Flow 10 | ------------- 11 | 12 | The Git Flow is a whole new workflow for git, based on branches, which can make your repos more organized, and making you work with git more efficiently. For example: 13 | 14 | - If you work on a feature with classic git workflow, you 15 | wouldn't want to work directly on your master branch or risk breaking 16 | everything in your production code. This workflow allows you to work 17 | on another branches alongside your master branch(see below) 18 | 19 | - Another example would be if you wanted to send a pull request. If your 20 | pull request was accepted, it would then be merged with the original repo, 21 | but only the most recent commit for each file will be here. What if 22 | you wanted history of every commit, for each feature you've worked on ? 23 | This workflow allows you to have a different branch for every 24 | different feature. When you're finished working on that feature, just 25 | merge it with "develop" and then delete that feature branch ! 26 | 27 | Here is a breakdown of branches in git flow: 28 | 29 | 30 | **Branches:** 31 | 32 | - **master**: Your production branch 33 | - **develop**: As the name suggests, your development branch) 34 | - **features**: A branch with every WIP features 35 | - **release**: A branch for making a few minor changes before production release 36 | 37 | 38 | git-flow software 39 | ------------- 40 | 41 | While this branching model can make your repos more organized, it would be hard to do manually. 42 | *That's what git-flow is for !* 43 | It allows you to enjoy the power of this workflow, without having to do everything manually. 44 | For example, to create a new feature branch, just do: 45 | `git flow feature start nameofyourfeature` 46 | If you're done and now want to merge that feature with develop, just "finish" it: 47 | `git flow feature finish nameofyourfeature` 48 | 49 | 50 | 51 | ### Installing git-flow 52 | On a mac, with homebrew: 53 | ```bash 54 | $ brew install git-flow 55 | ``` 56 | 57 | On linux: 58 | ```bash 59 | $ curl -OL https://raw.github.com/nvie/gitflow/develop/contrib/gitflow-installer.sh 60 | $ chmod +x gitflow-installer.sh 61 | $ sudo ./gitflow-installer.sh 62 | ``` 63 | 64 | On Windows, with cygwin: 65 | 66 | ```bash 67 | wget -q -O - --no-check-certificate https://github.com/nvie/gitflow/raw/develop/contrib/gitflow-installer.sh | bash 68 | ``` 69 | 70 | ### Getting started 71 | 72 | Same as with git commands, you use init to initialize a repo: 73 | 74 | ```git flow init``` 75 | It will ask you a few questions. Just keep the default values (recommended). 76 | 77 | If you want to start a new feature, use the feature start command: 78 | 79 | ```git flow feature start ``` 80 | Intuitive, isn't it ? and to end it, same logic: 81 | 82 | ```git flow feature finish ``` 83 | 84 | To start a release: 85 | 86 | ```git flow release start RELEASENAME ``` 87 | It will create a new release branch for that feature. 88 | 89 | And to finish it: 90 | 91 | ```git flow release finish RELEASENAME ``` 92 | It will merge the release branch with your development repo, and delete the branch, automatically ! 93 | 94 | 95 | Going Further 96 | ------------- 97 | 98 | As you can see, Git Flow is a powerful workflow, and the git-flow software does all the boring work for us, automatically. 99 | 100 | If you want to know more about git-flow features, you can read the [git-flow cheatsheet written by Daniel Kummer](http://danielkummer.github.io/git-flow-cheatsheet/). 101 | -------------------------------------------------------------------------------- /programmer-skills/hosting-on-github-gh-pages.md: -------------------------------------------------------------------------------- 1 | ## Hosting On GitHub 2 | 3 | This tutorial explains how to host static pages on github. At the end of this you will be able to host your pages on github for free and to assign **customs URLs to them**. 4 | 5 | The service is called Github Pages, and is very easy to use from your current github account. 6 | There are several good tutorials on github, so in this guide I will try to answer all the questions I still had after going through those. 7 | I encourage you to start from [here](https://pages.github.com/). This tutorial explains how to create a **user page**. A user page is not what you will probably be using most often, but it is the easiest to set up ( they are all easy) and a good starting point. The next paragraph is about the differences between **user pages** and **project pages** 8 | 9 | NOTE: to be able to use the project pages you need to be familiar with branches. [here](https://www.atlassian.com/git/tutorials/using-branches/git-branch) a good tutorial 10 | 11 | ### Two types of pages 12 | There are two types of pages you can create, **user pages** and **project pages**. 13 | The main difference is that you can have only one user page per github account, and it is usually used as a blog/site about you. It will be available at http://__yourUsername__.github.io. 14 | Instead, you can have as many **Project pages** as you want on the same github account and they are used for, well, your projects. 15 | 16 | ### Set up a user page 17 | Create a new repo using github interface and give it this name: __yourUsername__.github.io. So it will look something like this: 18 | `https://github.com/username/username.github.io` 19 | 20 | It can be public or private, and you can initialise it with a readme.md or not (do it). 21 | 22 | Now clone it on your machine in the folder you want: 23 | `$ git clone https://github.com/username/username.github.io.git` 24 | 25 | In your folder you need to have a file named index.html, copy paste it in the repo folder or create a simple one to test, like this: 26 | `$ echo “Hello, world” > index.html` 27 | 28 | Now add, commit and push to the master: 29 | `$ git add index.html` 30 | `$ git commit index.html -m “Hello world commit”` 31 | `$ git push origin master` 32 | 33 | Done! 34 | Your page will be available at http://__yourUsername__.github.io. 35 | 36 | 37 | ### Set up a project page 38 | Create a new repo and call it what you want. 39 | It can be public or private, and you can initialise it with a readme.md or not (do it). 40 | 41 | Now clone it on your machine in the folder you want: 42 | `$ git clone https://github.com/yourUsername/repoName` 43 | 44 | Create a new branch called gh-pages. This is a special name that github uses to build and publish: 45 | `$ git branch gh-pages` 46 | 47 | And switch to it: 48 | `$ git checkout` 49 | 50 | The shorthand for this would be: 51 | `$ git checkout -b gh-pages` 52 | The `-b` is an option to create a branch while switching to it. 53 | 54 | Now you can create a new file into this branch to test: 55 | `$ echo “Hello, world” > index.html` 56 | 57 | If you have your files you need to put them in the gh-pages branch. There are different ways of doing this and I will not cover working with branches in this tutorial. However this is one way to do it to try. 58 | For example, if you have a file index.html somewhere on your machine, but not yet in the repo folder. 59 | Copy paste it into the repo folder. Or use `cp path of file` 60 | 61 | Switch to gh-pages branch with: 62 | `$ git checkout gh-pages` 63 | 64 | Now add, commit and push to gh-pages: 65 | `$ git add index.html` 66 | `$ git commit -m “Index commit”` 67 | `$ git push origin gh-pages` 68 | 69 | Done! Your site will be accessible at http://__yourUsername__.github.io/repoName 70 | 71 | 72 | ### Using customs urls 73 | 74 | All of what has been covered until now is pretty cool, but it wouldn't be as useful as it is, if you couldn't then use a custom URL. Which means to change **yourUsername.github.io/repoName** to something like **www.myWebsite.com**. 75 | 76 | The practical steps to do it are covered by [this short tutorial](https://help.github.com/articles/setting-up-a-custom-domain-with-github-pages/) from gitHub. 77 | 78 | The main difficulty here for me was to understand how to set up DNS records. 79 | If you are using a subdomain, like **www.myWebsite.com**, or **myName.myFamilyName.com**, use a CNAME type of DNS record by your DNS provider. 80 | 81 | If you are using an apex domain, like **myWebsite.com**, you can set it up with an A or ANAME type of DNS record, by your DNS provider. 82 | Be aware that using apex domain is highly discourage on github as you will have some serious load time issues. 83 | 84 | 85 | 86 | ### Jekyll 87 | 88 | If you start to read documentations about gh-pages you will often come across references to Jekyll. So what is Jekyll? It is the engine that powers gh-pages, but for the purpose of this tutorial, it's a totally different way of using gh-pages than what has been shown in this tutorial. Instead of uploading valid html/css pages you will have to upload a valid Jekyll website, or, to make things easier, to use the online generator that is found on gitHub. (To be technically accurate, an html site is a valid Jekyll site, and on github even html pages are processed by Jekyll, which does not apply any changes to them. However just for clarity, I make the distinction between the two as a Jekyll site is practically different to make and as a different structure) 89 | 90 | While uploading a valid Jekyll website requires you to understand a little better how Jekyll works, the online generator is very easy to use. In essence, all you need is to write content in a markup language, like *Markdown* (see the irony?) or *Textile*, and Jekyll will translate it into valid html, and apply templates. The templates are based on the *Liquid* templating language, but if you use the online generator you don't need to know it either, as you can select those via a graphic interface. 91 | 92 | So, why use Jekyll over plain html/css? Because with it you can do things that would normally require a database and a content management system. 93 | In its own documentation Jekyll is defined as a blog-aware, static site generator. 94 | Blog-aware means that creating a blog is a feature embedded in Jekyll, which means that you can create a blog without the need for a database and without the need for a content management system. 95 | I'll stop here as Jekyll would require a tutorial for itself. If you are interested in the topic you can find a good resource [here](https://jekyllrb.com/docs/resources/) 96 | -------------------------------------------------------------------------------- /programmer-skills/markdown-cheat-sheet.md: -------------------------------------------------------------------------------- 1 | #Markdown CheatSheet 2 | 3 | [![Join the chat at https://gitter.im/codingforeveryone/READMEs](https://badges.gitter.im/codingforeveryone/READMEs.svg)](https://gitter.im/codingforeveryone/READMEs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) 4 | 5 | 6 | This is a simple tutorial to provide a refresher to Markdown and a reference to the most frequently used syntax. 7 | Here there is a short [interactive markdown tutorial](http://markdowntutorial.com/) to try. 8 | This is a link to [John Gruber site](https://daringfireball.net/projects/markdown/syntax), the creator of markdown, for a more exhaustive list of the syntax. 9 | Below you can find a small cheat sheet with some syntax present in the interactive tutorial, for quick reference. 10 | 11 | ##### Further text formatting 12 | If you want to achieve some effects that are not covered by basic Markdown syntax, you can **embed standard html tags** in Markdown and use inline css. 13 | 14 | For example if you want to have text wrapping around an image you could do the following, replace: 15 | 16 | ``` 17 | ![karate kata gif](https://45.media.tumblr.com/tumblr_m67my3RMlA1rvcjd7o1_400.gif) 18 | ``` 19 | 20 | with: 21 | 22 | ``` 23 | karate kata gif 24 | ``` 25 | 26 | 27 | Beware that what is shown above **will not work on GitHub** due to Github Markdown Limitation. 28 | GitHub accepts html tags in the Markdown, but for consistency/safety reasons it strips the 'style' parameter. 29 | See [here](http://stackoverflow.com/questions/20598628/do-style-tags-work-in-markdown) for a better explanation. 30 | 31 | 32 | ### CheatSheet 33 | 34 | * italics 35 | * \_myWord\_ --> _myWord_ 36 | * \_myWord1 myWord2\_ --> _myWord1 myWord2_ 37 | 38 | 39 | 40 | * bold 41 | * \*\*myWord\*\* --> **myWord** 42 | * \*\*myWord1 myWord2\*\* --> **myWord1 myWord2** 43 | 44 | 45 | 46 | * header 47 | The number of hashtags indicates what kind of header you are creating. 48 | * \#header1 49 | * \#\#header2 50 | * \#\#\#header3 51 | 52 | 53 | * links 54 | * \[name]\(url\) 55 | 56 | * images 57 | * \!\[name]\(url\) 58 | 59 | * block quotes 60 | * use \> on the first line of the text you want to quote 61 | 62 | * lists 63 | * unordered lists 64 | use \* followed by a space and your text 65 | * ordered lists 66 | use 1. followed by a space and your text 67 | 68 | * code 69 | * \` var foo = 'bar'; \` --> `var foo = 'bar';` 70 | * wrap your code between \`\`\`  to preserve its format. Optionally you can indicate its language. I.e: 71 | 72 | \`\`\`javascript 73 | 74 | var foo = 'bar'; 75 | 76 | function repeat(str, times){ 77 | 78 | return (''+Array(times + 1)).split(',').join(str); 79 | 80 | } 81 | 82 | repeat(foo, 5); 83 | 84 | \`\`\` 85 | 86 | turns into: 87 | 88 | ```javascript 89 | var foo = 'bar'; 90 | 91 | function repeat(str, times){ 92 | 93 | return (''+Array(times + 1)).split(',').join(str); 94 | 95 | } 96 | 97 | repeat(foo, 5); 98 | ``` 99 | 100 | ### Further readings 101 | 102 | - [Markdown basics by John Gruber](https://daringfireball.net/projects/markdown/basics) 103 | - [Gitbook - Markdown](https://www.gitbook.com/book/gitbookio/markdown/details) 104 | - [Ghost - The ultimate guide to markdown](https://blog.ghost.org/markdown/) 105 | 106 | ### Practicing markdown 107 | 108 | - [Dillinger.io](http://dillinger.io) 109 | - [Stackedit.io](https://stackedit.io) 110 | - [Codecademy](https://www.codecademy.com/courses/web-intermediate-en-Bw3bg/2/1) 111 | 112 | 113 | -------------------------------------------------------------------------------- /programmer-skills/mutable-vs-immutable.md: -------------------------------------------------------------------------------- 1 | #Mutable vs immutable types 2 | 3 | ![Teenage mutant ninja turtles](https://qph.is.quoracdn.net/main-qimg-56e5d36cc0289ab4af84a96db2d05b18?convert_to_webp=true) 4 | 5 | In javascript we have primitive types and reference types, which correspond to immutable and mutable types. 6 | 7 | ##Primitive Types 8 | 9 | - **Number**: `14`, `4.12` 10 | - **Boolean**: `_true`, `false` 11 | - **String**: `"Hello world"` 12 | - **null** 13 | - **undefined** 14 | 15 | ##Reference Types 16 | 17 | - **Object**: 18 | 19 | ```javascript 20 | { 21 | name: "Ben", 22 | age: 20 23 | } 24 | ``` 25 | 26 | - **Array**: `[23, 4, 55, 9]` 27 | - **Function**: `myFunction()` 28 | 29 | ##Mutability 30 | 31 | Reference types in Javascript are **mutable**. Consider this example: 32 | 33 | ```javascript 34 | var ben = { 35 | age: 20 36 | }; 37 | 38 | var another = ben; //ben is assigned to a new variable called another 39 | 40 | console.log(ben.age); //prints 20 41 | console.log(another.age); //prints 20 42 | 43 | another.age = 35; //another's age is set to 35 44 | 45 | console.log(ben.age); //prints 35 46 | console.log(another.age); //prints 35 47 | ``` 48 | 49 | Notice that when we modify `another`, `ben` is also modified (or mutated). 50 | 51 | Both variables are acting on the same object, so changing one will affect the other. 52 | 53 | When this code runs: 54 | 55 | ```javascript 56 | var another = ben; 57 | ``` 58 | 59 | ... the variable `another` is **NOT** assigned a copy of `ben`. It points to the same object as `ben`. 60 | 61 | An example with a function call: 62 | 63 | ```javascript 64 | function modifyAge(obj) { 65 | obj.age = 10; 66 | } 67 | 68 | var sally = { 69 | age: 23 70 | }; 71 | 72 | modifyAge(sally); 73 | 74 | console.log(sally.age); //prints 10 75 | ``` 76 | 77 | When we pass `sally` to `modifyAge()`, we are not passing a copy of `sally` which is why when we print `sally` after calling `modifyAge()`, we can see how the original object has been updated. 78 | 79 | ##Immutability 80 | 81 | The case is different for primitive types. Primitive types are **immutable**, they **CANNOT** be modified. 82 | 83 | ```javascript 84 | var a = 5; 85 | 86 | var b = a; 87 | 88 | console.log(a); //prints 5 89 | console.log(b); //prints 5 90 | 91 | a++; 92 | 93 | console.log(a); //prints 6 94 | console.log(b); //prints 5 95 | ``` 96 | 97 | As opposed to what happens with reference types, when we change the value of `a` it has no effect on the variable `b`. 98 | 99 | There is no change that can be applied to `a` that will affect `b` and vice versa. There is no connection between the two. 100 | 101 | An example with a function call: 102 | 103 | ```javascript 104 | function modifyValue(n) { 105 | n++; 106 | } 107 | 108 | var age = 53; 109 | 110 | modifyValue(age); 111 | 112 | console.log(age); //prints 53 113 | ``` 114 | 115 | In this example, an **immutable** type (a Number) is passed to the function `modifyValue()`. There, it is called `n`. But when `n` is modified, it has no effect on the original `age` variable. 116 | -------------------------------------------------------------------------------- /programmer-skills/online-console-options.md: -------------------------------------------------------------------------------- 1 | # Online console options 2 | 3 | ###Introduction: 4 | 5 | This README tutorial is an introduction to your online console and debugging options when starting out as a software developer. 6 | 7 | Code compilers and consoles are a great tool for creating small pieces of code and debugging purposes. 8 |
These tools are particularly useful when solving Codewars katas. 9 | 10 | There are many options to suit your coding requirements. Here are some popular suggestions with pros and cons for each. 11 | 12 | There are 3 key points to take into consideration when choosing a platform to use: 13 | 14 | 1. What coding languages do they support? 15 | 2. Do they simply help debug through syntax checking or can you run code and check the result in a console? 16 | 3. Do you have to set up an account to use them? 17 | 18 | ### Console and debugging tools: 19 | 20 | ####[repl.it](https://repl.it/) 21 | ![alt tag](http://codingforeveryone.foundersandcoders.org/images/OnlineConsoleOptions__repl_it.png)
22 | 23 | 1. Supported languages: Python, JavaScript, Ruby, Scheme, C#, Java, PHP, C++, C... (The list goes on!)
24 | 2. You can run code in the console and there is a built in syntax checker too.
25 | 3. You can use this tool without an account and can save multiple sets of code with an account.
26 | 27 | Pros: The best tool for creating functions and testing them in a console. Free service with great aims to democratize coding and make it accessible.
28 | Cons: You have to create an account to retrieve saved code. 29 |
30 |
31 | 32 | ####[jshint.com](http://jshint.com) 33 | ![alt tag](http://codingforeveryone.foundersandcoders.org/images/OnlineConsoleOptions__jshint_com.png)
34 | 35 | 1. Supported languages: JavaScript.
36 | 2. The tool is a simple syntax and error checker.
37 | 3. 100% functionality can be used without an account.
38 | 39 | Pros: Very intuitive to use. Best tool for simple debugging purposes.
40 | Cons: No console output makes the tool limited in its use. You can't save code.
41 |
42 |
43 | 44 | ####[jsbin.com](https://jsbin.com) 45 | ![alt tag](http://codingforeveryone.foundersandcoders.org/images/OnlineConsoleOptions__jsbin_com.png)
46 | 47 | 1. Supported languages: JavaScript, HTML, CSS, CoffeeScript.
48 | 2. You can run code in the console and there is a built in error checker too.
49 | 3. Most of the functionality that a beginner needs can be used without signing up to a 'Pro' account.
50 | 51 | Pros: Enables you to code JavaScript alongside HTML and CSS. Share code with Gist.
52 | Cons: A great tool for beginners with few flaws.
53 |
54 |
55 | 56 | ####[jsfiddle.net](https://jsfiddle.net/) 57 | ![alt tag](http://codingforeveryone.foundersandcoders.org/images/OnlineConsoleOptions__jsfiddle.png)
58 | 59 | 1. Supported languages: JavaScript, HTML, CSS, CoffeeScript.
60 | 2. You can run code in the console and there is a built in error checker too.
61 | 3. Most of the functionality that a beginner needs can be used without signing up to a 'Pro' account.
62 | 63 | Pros: Built in tool to collaboratively code with others. Useful to code JavaScript alongside HTML and CSS.
64 | Cons: Tricky to get the hang of when starting out.
65 | 66 | [Instructions for using JSFiddle.](http://doc.jsfiddle.net/tutorial.html) 67 |
68 |
69 | 70 | ####[codepen.io](http://codepen.io/nullobject/pen/rAbio) 71 | ![alt tag](http://codingforeveryone.foundersandcoders.org/images/OnlineConsoleOptions__codepen_io.png)
72 | 73 | 1. Supported languages: JavaScript, HTML, CSS, CoffeeScript.
74 | 2. You can run code in the console and there is a built in error checker too.
75 | 3. Basic functionality can be used without an account but the tool is a small part of a bigger pay for service that most beginners won't want or need.
76 | 77 | Pros: Useful to code JavaScript alongside HTML and CSS.
78 | Cons: Could be more intuitive to use. 79 |
80 | 81 | [Instructions for using the console tool on CodePen.](https://blog.codepen.io/documentation/editor/console/) 82 |
83 |
84 | 85 | ### Related 86 | 87 | This README focuses on online debugging and console tools, an extension of this README would be to explore a beginner's options in regards to applications that run direct from your OS such as Oracle and Android Studio. 88 | 89 | Here are some related Coding for Everyone READMEs:
90 | [Debugging.](https://github.com/codingforeveryone/READMEs/blob/master/programmer-skills/Debugging-Javascript.md)
91 | [Start to develop with JavaScript.](https://github.com/codingforeveryone/READMEs/blob/master/programmer-skills/start-to-develop-js.md)
92 | 93 | ### References and further reading 94 | 95 | [Tools for coding online.](http://www.hongkiat.com/blog/tools-to-coding-online/)
96 | [Online browser based debugging tools.](https://www.sitepoint.com/10-javascript-online-browser-based-debugging-tools/)
97 | [JavaScript console in your browser.](http://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers)
98 | [The Codecademy console.](http://labs.codecademy.com/)
99 | -------------------------------------------------------------------------------- /programmer-skills/setting-up-a-local-server.md: -------------------------------------------------------------------------------- 1 | # Setting Up a Local Server 2 | 3 | 4 | ![XAMPP and MAMP](/images/setting-up-a-local-server.png) 5 | 6 | 7 | If you're working on a website, it's always a good idea to use a local test server. This is a server that runs on your computer, so you can work on a copy of a website that only you can access. This means a local server will allow you to see how your changes will work in the browser, without affecting the website that users actually visit [until you push your changes to the live site](http://codingforeveryone.foundersandcoders.org/programmer-skills/git-basics.html). That means you can make all the changes you want without worrying you're sending your users to a broken site! 8 | 9 | ## Installation 10 | 11 | The easiest way to set up a local server is to install a programme that will do it all for you. [XAMPP](https://www.apachefriends.org/index.html) is a free and open-source programme that can be used on Windows, Linux or OS X. If you're using a Mac, however, you'll probably want to use [MAMP](https://www.mamp.info/en/), as it's a bit easier to use. If you're on Windows, you can also pay for [MAMP Pro for Windows](https://sites.fastspring.com/mamp/product/mamp-pro). 12 | 13 | Both XAMPP and MAMP are easy to install, though MAMP will also install a trial version of their paid programme MAMP Pro - feel free to just ignore it, you probably don't need any of the extra features right now. 14 | 15 | When you open the programme, you'll need to activate both the Apache and MySQL servers. On MAMP, this will happen automatically, while on XAMPP you'll have to click the Start button for each. 16 | 17 | Now to check everything is working properly! If you're using MAMP, just click the button that reads 'Open Start Page'; for XAMPP, open your browser and navigate to `http://localhost/`. If it works, you're good to go! 18 | 19 | ## Now What? 20 | 21 | Anything you want to run through your local server has to live in its `htdocs` folder. You'll be able to find this inside your MAMP/XAMPP installation folder - check your Applications folder on Mac or Program Files on Windows. You should create any new sites in here or, if you already have a site saved elsewhere, just move it over. Now, you should be able to access it in your browser by navigating to `http://localhost/[name of your folder]`. You'll be able to see any changes you make to it by refreshing the page. 22 | 23 | You can install any kind of CMS like WordPress or Drupal on your local server too - lots of people have written helpful guides on how to do this. 24 | 25 | 26 | Running your own server might initially sound like a daunting prospect, but with the help of software like MAMP and XAMPP it's actually pretty simple. Enjoy squashing bugs and changing fonts worry-free! 27 | 28 | ### Further Reading 29 | 30 | * [MAMP FAQs](https://www.mamp.info/en/documentation/) 31 | * XAMPP FAQs for [Windows](https://www.apachefriends.org/faq_windows.html), [Linux](https://www.apachefriends.org/faq_linux.html) and [OS X](https://www.apachefriends.org/faq_osx.html) 32 | * [Installing WordPress Locally on Your Mac with MAMP](https://codex.wordpress.org/Installing_WordPress_Locally_on_Your_Mac_With_MAMP) 33 | * [How to Install XAMPP and WordPress Locally on PC/Windows](https://premium.wpmudev.org/blog/setting-up-xampp/) 34 | * [Installing MAMP and Drupal Locally on a Mac](https://www.drupal.org/node/2109497) 35 | * [Quick Install Drupal with XAMPP on Windows](https://www.drupal.org/node/2347717) 36 | -------------------------------------------------------------------------------- /programmer-skills/setting-up-your-development-environment.md: -------------------------------------------------------------------------------- 1 | #Setting Up Your Development Environment 2 | 3 | Taking the time to properly set up your text editor massively speeds up your workflow in the long-run. Do it! 4 | 5 | ##Sublime Text 3 6 | 7 | ###Download and Installation 8 | Begin by downloading and installing Sublime [here](https://www.sublimetext.com/). 9 | 10 | ###Package Control 11 | Package Control allows you to add custom features ("packages") to Sublime. 12 | 13 | To get started, install Package Control by copying the code listed [here](https://packagecontrol.io/installation). 14 | The code to copy is shown in the red box, below. 15 | ![Copy the code in the red box](../images/package-control.png) 16 | 17 | Next, open Sublime. Select "View" --> "Show Console". 18 | 19 | Paste the red-box code into the console and hit "Enter". 20 | 21 | Once the installation is complete, close and re-open Sublime to allow it to update. 22 | 23 | To test that the installation was succesful, open your Command Palette with CTRL-SHIFT-P (CMD-SHIFT-P) and begin typing "install package". You should see an option appear 24 | called "Package Control: Install Package". Select this option to begin searching for and installing new packages! 25 | 26 | ###Packages 27 | 28 | Packages are customizing add-on features for your text editor. There are tons of them available for Sublime! Remember that some packages come with their own READMEs that detail how to correctly install them. 29 | 30 | * Colour scheme packages: 31 | These alter the colours of your code. _Recommended:_ **Dayle Rees Colour Schemes**. This package includes many colour schemes that you can test out and pick your favourite one of. 32 | 33 | * Themes: 34 | These alter the entire aesthetic of your workspace, including things like the appearance of folder icons. _Recommended:_ **Predawn**. 35 | 36 | * Bracket Highlighter: 37 | This package visually matches any bracket with its partner bracket when you click on it. This is extremely useful when dealing with nested blocks of code! _Recommended:_ **BracketHighlighter**. 38 | 39 | * JavaScript Autocompletion: 40 | This package will provide suggestions while you're writing your JS code. Huge time-saver. _Recommended:_ **tern_for_sublime** 41 | 42 | * HTML and CSS Autocompletion: 43 | This package is called Emmet and will autofill (via either the Tab key, or CTRL+E) while you're writing HTML and CSS. For example, to get a basic skeleton for your HTML code, save your document as a ".html" file to let Emmet know that you're writing HTML code. Then simply type an exclamation mark, "!", followed by the Tab key afterward. Emmet will produce your whole HTML skeleton on cue - it's that easy!. _Recommended:_ **Emmet** 44 | 45 | * Linter: 46 | A linter automatically checks for typos and small errors in your lines of code. To use such a package, you first have to download and install [node.js](https://nodejs.org/en/). Now install the package, "SublimeLinter". This is a required first step, but you'll have to now install separate linters for JS, CSS and HTML.

Go to your Terminal (or Command Line / Bash in Windows) and type in "npm install -g jshint" and run that. If it doesn't work, try "sudo npm install -g jshint". You may be prompted for an administrator password. Details on that can be found [here](https://github.com/SublimeLinter/SublimeLinter-jshint). Now go back to your package installer in Sublime (remember: CTRL-SHIFT-P --> "Install Package") and type in "SublimeLinter-jshint". Install it.

A similar process can be followed for installing your CSS linter. Go [this page](https://github.com/SublimeLinter/SublimeLinter-csslint) and find the relevant line of code for your Terminal/Command Line/Bash- it should be "npm install -g csslint" (or with a "sudo" in front). Then install "SublimeLinter-csslint" from your Package Installer.

For your HTML, install [HTML Tidy](https://github.com/SublimeLinter/SublimeLinter-html-tidy).

Restart Sublime and you should have a linter for your code! If you make an error (e.g. forgetting a semi-colon in your code), a red dot should appear next to that line of code. Click on the line and at the bottom of your screen, the linter will display a brief message telling you what it believes to be wrong with your code. 47 | 48 | ###Removing packages that you no longer want 49 | 50 | Quite easy: open your Command Palette (CTRL+SHIFT+P) and type "Package Control: Remove Package" and you will be able to remove any package that you currently have installed. 51 | 52 | 53 | ##Atom 54 | 55 | ###Packages 56 | * Atom HTML Preview: 57 | [This package](https://atom.io/packages/atom-html-preview) allows you to preview your HTML live, while you code! 58 | 59 | ##Brackets 60 | -------------------------------------------------------------------------------- /responsiveD3.md: -------------------------------------------------------------------------------- 1 | If you're building a visualisation with D3, many of your audience will be coming from mobile devices. 2 | 3 | Over in my responsiveD3Tutorial repo, I've created a tutorial 4 | that will walk you though how to make a D3 visualisation that is responsive, by way of listening for a resize event in the window. 5 | 6 | Any and all feedback welcome! 7 | 8 | Thanks
9 | Alison 10 | 11 | --------------------------------------------------------------------------------