diff --git a/README.md b/README.md index 7ec588c8..6b54c71a 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,12 @@ -Learn Javascript +Learn the basics of Javascript ====== +This book is based from [Learn Javascript made by Gitbook](https://www.gitbook.com/book/gitbookio/javascript/details). Ironhack adapted it a little so it has more exercises and it prepare yourself for our Technical Interviews! + 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) 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..7002f437 100644 --- a/SUMMARY.md +++ b/SUMMARY.md @@ -21,20 +21,19 @@ * [Arrays](arrays/README.md) * [Indices](arrays/indices.md) * [Length](arrays/length.md) + * [Array Methods](arrays/array_methods.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) + * [Higher order (Advanced)](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) + * [Reference (Advanced)](objects/reference.md) +* [Summary](summary/README.md) +* [Exercises](exercises/README.md) + + * [All Exercises](exercises/all_exercises.md) diff --git a/arrays/array_methods.md b/arrays/array_methods.md new file mode 100644 index 00000000..b3065096 --- /dev/null +++ b/arrays/array_methods.md @@ -0,0 +1,29 @@ +# Push + +You can insert elements inside an array with their method `push`. In fact, there is many other properties: +- `push(n)`: Add the element `n` at the end +- `pop()`: Remove the last element +- `sort()`: Sort the array by lexicographical order + +```javascript +var array = [1, 2, 4]; +array.push(8); +// Now array = [1, 2, 4, 8] +``` + +{% exercise %} +Add the city "Paris" to cities and sort it +{% initial %} +var cities = ["Madrid", "Barcelona", "Miami"]; +{% solution %} +var cities = ["Madrid", "Barcelona", "Miami"]; +cities.push("Paris"); +cities.sort(); + +{% validation %} +assert (cities.length === 4); +assert (cities[0] === "Barcelona"); +assert (cities[1] === "Madrid"); +assert (cities[2] === "Miami"); +assert (cities[3] === "Paris"); +{% endexercise %} \ No newline at end of file diff --git a/exercises/README.md b/exercises/README.md new file mode 100644 index 00000000..699197b4 --- /dev/null +++ b/exercises/README.md @@ -0,0 +1,4 @@ +# Exercises + +Now it's time to practise everything to consolidate your knowledge and make sure you understood everything! + diff --git a/exercises/all_exercises.md b/exercises/all_exercises.md new file mode 100644 index 00000000..ea69a516 --- /dev/null +++ b/exercises/all_exercises.md @@ -0,0 +1,338 @@ +# All Exercises + + + +{% exercise %} +Substration of 2 numbers
+- Input: 2 numbers (ex: 42 and 38)
+- Output: The difference (ex: 4) + +{% initial %} +function subs(a, b) { +} + +{% solution %} +function subs(a, b) { + return a - b; +} + +{% validation %} +assert(subs(42, 38) === 4, "Fail for subs(42, 38)"); +assert(subs(38, 42) === -4, "Fail for subs(38, 42)"); +assert(subs(100,100) === 0, "Fail for subs(100,100)"); + +{% endexercise %} + + + + +{% exercise %} +Even or Odd number?
+- Input: A number (ex: 42)
+- Output: A string that is either "Even" or "Odd" (ex: "Even") + +{% initial %} +function evenOrOdd(n) { +} + +{% solution %} +function evenOrOdd(n) { + if (n % 2 === 0) { + return "Even"; + } + else { + return "Odd"; + } +} + +{% validation %} +assert(evenOrOdd(42) === "Even", "Fail for evenOrOdd(42)"); +assert(evenOrOdd(1) === "Odd", "Fail for evenOrOdd(1)"); + +{% endexercise %} + + + + +{% exercise %} +Find the maximum of 2 numbers
+- Input: 2 numbers (ex: 42 and 38)
+- Output: The biggest number (ex: 42) + +{% initial %} +function maxOfTwoNumbers(a, b) { +} + +{% solution %} +function maxOfTwoNumbers(a, b) { + if (a > b) { + return a; + } + else { + return b; + } +} + +{% validation %} +assert(maxOfTwoNumbers(42, 38) === 42, "Fail for maxOfTwoNumbers(42, 38)"); +assert(maxOfTwoNumbers(38, 42) === 42, "Fail for maxOfTwoNumbers(38, 42)"); +assert(maxOfTwoNumbers(100,100) === 100, "Fail for maxOfTwoNumbers(100,100)"); + +{% endexercise %} + + + +{% exercise %} +Find the maximum of 3 numbers
+- Input: 3 numbers (ex: 42, 38 and 12)
+- Output: The biggest number (ex: 42) + +{% initial %} +function maxOfThreeNumbers(a, b, c) { +} + +{% solution %} +function maxOfThreeNumbers(a, b, c) { + if (a > b && a > c) { + return a; + } + else if (b > c) { + return b; + } + else { + return c; + } +} + +{% validation %} +assert(maxOfThreeNumbers(42, 38, 12) === 42, "Fail for maxOfThreeNumbers(42, 38, 12)"); +assert(maxOfThreeNumbers(38, 42, 12) === 42, "Fail for maxOfThreeNumbers(38, 42, 12)"); +assert(maxOfThreeNumbers(12, 38, 42) === 42, "Fail for maxOfThreeNumbers(12, 38, 42)"); + +{% endexercise %} + + + +{% exercise %} +Calculate the sum of all elements
+Input: Array of number (ex: [2, 10, 30])
+Output: The sum (ex: 42) + +{% initial %} +function sumArray(array) { +} + +{% solution %} +function sumArray(array) { + var curSum = 0; + for (var i = 0; i < array.length; i++) { + curSum += array[i]; + } + return curSum; +} + +{% validation %} +assert(sumArray([2, 10, 30]) === 42, "Fail for sumArray([2, 10, 30])"); +assert(sumArray([8]) === 8, "Fail for sumArray([8])"); + +{% endexercise %} + + + + +{% exercise %} +Find the maximum of a non-empty array
+- Input: Array of numbers (ex: [ 3, 5, 42, 12, 38 ] )
+- Output: The biggest number (ex: 42 ) + +{% initial %} +function maxOfArray(numbers) { +} + +{% solution %} +function maxOfArray(numbers) { + if (numbers.length === 0) { + return null; + } + var currentMax = numbers[0]; + for (var i = 1; i < numbers.length; i++) { + if (currentMax < numbers[i]) { + currentMax = numbers[i]; + } + } + return currentMax; +} + +{% validation %} +assert(maxOfArray([42, 38, 12]) === 42, "Fail for maxOfArray([42, 38, 12])"); +assert(maxOfArray([38, 42, 12]) === 42, "Fail for maxOfArray([38, 42, 12])"); +assert(maxOfArray([12, 38, 42]) === 42, "Fail for maxOfArray([12, 38, 42])"); + +{% endexercise %} + + + + + +{% exercise %} +Find the longest word
+- Input: Array of strings (ex: [ "car", "plane", "bike"])
+- Output: The longest string (ex: "plane") + +{% initial %} +function findLongestWord (words) { +} + +{% solution %} +function findLongestWord (words) { + var currentMax = ""; + for (var i = 0; i < words.length; i++) { + if (currentMax.length < words[i].length) { + currentMax = words[i]; + } + } + return currentMax; +} + + +{% validation %} +assert(findLongestWord([ "car", "plane", "bike"]) === "plane", 'Fail for findLongestWord([ "car", "plane", "bike"])'); +assert(findLongestWord([ "mystery", "brother", "aviator", "crocodile", "pearl", "orchard", "crackpot"]) === "crocodile", 'Fail for findLongestWord([ "mystery", "brother", "aviator", "crocodile", "pearl", "orchard", "crackpot"])'); + +{% endexercise %} + + + + + + + + +{% exercise %} +Finding a word inside an array
+- Input: Array of strings and a string (ex: ["Madrid", "Barcelona", "Miami"] and "Paris")
+- Output: A boolean that is true when the word is in the array (ex: false) + +{% initial %} +function doesWordExist(wordsArray, word) { +} + +{% solution %} +function doesWordExist(wordsArray, word) { + for (var i = 0; i < wordsArray.length; i++) { + if (wordsArray[i] === word) { + return true; + } + } + return false; +} + +{% validation %} +assert(doesWordExist(["Madrid", "Barcelona", "Miami"], "Paris") === false, 'Fail for doesWordExist(["Madrid", "Barcelona", "Miami"], "Paris")'); +assert(doesWordExist(["Madrid", "Barcelona", "Miami"], "Madrid") === true, 'Fail for doesWordExist(["Madrid", "Barcelona", "Miami"], "Madrid")'); + +{% endexercise %} + + + + +{% exercise %} +Get the fullname
+- Input: An object with at least 2 string properties "firstname" and "lastaname" (ex: {firstname: "John", lastname: "Doe"})
+- Output: A string the represents the fullname (dont' forget the space in the middle) (ex: John Doe) + +{% initial %} +function getFullname(person) { +} + +{% solution %} +function getFullname(person) { + return person.firstname + ' ' + person.lastname; +} + +{% validation %} +assert(getFullname({firstname: 'John', lastname: 'Doe'}) === 'John Doe', "Fail for getFullname({firstname: 'John', lastname: 'Doe'})"); +assert(getFullname({firstname: 'A', lastname: 'B'}) === 'A B', "Fail for getFullname({firstname: 'A', lastname: 'B'})"); + +{% endexercise %} + + + + + +{% exercise %} +Find the maximum of a two dimensional array
+- Input: Array of array of numbers (ex: [ [1,6], [3,8], [5,6] ] )
+- Output: The maximum of everything (ex: 8 ) + +{% initial %} +function maxTwoDimArray(matrix) { +} + +{% solution %} +function maxTwoDimArray(matrix) { + var currentMax = 0; + for (var row = 0; row < matrix.length; row++) { + for (var col = 0; col < matrix[row].length; col++) { + if (currentMax < matrix[row][col]) { + currentMax = matrix[row][col]; + } + } + } + return currentMax; +} + +{% validation %} +assert(maxTwoDimArray([[42]]) === 42, "Fail for maxTwoDimArray([[42]])"); +assert(maxTwoDimArray([ [1,6], [3,8], [5,6] ]) === 8, "Fail for maxTwoDimArray([ [1,6], [3,8], [5,6] ])"); + +{% endexercise %} + + + + + + +{% exercise %} +Build a triangle
+- Input: A number "n" (ex: 2)
+- Output: An array of length "n", that contains an array of "*" with a size incrementing by one each time (ex: [ ["*"],["*","*"] ])
+Example output for 4:
+[ + ["*"], + ["*","*"], + ["*","*","*"], + ["*","*","*","*"], +] + +{% initial %} +function buildTriangle(n) { +} + +{% solution %} +function buildTriangle(n) { + var res = []; + for (var row = 0; row < n; row++) { + res.push([]); + for (var col = 0; col < row+1; col++) { + res[row].push("*"); + } + } + return res; +} + +{% validation %} +assert(buildTriangle(1).length === 1, "Fail for buildTriangle(1)"); +assert(buildTriangle(5).length === 5, "Fail for buildTriangle(5)"); +assert(buildTriangle(5) && buildTriangle(5)[3].length === 4, "Fail for buildTriangle(5)"); +assert(buildTriangle(5) && buildTriangle(5)[3][3] === "*", "Fail for buildTriangle(5)"); + +{% endexercise %} + + + + + + + + diff --git a/functions/higher_order.md b/functions/higher_order.md index 66984ad9..d5c6a0f1 100644 --- a/functions/higher_order.md +++ b/functions/higher_order.md @@ -1,4 +1,4 @@ -# Higher Order Functions +# Higher Order (Advanced) 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. diff --git a/loops/dowhile.md b/loops/dowhile.md deleted file mode 100644 index ad3e9fe7..00000000 --- a/loops/dowhile.md +++ /dev/null @@ -1,35 +0,0 @@ -# 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 - -```javascript -do{ - // statement -} -while(expression) ; -``` - -Lets for example see how to print numbers less than 10 using `do...while` loop: - -``` -var i = 0; -do { - document.write(i + " "); - i++; // incrementing i by 1 -} while (i < 10); -``` - ->***Note***: `i = i + 1` can be written `i++`. - - -{% exercise %} -Using a do...while-loop, print numbers between less than 5. -{% initial %} -var i = 0; -{% solution %} -var i = 0; -do { - i++; // incrementing i by 1 -} while (i < 5); -{% endexercise %} diff --git a/objects/delete.md b/objects/delete.md deleted file mode 100644 index b4b5cf1b..00000000 --- a/objects/delete.md +++ /dev/null @@ -1,14 +0,0 @@ -# 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; - -delete child.age; - /* 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. -``` diff --git a/objects/enumeration.md b/objects/enumeration.md deleted file mode 100644 index 2e4c49dd..00000000 --- a/objects/enumeration.md +++ /dev/null @@ -1,20 +0,0 @@ -# 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')+ - ', '; -} - // 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 deleted file mode 100644 index 86de8075..00000000 --- a/objects/global_footprint.md +++ /dev/null @@ -1,18 +0,0 @@ -# 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; - } -} -``` -> ***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 deleted file mode 100644 index c5ead5f8..00000000 --- a/objects/mutable.md +++ /dev/null @@ -1,10 +0,0 @@ -# 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. -``` diff --git a/objects/prototype.md b/objects/prototype.md deleted file mode 100644 index 43bb815a..00000000 --- a/objects/prototype.md +++ /dev/null @@ -1,43 +0,0 @@ -# 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 -``` -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]' -``` - -`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; -} -``` -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. - -To set your own object as a prototype instead of the default Object.prototype, you can invoke `Object.create` as follows: - -```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. */ -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. - 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" */ -``` - -`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..bfb8e3e6 100644 --- a/objects/reference.md +++ b/objects/reference.md @@ -1,20 +1,21 @@ -# Reference +# Reference (Advanced) + +The difference between objects and primitive values is that **we can change objects**, whereas primitive values are immutable. + 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 -var yourPizza = myPizza; - // 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 -a = b = c = {}; - // a, b, and c all refer to - // the same empty object +var myPrimitive1 = "first value"; +var myPrimitive2 = myPrimitive1; +myPrimitive2 = "second value"; + +var myObject1 = { key: "first value"}; +var myObject2 = myObject1; +myObject2.key = "second value"; + +// myPrimitive1 = "first value" +// myPrimitive2 = "second value" +// myObject1 = { key: "second value"} +// myObject2 = { key: "second value"} ``` diff --git a/summary/README.md b/summary/README.md new file mode 100644 index 00000000..32a0d915 --- /dev/null +++ b/summary/README.md @@ -0,0 +1,110 @@ +# Summary + +## Basics +```javascript +var float = 3.1416; +var integer = 42; +var boolean = true; +var n = null; +``` + +## Numbers +```javascript +var x = 0; // = 0 +x = x + 10; // = 10 +x += 5; // = 15 +x++; // = 16 +``` + +## Strings +```javascript +var firstname = "John"; +var lastname = "Doe"; +var fullname = firstname + " " + lastname; // = "John Doe" +var size = fullname.length; // = 8 +``` + +## Conditional Logic +```javascript +if(country === 'England') { + // ... +} else if(country === 'France') { + // ... +} else if(country === 'Germany') { + // ... +} else { + // ... +} + +// AND +if(x > 10 && x < 20) { + // ... +} + +// OR +if(x < 10 || x > 20) { + // ... +} +``` + + + + +## Arrays +```javascript +// Creation +var cars = ["Mazda", "Tesla", "Chevy", "Ford"]; + +// Access +var myCar = cars[1]; // = "Tesla" + +// Length +let nb = cars.length; // = 4 + +// Add a new element +cars.push("Peugeot"); // = ["Mazda", "Tesla", "Chevy", "Ford", "Peugeot"] + +// Sort +cars.sort(); // = ["Chevy", "Ford", "Mazda", "Peugeot", "Tesla"] +``` + +## Loops +```javascript +// For i from 0 to 10 excluded and incremented by 1 +for(var i = 0; i < 10; i++){ + // do this code ten-times +} + +while(condition){ + // do it as long as condition is true +} +``` + +## Functions +```javascript +function myFunctionName(param1, param2, param3) { + return param1 + param2 + param3; +} +``` + +## Objects +```javascript +var myEmptyObject = {}; + +var language = { + name: 'JavaScript', + isSupportedByBrowsers: true, + createdIn: 1995, + author:{ + firstName: 'Brendan', + lastName: 'Eich' + }, + getAuthorFullName: function(){ + return this.author.firstName + " " + this.author.lastName; + } +}; +language.name; // = "JavaScript" +language["name"]; // = "JavaScript" +language.author.lastName; // = "Eich" +language.getAuthorFullName(); // = "Brendan Eich" +``` \ No newline at end of file