diff --git a/.gitignore b/.gitignore index 5522779b..964829e6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ node_modules .grunt /_book/ +.vscode diff --git a/README.md b/README.md index 7ec588c8..b5a5a635 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,7 @@ -Learn Javascript -====== +# Learn Javascript This book will teach you the basics of programming and Javascript. Whether you are an experienced programmer or not, this book is intended for everyone who wishes to learn the JavaScript programming language. -![Screen](./assets/intro.png) +![](./assets/intro.png) -JavaScript (*JS for short*) is the programming language that enables web pages to respond to user interaction beyond the basic level. It was created in 1995, and is today one of the most famous and used programming languages. +JavaScript (_JS for short_) is the programming language that enables web pages to respond to user interaction beyond the basic level. It was created in 1995, and is today one of the most famous and used programming languages. diff --git a/SUMMARY.md b/SUMMARY.md index fb6a379d..94c76226 100644 --- a/SUMMARY.md +++ b/SUMMARY.md @@ -1,40 +1,39 @@ # Summary -* [Basics](basics/README.md) - * [Comments](basics/comments.md) - * [Variables](basics/variables.md) - * [Types](basics/types.md) - * [Equality](basics/equality.md) -* [Numbers](numbers/README.md) - * [Creation](numbers/create.md) - * [Basic Operators](numbers/operators.md) - * [Advanced Operators](numbers/advanced.md) -* [Strings](strings/README.md) - * [Creation](strings/create.md) - * [Concatenation](strings/concat.md) - * [Length](strings/length.md) -* [Conditional Logic](conditional/README.md) - * [If](conditional/if.md) - * [Else](conditional/else.md) - * [Comparators](conditional/comparators.md) - * [Concatenate](conditional/concatenate.md) -* [Arrays](arrays/README.md) - * [Indices](arrays/indices.md) - * [Length](arrays/length.md) -* [Loops](loops/README.md) - * [For](loops/for.md) - * [While](loops/while.md) - * [Do...While](loops/dowhile.md) -* [Functions](functions/README.md) - * [Declare](functions/declare.md) - * [Higher order](functions/higher_order.md) -* [Objects](objects/README.md) - * [Creation](objects/creation.md) - * [Properties](objects/properties.md) - * [Mutable](objects/mutable.md) - * [Reference](objects/reference.md) - * [Prototype](objects/prototype.md) - * [Delete](objects/delete.md) - * [Enumeration](objects/enumeration.md) - * [Global footprint](objects/global_footprint.md) - +- [Basics](basics/README.md) + - [Comments](basics/comments.md) + - [Variables](basics/variables.md) + - [Types](basics/types.md) + - [Equality](basics/equality.md) +- [Numbers](numbers/README.md) + - [Creation](numbers/create.md) + - [Basic Operators](numbers/operators.md) + - [Advanced Operators](numbers/advanced.md) +- [Strings](strings/README.md) + - [Creation](strings/create.md) + - [Concatenation](strings/concat.md) + - [Length](strings/length.md) +- [Conditional Logic](conditional/README.md) + - [If](conditional/if.md) + - [Else](conditional/else.md) + - [Comparators](conditional/comparators.md) + - [Concatenate](conditional/concatenate.md) +- [Arrays](arrays/README.md) + - [Indices](arrays/indices.md) + - [Length](arrays/length.md) +- [Loops](loops/README.md) + - [For](loops/for.md) + - [While](loops/while.md) + - [Do...While](loops/dowhile.md) +- [Functions](functions/README.md) + - [Declare](functions/declare.md) + - [Higher order](functions/higher_order.md) +- [Objects](objects/README.md) + - [Creation](objects/creation.md) + - [Properties](objects/properties.md) + - [Mutable](objects/mutable.md) + - [Reference](objects/reference.md) + - [Prototype](objects/prototype.md) + - [Delete](objects/delete.md) + - [Enumeration](objects/enumeration.md) + - [Global footprint](objects/global_footprint.md) diff --git a/arrays/README.md b/arrays/README.md index 0690816e..e9fd7c21 100644 --- a/arrays/README.md +++ b/arrays/README.md @@ -9,4 +9,4 @@ Here is a simple array: ```javascript // 1, 1, 2, 3, 5, and 8 are the elements in this array var numbers = [1, 1, 2, 3, 5, 8]; -``` \ No newline at end of file +``` diff --git a/arrays/length.md b/arrays/length.md index 78deb9f4..3e37c961 100644 --- a/arrays/length.md +++ b/arrays/length.md @@ -3,7 +3,7 @@ Arrays have a property called length, and it's pretty much exactly as it sounds, it's the length of the array. ```javascript -var array = [1 , 2, 3]; +var array = [1, 2, 3]; // Result: l = 3 var l = array.length; diff --git a/basics/README.md b/basics/README.md index 4ed143ce..3668d9e5 100644 --- a/basics/README.md +++ b/basics/README.md @@ -4,7 +4,7 @@ In this first chapter, we'll learn the basics of programming and the Javascript Programming means writing code. A book is made up of chapters, paragraphs, sentences, phrases, words and finally punctuation and letters, likewise a program can be broken down into smaller and smaller components. For now, the most important is a statement. A statement is analogous to a sentence in a book. On its own, it has structure and purpose, but without the context of the other statements around it, it isn't that meaningful. -A statement is more casually (and commonly) known as a *line of code*. That's because statements tend to be written on individual lines. As such, programs are read from top to bottom, left to right. You might be wondering what code (also called source code) is. That happens to be a broad term which can refer to the whole of the program or the smallest part. Therefore, a line of code is simply a line of your program. +A statement is more casually (and commonly) known as a _line of code_. That's because statements tend to be written on individual lines. As such, programs are read from top to bottom, left to right. You might be wondering what code (also called source code) is. That happens to be a broad term which can refer to the whole of the program or the smallest part. Therefore, a line of code is simply a line of your program. Here is a simple example: @@ -16,4 +16,4 @@ var world = "World"; var message = hello + " " + world; ``` -This code can be executed by another program called an *interpreter* that will read the code, and execute all the statements in the right order. +This code can be executed by another program called an _interpreter_ that will read the code, and execute all the statements in the right order. diff --git a/basics/comments.md b/basics/comments.md index 21d9c8d2..95b56fd7 100644 --- a/basics/comments.md +++ b/basics/comments.md @@ -4,14 +4,14 @@ Comments are statements that will not be executed by the interpreter, comments a In Javascript, comments can be written in 2 different ways: -* Line starting with `//`: +- Line starting with `//`: ```javascript // This is a comment, it will be ignored by the interpreter var a = "this is a variable defined in a statement"; ``` -* Section of code starting with `/*`and ending with `*/`, this method is used for multi-line comments: +- Section of code starting with `/*`and ending with `*/`, this method is used for multi-line comments: ```javascript /* @@ -20,28 +20,3 @@ it will be ignored by the interpreter */ var a = "this is a variable defined in a statement"; ``` - - ---- - -Mark the editor's contents as a comment - -```js - -Mark me as a comment -or I'll throw an error - -``` - -```js -/* -Mark me as a comment -or I'll throw an error -*/ -``` - -```js -assert(true); -``` - ---- diff --git a/basics/equality.md b/basics/equality.md index c3ea8716..8561977d 100644 --- a/basics/equality.md +++ b/basics/equality.md @@ -2,9 +2,10 @@ Programmers frequently need to determine the equality of variables in relation to other variables. This is done using an equality operator. -The most basic equality operator is the `==` operator. This operator does everything it can to determine if two variables are equal, even if they are not of the same type. +The most basic equality operator is the `==` operator. This operator does everything it can to determine if two variables are equal, even if they are not of the same type. For example, assume: + ```javascript var foo = 42; var bar = 42; @@ -12,6 +13,6 @@ var baz = "42"; var qux = "life"; ``` -`foo == bar` will evaluate to `true` and `baz == qux` will evaluate to `false`, as one would expect. However, `foo == baz` will *also* evaluate to `true` despite `foo` and `baz` being different types. Behind the scenes the `==` equality operator attempts to force its operands to the same type before determining their equality. This is in contrast to the `===` equality operator. +`foo == bar` will evaluate to `true` and `baz == qux` will evaluate to `false`, as one would expect. However, `foo == baz` will _also_ evaluate to `true` despite `foo` and `baz` being different types. Behind the scenes the `==` equality operator attempts to force its operands to the same type before determining their equality. This is in contrast to the `===` equality operator. -The `===` equality operator determines that two variables are equal if they are of the same type *and* have the same value. With the same assumptions as before, this means that `foo === bar` will still evaluate to `true`, but `foo === baz` will now evaluate to `false`. `baz === qux` will still evaluate to `false`. +The `===` equality operator determines that two variables are equal if they are of the same type _and_ have the same value. With the same assumptions as before, this means that `foo === bar` will still evaluate to `true`, but `foo === baz` will now evaluate to `false`. `baz === qux` will still evaluate to `false`. diff --git a/basics/types.md b/basics/types.md index cd0c65f7..12d231a9 100644 --- a/basics/types.md +++ b/basics/types.md @@ -4,23 +4,24 @@ Computers are sophisticated and can make use of more complex variables than just The most common types are: -* **Numbers** - * **Float**: a number, like 1.21323, 4, -33.5, 100004 or 0.123 - * **Integer**: a number like 1, 12, -33, 140 but not 1.233 +- **Numbers** -* **String**: a line of text like "boat", "elephant" or "damn, you are tall!" + - **Float**: a number, like 1.21323, 4, -33.5, 100004 or 0.123 + - **Integer**: a number like 1, 12, -33, 140 but not 1.233 -* **Boolean**: either true or false, but nothing else +- **String**: a line of text like "boat", "elephant" or "damn, you are tall!" -* **Arrays**: a collection of values like: 1,2,3,4,'I am bored now' +- **Boolean**: either true or false, but nothing else -* **Objects**: a representation of a more complex object +- **Arrays**: a collection of values like: 1,2,3,4,'I am bored now' -* **null**: a variable that contains null contains no valid Number, String, Boolean, Array, or Object +- **Objects**: a representation of a more complex object -* **undefined**: the undefined value is obtained when you use an object property that does not exist, or a variable that has been declared, but has no value assigned to it. +- **null**: a variable that contains null contains no valid Number, String, Boolean, Array, or Object -JavaScript is a *“loosely typed”* language, which means that you don't have to explicitly declare what type of data the variables are. You just need to use the ```var``` keyword to indicate that you are declaring a variable, and the interpreter will work out what data type you are using from the context, and use of quotes. +- **undefined**: the undefined value is obtained when you use an object property that does not exist, or a variable that has been declared, but has no value assigned to it. + +JavaScript is a _“loosely typed”_ language, which means that you don't have to explicitly declare what type of data the variables are. You just need to use the `var` keyword to indicate that you are declaring a variable, and the interpreter will work out what data type you are using from the context, and use of quotes. {% exercise %} Create a variable named `a` using the keyword `var`. diff --git a/book.json b/book.json deleted file mode 100644 index 5756364a..00000000 --- a/book.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "gitbook": ">1.x.x", - "plugins": [ - "exercises" - ] -} \ No newline at end of file diff --git a/conditional/README.md b/conditional/README.md index e0dc77ca..3d5f1a80 100644 --- a/conditional/README.md +++ b/conditional/README.md @@ -6,4 +6,4 @@ First of all conditions can be used to ensure that your program works, regardles The other thing conditions can do for you is allow for branching. You might have encountered branching diagrams before, for example when filling out a form. Basically, this refers to executing different “branches” (parts) of code, depending on if the condition is met or not. -In this chapter, we'll learn the base of conditional logic in Javascript. \ No newline at end of file +In this chapter, we'll learn the base of conditional logic in Javascript. diff --git a/conditional/comparators.md b/conditional/comparators.md index 3cc21648..52f5ce92 100644 --- a/conditional/comparators.md +++ b/conditional/comparators.md @@ -8,17 +8,16 @@ if (country === "France") { } ``` -The conditional part is the variable `country` followed by the three equal signs (`===`). Three equal signs tests if the variable `country` has both the correct value (`France`) and also the correct type (`String`). You can test conditions with double equal signs, too, however a conditional such as `if (x == 5)` would then return true for both `var x = 5;` and `var x = "5";`. Depending on what your program is doing, this could make quite a difference. It is highly recommended as a best practice that you always compare equality with three equal signs (`===` and `!==`) instead of two (`==` and `!=`). +The conditional part is the variable `country` followed by the three equal signs (`===`). Three equal signs tests if the variable `country` has both the correct value (`France`) and also the correct type (`String`). You can test conditions with double equal signs, too, however a conditional such as `if (x == 5)` would then return true for both `var x = 5;` and `var x = "5";`. Depending on what your program is doing, this could make quite a difference. It is highly recommended as a best practice that you always compare equality with three equal signs (`===` and `!==`) instead of two (`==` and `!=`). Other conditional test: -* ```x > a```: is x bigger than a? -* ```x < a```: is x less than a? -* ```x <= a```: is x less than or equal to a? -* ```x >=a```: is x greater than or equal to a? -* ```x != a```: is x not a? -* ```x```: does x exist? - +- `x > a`: is x bigger than a? +- `x < a`: is x less than a? +- `x <= a`: is x less than or equal to a? +- `x >=a`: is x greater than or equal to a? +- `x != a`: is x not a? +- `x`: does x exist? {% exercise %} Add a condition to change the value of `a` to the number 10 if `x` is bigger than 5. @@ -30,7 +29,7 @@ var x = 6; var a = 0; if (x > 5) { - a = 10; +a = 10; } {% validation %} assert(a === 10); @@ -41,7 +40,7 @@ assert(a === 10); In order to avoid the if-else hassle, simple logical comparisons can be utilised. ```js -var topper = (marks > 85) ? "YES" : "NO"; +var topper = marks > 85 ? "YES" : "NO"; ``` In the above example, `?` is a logical operator. The code says that if the value of marks is greater than 85 i.e. `marks > 85` , then `topper = YES` ; otherwise `topper = NO` . Basically, if the comparison condition proves true, the first argument is accessed and if the comparison condition is false , the second argument is accessed. diff --git a/conditional/concatenate.md b/conditional/concatenate.md index d31b0565..aed32557 100644 --- a/conditional/concatenate.md +++ b/conditional/concatenate.md @@ -6,21 +6,21 @@ In JavaScript “or” is written as `||` and “and” is written as `&&`. Say you want to test if the value of x is between 10 and 20—you could do that with a condition stating: -``` -if(x > 10 && x < 20) { +```javascript +if (x > 10 && x < 20) { ... } ``` If you want to make sure that country is either “England” or “Germany” you use: -``` -if(country === 'England' || country === 'Germany') { +```javascript +if (country === "England" || country === "Germany") { ... } ``` -**Note**: Just like operations on numbers, Condtions can be grouped using parenthesis, ex: ```if ( (name === "John" || name === "Jennifer") && country === "France")```. +**Note**: Just like operations on numbers, Condtions can be grouped using parenthesis, ex: `if ( (name === "John" || name === "Jennifer") && country === "France")`. {% exercise %} Fill up the 2 conditions so that `primaryCategory` equals `"E/J"` only if name equals `"John"` and country is `"England"`, and so that `secondaryCategory` equals `"E|J"` only if name equals `"John"` or country is `"England"` @@ -29,11 +29,11 @@ var name = "John"; var country = "England"; var primaryCategory, secondaryCategory; -if ( /* Fill here */ ) { - primaryCategory = "E/J"; +if ( /_ Fill here _/ ) { +primaryCategory = "E/J"; } -if ( /* Fill here */ ) { - secondaryCategory = "E|J"; +if ( /_ Fill here _/ ) { +secondaryCategory = "E|J"; } {% solution %} var name = "John"; @@ -41,10 +41,10 @@ var country = "England"; var primaryCategory, secondaryCategory; if (name === "John" && country === "England") { - primaryCategory = "E/J"; +primaryCategory = "E/J"; } if (name === "John" || country === "England") { - secondaryCategory = "E|J"; +secondaryCategory = "E|J"; } {% validation %} assert(primaryCategory === "E/J" && secondaryCategory === "E|J"); diff --git a/conditional/else.md b/conditional/else.md index e667ddb7..6f06a73d 100644 --- a/conditional/else.md +++ b/conditional/else.md @@ -5,26 +5,25 @@ There is also an `else` clause that will be applied when the first condition isn ```javascript var umbrellaMandatory; -if(country === 'England'){ - umbrellaMandatory = true; +if (country === "England") { + umbrellaMandatory = true; } else { - umbrellaMandatory = false; + umbrellaMandatory = false; } ``` The `else` clause can be joined with another `if`. Lets remake the example from the previous article: ```javascript -if(country === 'England') { - ... -} else if(country === 'France') { - ... -} else if(country === 'Germany') { - ... +if (country === "England") { + ... +} else if (country === "France") { + ... +} else if (country === "Germany") { + ... } ``` - {% exercise %} Fill up the value of `name` to validate the `else` condition. {% initial %} @@ -33,7 +32,7 @@ var name = if (name === "John") { } else if (name === "Aaron") { - // Valid this condition +// Valid this condition } {% solution %} var name = "Aaron"; @@ -41,7 +40,7 @@ var name = "Aaron"; if (name === "John") { } else if (name === "Aaron") { - // Valid this condition +// Valid this condition } {% validation %} assert(name === "Aaron"); diff --git a/conditional/if.md b/conditional/if.md index b9692db4..6aeeddbf 100644 --- a/conditional/if.md +++ b/conditional/if.md @@ -3,32 +3,39 @@ The easiest condition is an if statement and its syntax is `if(condition){ do this … }`. The condition has to be true for the code inside the curly braces to be executed. You can for example test a string and set the value of another string dependent on its value: ```javascript -var country = 'France'; +var country = "France"; var weather; var food; var currency; -if(country === 'England') { - weather = 'horrible'; - food = 'filling'; - currency = 'pound sterling'; +if (country === "England") { + weather = "horrible"; + food = "filling"; + currency = "pound sterling"; } -if(country === 'France') { - weather = 'nice'; - food = 'stunning, but hardly ever vegetarian'; - currency = 'funny, small and colourful'; +if (country === "France") { + weather = "nice"; + food = "stunning, but hardly ever vegetarian"; + currency = "funny, small and colourful"; } -if(country === 'Germany') { - weather = 'average'; - food = 'wurst thing ever'; - currency = 'funny, small and colourful'; +if (country === "Germany") { + weather = "average"; + food = "wurst thing ever"; + currency = "funny, small and colourful"; } -var message = 'this is ' + country + ', the weather is ' + - weather + ', the food is ' + food + ' and the ' + - 'currency is ' + currency; +var message = + "this is " + + country + + ", the weather is " + + weather + + ", the food is " + + food + + " and the " + + "currency is " + + currency; ``` **Note:** Conditions can also be nested. diff --git a/cover.jpg b/cover.jpg deleted file mode 100644 index 639fbd93..00000000 Binary files a/cover.jpg and /dev/null differ diff --git a/cover_small.jpg b/cover_small.jpg deleted file mode 100644 index 598f51bb..00000000 Binary files a/cover_small.jpg and /dev/null differ diff --git a/functions/README.md b/functions/README.md index 76f2091d..1edee5c5 100644 --- a/functions/README.md +++ b/functions/README.md @@ -3,4 +3,3 @@ Functions, are one of the most powerful and essential notions in programming. Functions like mathematical functions perform transformations, they take input values called **arguments** and **return** an output value. - diff --git a/functions/declare.md b/functions/declare.md index cf4e8b31..9756103b 100644 --- a/functions/declare.md +++ b/functions/declare.md @@ -4,27 +4,27 @@ Functions, like variables, must be declared. Let's declare a function `double` t ```javascript function double(x) { - return 2 * x; + return 2 * x; } ``` ->*Note:* the function above **may** be referenced before it has been defined. +> _Note:_ the function above **may** be referenced before it has been defined. Functions are also values in JavaScript; they can be stored in variables (just like numbers, strings, etc ...) and given to other functions as arguments : ```javascript -var double = function(x) { - return 2 * x; +var double = function (x) { + return 2 * x; }; ``` ->*Note:* the function above **may not** be referenced before it is defined, just like any other variable. +> _Note:_ the function above **may not** be referenced before it is defined, just like any other variable. {% exercise %} Declare a function named `triple` that takes an argument and returns its triple. {% solution %} var triple = function(x) { - return x * 3; +return x \* 3; } {% validation %} assert(triple); diff --git a/functions/higher_order.md b/functions/higher_order.md index 66984ad9..bd2a3bae 100644 --- a/functions/higher_order.md +++ b/functions/higher_order.md @@ -2,35 +2,34 @@ Higher order functions are functions that manipulate other functions. For example, a function can take other functions as arguments and/or produce a function as its return value. -Such *fancy* functional techniques are powerful constructs available to you in JavaScript and other high-level languages like python, lisp, etc. +Such _fancy_ functional techniques are powerful constructs available to you in JavaScript and other high-level languages like python, lisp, etc. We will now create two simple functions, `add_2` and `double`, and a higher order function called `map`. `map` will accept two arguments, `func` and `list` (its declaration will therefore begin `map(func,list)`), and return an array. `func` (the first argument) will be a function that will be applied to each of the elements in the array `list` (the second argument). ```javascript // Define two simple functions -var add_2 = function(x) { - return x + 2; +var add_2 = function (x) { + return x + 2; }; -var double = function(x) { - return 2 * x; +var double = function (x) { + return 2 * x; }; // map is cool function that accepts 2 arguments: // func the function to call // list a array of values to call func on -var map = function(func, list) { - var output=[]; // output list - for(idx in list) { - output.push( func(list[idx]) ); - } - return output; -} - +var map = function (func, list) { + var output = []; // output list + for (idx in list) { + output.push(func(list[idx])); + } + return output; +}; // We use map to apply a function to an entire list // of inputs to "map" them to a list of corresponding outputs -map(add_2, [5,6,7]) // => [7, 8, 9] -map(double, [5,6,7]) // => [10, 12, 14] +map(add_2, [5, 6, 7]); // => [7, 8, 9] +map(double, [5, 6, 7]); // => [10, 12, 14] ``` The functions in the above example are simple. However, when passed as arguments to other functions, they can be composed in unforeseen ways to build more complex functions. @@ -38,14 +37,14 @@ The functions in the above example are simple. However, when passed as arguments For example, if we notice that we use the invocations `map(add_2, ...)` and `map(double, ...)` very often in our code, we could decide we want to create two special-purpose list processing functions that have the desired operation baked into them. Using function composition, we could do this as follows: ```javascript -process_add_2 = function(list) { - return map(add_2, list); -} -process_double = function(list) { - return map(double, list); -} -process_add_2([5,6,7]) // => [7, 8, 9] -process_double([5,6,7]) // => [10, 12, 14] +process_add_2 = function (list) { + return map(add_2, list); +}; +process_double = function (list) { + return map(double, list); +}; +process_add_2([5, 6, 7]); // => [7, 8, 9] +process_double([5, 6, 7]); // => [10, 12, 14] ``` Now let's create a function called `buildProcessor` that takes a function `func` as input @@ -53,33 +52,31 @@ and returns a `func`-processor, that is, a function that applies `func` to each ```javascript // a function that generates a list processor that performs -var buildProcessor = function(func) { - var process_func = function(list) { - return map(func, list); - } - return process_func; -} +var buildProcessor = function (func) { + var process_func = function (list) { + return map(func, list); + }; + return process_func; +}; // calling buildProcessor returns a function which is called with a list input - // using buildProcessor we could generate the add_2 and double list processors as follows: process_add_2 = buildProcessor(add_2); process_double = buildProcessor(double); -process_add_2([5,6,7]) // => [7, 8, 9] -process_double([5,6,7]) // => [10, 12, 14] +process_add_2([5, 6, 7]); // => [7, 8, 9] +process_double([5, 6, 7]); // => [10, 12, 14] ``` - Let's look at another example. We'll create a function called `buildMultiplier` that takes a number `x` as input and returns a function that multiplies its argument by `x` : ```javascript -var buildMultiplier = function(x) { - return function(y) { - return x * y; - } -} +var buildMultiplier = function (x) { + return function (y) { + return x * y; + }; +}; var double = buildMultiplier(2); var triple = buildMultiplier(3); @@ -92,26 +89,26 @@ triple(3); // => 9 Define a function named `negate` that takes `add1` as argument and returns a function, that returns the negation of the value returned by `add1`. (Things get a bit more complicated ;) ) {% initial %} var add1 = function (x) { - return x + 1; +return x + 1; }; var negate = function(func) { - // TODO +// TODO }; // Should return -6 -// Because (5+1) * -1 = -6 +// Because (5+1) \* -1 = -6 negate(add1)(5); {% solution %} var add1 = function (x) { - return x + 1; +return x + 1; } var negate = function(func) { - return function(x) { - return -1 * func(x); - } +return function(x) { +return -1 \* func(x); +} } negate(add1)(5); diff --git a/loops/README.md b/loops/README.md index d41b905f..cdb29ec3 100644 --- a/loops/README.md +++ b/loops/README.md @@ -15,7 +15,7 @@ doThing(cars[4]); You can write: ```javascript -for (var i=0; i < cars.length; i++) { - doThing(cars[i]); +for (var i = 0; i < cars.length; i++) { + doThing(cars[i]); } -``` \ No newline at end of file +``` diff --git a/loops/dowhile.md b/loops/dowhile.md index ad3e9fe7..bafe0a19 100644 --- a/loops/dowhile.md +++ b/loops/dowhile.md @@ -1,27 +1,25 @@ # Do...While Loop -The do...while statement creates a loop that executes a specified statement until the test condition evaluates to be false. The condition is evaluated after executing the statement. -Syntax for do... while is +The do...while statement creates a loop that executes a specified statement until the test condition evaluates to be false. The condition is evaluated after executing the statement. +Syntax for do... while is ```javascript -do{ - // statement -} -while(expression) ; +do { + // statement +} while (expression); ``` Lets for example see how to print numbers less than 10 using `do...while` loop: -``` +```javascript var i = 0; do { - document.write(i + " "); - i++; // incrementing i by 1 + document.write(i + " "); + i++; // incrementing i by 1 } while (i < 10); ``` ->***Note***: `i = i + 1` can be written `i++`. - +> **_Note_**: `i = i + 1` can be written `i++`. {% exercise %} Using a do...while-loop, print numbers between less than 5. @@ -30,6 +28,6 @@ var i = 0; {% solution %} var i = 0; do { - i++; // incrementing i by 1 +i++; // incrementing i by 1 } while (i < 5); {% endexercise %} diff --git a/loops/for.md b/loops/for.md index 4dbd89e7..0529f2fc 100644 --- a/loops/for.md +++ b/loops/for.md @@ -3,21 +3,20 @@ The easiest form of a loop is the for statement. This one has a syntax that is similar to an if statement, but with more options: ```javascript -for(condition; end condition; change){ +for (condition; end condition; change) { // do it, do it now } ``` Lets for example see how to execute the same code ten-times using a `for` loop: -``` -for(var i = 0; i < 10; i = i + 1){ - // do this code ten-times +```javascript +for (var i = 0; i < 10; i = i + 1) { + // do this code ten-times } ``` ->***Note***: `i = i + 1` can be written `i++`. - +> **_Note_**: `i = i + 1` can be written `i++`. {% exercise %} Using a for-loop, create a variable named `message` that equals the concatenation of integers (0, 1, 2, ...) from 0 to 99. @@ -27,13 +26,13 @@ var message = ""; var message = ""; for(var i = 0; i < 100; i++){ - message = message + i; +message = message + i; } {% validation %} var message2 = "" for(var i = 0; i < 100; i++){ - message2 = message2 + i; +message2 = message2 + i; } assert(message === message2); {% endexercise %} diff --git a/loops/while.md b/loops/while.md index bcc3ffb0..4b705b0b 100644 --- a/loops/while.md +++ b/loops/while.md @@ -3,33 +3,24 @@ While Loops repetitively execute a block of code as long as a specified condition is true. ```javascript -while(condition){ - // do it as long as condition is true +while (condition) { + // do it as long as condition is true } ``` For example, the loop in this example will repetitively execute its block of code as long as the variable i is less than 5: ```javascript -var i = 0, x = ""; +var i = 0, + x = ""; while (i < 5) { - x = x + "The number is " + i; - i++; + x = x + "The number is " + i; + i++; } ``` -The Do/While Loop is a variant of the while loop. This loop will execute the code block once before checking if the condition is true. It then repeats the loop as long as the condition is true: - -```javascript -do { - // code block to be executed -} while (condition); -``` - - **Note**: Be careful to avoid infinite looping if the condition is always true! - {% exercise %} Using a while-loop, create a variable named `message` that equals the concatenation of integers (0, 1, 2, ...) as long as its length (`message.length`) is less than 100. {% initial %} @@ -39,16 +30,16 @@ var message = ""; var i = 0; while (message.length < 100) { - message = message + i; - i = i + 1; +message = message + i; +i = i + 1; } {% validation %} var message2 = ""; var i2 = 0; while (message2.length < 100) { - message2 = message2 + i2; - i2 = i2 + 1; +message2 = message2 + i2; +i2 = i2 + 1; } assert(message === message2); {% endexercise %} diff --git a/numbers/advanced.md b/numbers/advanced.md index 12cad0e7..7cc48de8 100644 --- a/numbers/advanced.md +++ b/numbers/advanced.md @@ -2,15 +2,13 @@ Some advanced operators can be used, such as: -* **Modulus (division remainder)**: ```x = y % 2``` -* **Increment**: Given a = 5 - * ```c = a++```, Results: c = 5 and a = 6 - * ```c = ++a```, Results: c = 6 and a = 6 -* **Decrement**: Given a = 5 - * ```c = a--```, Results: c = 5 and a = 4 - * ```c = --a```, Results: c = 4 and a = 4 - - +- **Modulus (division remainder)**: `x = y % 2` +- **Increment**: Given a = 5 + - `c = a++`, Results: c = 5 and a = 6 + - `c = ++a`, Results: c = 6 and a = 6 +- **Decrement**: Given a = 5 + - `c = a--`, Results: c = 5 and a = 4 + - `c = --a`, Results: c = 4 and a = 4 {% exercise %} Define a variable `c` as the modulus of the decremented value of `x` by 3. diff --git a/numbers/create.md b/numbers/create.md index e5bfae69..2bf1243a 100644 --- a/numbers/create.md +++ b/numbers/create.md @@ -1,10 +1,10 @@ # Creation -Creating a number is easy, it can be done just like for any other variable type using the ```var``` keyword. +Creating a number is easy, it can be done just like for any other variable type using the `var` keyword. Numbers can be created from a constant value: -``` +```javascript // This is a float: var a = 1.2; @@ -14,7 +14,7 @@ var b = 10; Or from the value of another variable: -``` +```javascript var a = 2; var b = a; ``` diff --git a/numbers/operators.md b/numbers/operators.md index e6202271..b77ae6a1 100644 --- a/numbers/operators.md +++ b/numbers/operators.md @@ -2,13 +2,12 @@ You can apply mathematic operations to numbers using some basic operators like: -* **Addition**: ```c = a + b``` -* **Subtraction**: ```c = a - b``` -* **Multiplication**: ```c = a * b``` -* **Division**: ```c = a / b``` - -You can use parentheses just like in math to separate and group expressions: ```c = (a / b) + d``` +- **Addition**: `c = a + b` +- **Subtraction**: `c = a - b` +- **Multiplication**: `c = a * b` +- **Division**: `c = a / b` +You can use parentheses just like in math to separate and group expressions: `c = (a / b) + d` {% exercise %} Create a variable `x` equal to the sum of `a` and `b` divided by `c` and finally multiplied by `d`. @@ -25,7 +24,7 @@ var b = 1.567; var c = 6758.768; var d = 45084; -var x = ((a + b) / c) * d; +var x = ((a + b) / c) _ d; {% validation %} -assert(x === (((a + b) / c) * d)); +assert(x === (((a + b) / c) _ d)); {% endexercise %} diff --git a/objects/README.md b/objects/README.md index 12730441..eda1fb3d 100644 --- a/objects/README.md +++ b/objects/README.md @@ -1,4 +1,5 @@ # Objects + The primitive types of JavaScript are `true`, `false`, numbers, strings, `null` and `undefined`. **Every other value is an `object`.** In JavaScript objects contain `propertyName`: `propertyValue` pairs. diff --git a/objects/creation.md b/objects/creation.md index e1a82b3a..5af66efa 100644 --- a/objects/creation.md +++ b/objects/creation.md @@ -1,19 +1,20 @@ # Creation + There are two ways to create an `object` in JavaScript: 1. literal - ```js - var object = {}; - // Yes, simply a pair of curly braces! + ```js + var object = {}; + // Yes, simply a pair of curly braces! + ``` - ``` - > ***Note:*** this is the **recomended** way. + > **_Note:_** this is the **recommended** way. 2. and object-oriented - ```js - var object = new Object(); + ```js + var object = new Object(); + ``` - ``` - > ***Note:*** it's almost like Java. + > **_Note:_** it's almost like Java. diff --git a/objects/delete.md b/objects/delete.md index b4b5cf1b..ec930622 100644 --- a/objects/delete.md +++ b/objects/delete.md @@ -1,14 +1,16 @@ # Delete + `delete` can be used to **remove a property** from an object. It will remove a property from the object if it has one. It will not look further in the prototype chain. Removing a property from an object may allow a property from the prototype chain to shine through: + ```js -var adult = {age:26}, - child = Object.create(adult); - child.age = 8; +var adult = { age: 26 }, + child = Object.create(adult); +child.age = 8; delete child.age; - /* Remove age property from child, revealing the age of the prototype, because then it is not overriden. */ +/* Remove age property from child, revealing the age of the prototype, because then it is not overriden. */ var prototypeAge = child.age; - // 26, because child does not have its own age property. +// 26, because child does not have its own age property. ``` diff --git a/objects/enumeration.md b/objects/enumeration.md index 2e4c49dd..53ea2892 100644 --- a/objects/enumeration.md +++ b/objects/enumeration.md @@ -1,20 +1,20 @@ # Enumeration + The `for in` statement can loop over all of the property names in an object. The enumeration will include functions and prototype properties. + ```js var fruit = { apple: 2, - orange:5, - pear:1 -}, -sentence = 'I have ', -quantity; -for (kind in fruit){ - quantity = fruit[kind]; - sentence += quantity+' '+kind+ - (quantity===1?'':'s')+ - ', '; + orange: 5, + pear: 1, + }, + sentence = "I have ", + quantity; +for (kind in fruit) { + quantity = fruit[kind]; + sentence += quantity + " " + kind + (quantity === 1 ? "" : "s") + ", "; } - // The following line removes the trailing coma. -sentence = sentence.substr(0,sentence.length-2)+'.'; - // I have 2 apples, 5 oranges, 1 pear. +// The following line removes the trailing coma. +sentence = sentence.substr(0, sentence.length - 2) + "."; +// I have 2 apples, 5 oranges, 1 pear. ``` diff --git a/objects/global_footprint.md b/objects/global_footprint.md index 86de8075..6572c4ba 100644 --- a/objects/global_footprint.md +++ b/objects/global_footprint.md @@ -1,18 +1,21 @@ # Global footprint + If you are developing a module, which might be running on a web page, which also runs other modules, then you must beware the variable name overlapping. Suppose we are developing a counter module: + ```js var myCounter = { - number : 0, - plusPlus : function(){ - this.number : this.number + 1; - }, - isGreaterThanTen : function(){ - return this.number > 10; - } -} + number: 0, + plusPlus: function () { + this.number = this.number + 1; + }, + isGreaterThanTen: function () { + return this.number > 10; + }, +}; ``` -> ***Note:*** this technique is often used with closures, to make the internal state immutable from the outside. + +> **_Note:_** this technique is often used with closures, to make the internal state immutable from the outside. The module now takes only one variable name — `myCounter`. If any other module on the page makes use of such names like `number` or `isGreaterThanTen` then it's perfectly safe, because we will not override each others values; diff --git a/objects/mutable.md b/objects/mutable.md index c5ead5f8..5fad79e1 100644 --- a/objects/mutable.md +++ b/objects/mutable.md @@ -1,10 +1,12 @@ # Mutable + The difference between objects and primitive values is that **we can change objects**, whereas primitive values are immutable. + ```js var myPrimitive = "first value"; - myPrimitive = "another value"; - // myPrimitive now points to another string. -var myObject = { key: "first value"}; - myObject.key = "another value"; - // myObject points to the same object. +myPrimitive = "another value"; +// myPrimitive now points to another string. +var myObject = { key: "first value" }; +myObject.key = "another value"; +// myObject points to the same object. ``` diff --git a/objects/properties.md b/objects/properties.md index 1581c5b4..5a3ed5af 100644 --- a/objects/properties.md +++ b/objects/properties.md @@ -1,35 +1,40 @@ # Properties + Object's property is a `propertyName`: `propertyValue` pair, where **property name can be only a string**. If it's not a string, it gets casted into a string. You can specify properties **when creating** an object **or later**. There may be zero or more properties separated by commas. + ```js var language = { - name: 'JavaScript', - isSupportedByBrowsers: true, - createdIn: 1995, - author:{ - firstName: 'Brendan', - lastName: 'Eich' - }, - // Yes, objects can be nested! - getAuthorFullName: function(){ - return this.author.firstName + " " + this.author.lastName; - } - // Yes, functions can be values too! + name: "JavaScript", + isSupportedByBrowsers: true, + createdIn: 1995, + author: { + firstName: "Brendan", + lastName: "Eich", + }, + // Yes, objects can be nested! + getAuthorFullName: function () { + return this.author.firstName + " " + this.author.lastName; + }, + // Yes, functions can be values too! }; - ``` -The following code demonstates how to **get** a property's value. + +The following code demonstrates how to **get** a property's value. + ```js var variable = language.name; - // variable now contains "JavaScript" string. - variable = language['name']; - // The lines above do the same thing. The difference is that the second one lets you use litteraly any string as a property name, but it's less readable. - variable = language.newProperty; - // variable is now undefined, because we have not assigned this property yet. +// variable now contains "JavaScript" string. +variable = language["name"]; +// The lines above do the same thing. The difference is that the second one lets you use litteraly any string as a property name, but it's less readable. +variable = language.newProperty; +// variable is now undefined, because we have not assigned this property yet. ``` + The following example shows how to **add** a new property **or change** an existing one. + ```js -language.newProperty = 'new value'; - // Now the object has a new property. If the property already exists, its value will be replaced. -language['newProperty'] = 'changed value'; - // Once again, you can access properties both ways. The first one (dot notation) is recomended. +language.newProperty = "new value"; +// Now the object has a new property. If the property already exists, its value will be replaced. +language["newProperty"] = "changed value"; +// Once again, you can access properties both ways. The first one (dot notation) is recomended. ``` diff --git a/objects/prototype.md b/objects/prototype.md index 43bb815a..4354c539 100644 --- a/objects/prototype.md +++ b/objects/prototype.md @@ -1,27 +1,32 @@ # Prototype + Every object is linked to a prototype object from which it inherits properties. All objects created from object literals (`{}`) are automatically linked to Object.prototype, which is an object that comes standard with JavaScript. When a JavaScript interpreter (a module in your browser) tries to find a property, which You want to retrieve, like in the following code: + ```js -var adult = {age: 26}, - retrievedProperty = adult.age; - // The line above +var adult = { age: 26 }, + retrievedProperty = adult.age; +// The line above ``` + First, the interpreter looks through every property the object itself has. For example, `adult` has only one own property — `age`. But besides that one it actually has a few more properties, which were inherited from Object.prototype. + ```js var stringRepresentation = adult.toString(); - // the variable has value of '[object Object]' +// the variable has value of '[object Object]' ``` `toString` is an Object.prototype's property, which was inherited. It has a value of a function, which returns a string representation of the object. If you want it to return a more meaningful representation, then you can override it. Simply add a new property to the adult object. ```js -adult.toString = function(){ - return "I'm "+this.age; -} +adult.toString = function () { + return "I'm " + this.age; +}; ``` + If you call the `toString` function now, the interpreter will find the new property in the object itself and stop. Thus the interpreter retrieves the first property it will find on the way from the object itself and further through its prototype. @@ -30,14 +35,14 @@ To set your own object as a prototype instead of the default Object.prototype, y ```js var child = Object.create(adult); - /* This way of creating objects lets us easily replace the default Object.prototype with the one we want. In this case, the child's prototype is the adult object. */ +/* This way of creating objects lets us easily replace the default Object.prototype with the one we want. In this case, the child's prototype is the adult object. */ child.age = 8; - /* Previously, child didn't have its own age property, and the interpreter had to look further to the child's prototype to find it. +/* Previously, child didn't have its own age property, and the interpreter had to look further to the child's prototype to find it. Now, when we set the child's own age, the interpreter will not go further. Note: adult's age is still 26. */ var stringRepresentation = child.toString(); - // The value is "I'm 8". - /* Note: we have not overridden the child's toString property, thus the adult's method will be invoked. If adult did not have toString property, then Object.prototype's toString method would be invoked, and we would get "[object Object]" instead of "I'm 8" */ +// The value is "I'm 8". +/* Note: we have not overridden the child's toString property, thus the adult's method will be invoked. If adult did not have toString property, then Object.prototype's toString method would be invoked, and we would get "[object Object]" instead of "I'm 8" */ ``` `child`'s prototype is `adult`, whose prototype is `Object.prototype`. This sequence of prototypes is called **prototype chain**. diff --git a/objects/reference.md b/objects/reference.md index 798e1e85..ecf1e725 100644 --- a/objects/reference.md +++ b/objects/reference.md @@ -1,20 +1,23 @@ # Reference + Objects are **never copied**. They are passed around by reference. + ```js - // Imagine I had a pizza -var myPizza = {slices: 5}; - // And I shared it with You +// Imagine I had a pizza +var myPizza = { slices: 5 }; +// And I shared it with You var yourPizza = myPizza; - // I eat another slice +// I eat another slice myPizza.slices = myPizza.slices - 1; var numberOfSlicesLeft = yourPizza.slices; - // Now We have 4 slices because myPizza and yourPizza - // reference to the same pizza object. -var a = {}, b = {}, c = {}; - // a, b, and c each refer to a - // different empty object +// Now We have 4 slices because myPizza and yourPizza +// reference to the same pizza object. +var a = {}, + b = {}, + c = {}; +// a, b, and c each refer to a +// different empty object a = b = c = {}; - // a, b, and c all refer to - // the same empty object - +// a, b, and c all refer to +// the same empty object ``` diff --git a/strings/README.md b/strings/README.md index 32b92767..b55bc1a7 100644 --- a/strings/README.md +++ b/strings/README.md @@ -6,6 +6,6 @@ In this course we will cover the basics. How to create new strings and perform c Here is an example of a string: -```javascript +``` "Hello World" -``` \ No newline at end of file +``` diff --git a/strings/concat.md b/strings/concat.md index 81c7a122..fe080337 100644 --- a/strings/concat.md +++ b/strings/concat.md @@ -3,7 +3,7 @@ Concatenation involves adding two or more strings together, creating a larger string containing the combined data of those original strings. This is done in JavaScript using the **+** operator. ```js -var bigStr = 'Hi ' + 'JS strings are nice ' + 'and ' + 'easy to add'; +var bigStr = "Hi " + "JS strings are nice " + "and " + "easy to add"; ``` {% exercise %} diff --git a/strings/create.md b/strings/create.md index 79e07fcf..511497ff 100644 --- a/strings/create.md +++ b/strings/create.md @@ -12,11 +12,10 @@ var otherStr = "Another nice string"; In Javascript, Strings can contain UTF-8 characters: -```js +``` "中文 español English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어"; ``` - **Note:** Strings can not be subtracted, multiplied or divided. {% exercise %} diff --git a/strings/length.md b/strings/length.md index b9932177..67866ec3 100644 --- a/strings/length.md +++ b/strings/length.md @@ -4,11 +4,10 @@ It's easy in Javascript to know how many characters are in string using the prop ```js // Just use the property .length -var size = 'Our lovely string'.length; - +var size = "Our lovely string".length; ``` -**Note:** Strings can not be substracted, multiplied or divided. +**Note:** Strings can not be subtracted, multiplied or divided. {% exercise %} Store in the variable named `size` the length of `str`. @@ -22,4 +21,4 @@ var str = "Hello World"; var size = str.length; {% validation %} assert(size === str.length); -{% endexercise %} \ No newline at end of file +{% endexercise %} diff --git a/strings/substrings.md b/strings/substrings.md deleted file mode 100644 index 998c48a5..00000000 --- a/strings/substrings.md +++ /dev/null @@ -1,28 +0,0 @@ -# Substrings - -substring is used to take a part of a string. -Syntax: substring(first_index,last_index). - -```js -var a = 'Hello world!'; -document.write(a.substring(1,6)); -``` -The preceding code snippet gives ```'ello '``` . Note that the 'w' (index 6) is not part of this substring. - -We could also do, -```js -var a = 'Hello world!'; -document.write(a.substring(2)); -``` -This gives the whole string from the character with index 2. ``` 'llo world!'``` - -##substr - -There is also a method substr() that works slightly differently. Instead of the second number being an index number, -it gives the number of characters. -```js -var a = 'Hello world!'; -document.write(a.substr(1,6)); -``` - -starts at the character with index 1 ('e') and then gives 6 characters, so the output is ```ello w```