From bc018ef95da7270ce6f2d9d1da78ff745e5b1bae Mon Sep 17 00:00:00 2001 From: Nigel Yong <23243585+niyonx@users.noreply.github.com> Date: Fri, 25 Oct 2019 02:43:50 -0400 Subject: [PATCH 01/93] No need to install docsify-cli globally Remove global flag --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a6ea53d..4b476e6 100644 --- a/README.md +++ b/README.md @@ -15,9 +15,9 @@ $ npm run lint:fix This repository uses [Docsify](https://docsify.js.org) for generating documentation website on the fly. **Steps:** -1. Install `docsify-cli` globally. +1. Install `docsify-cli` ``` - npm i docsify-cli -g + npm i docsify-cli ``` 2. Then run the following command to serve the documentation. ``` From bc3f9561d0471a347bdd062e92a220c58fce62f5 Mon Sep 17 00:00:00 2001 From: ITGrusha Date: Fri, 25 Oct 2019 19:57:51 +0300 Subject: [PATCH 02/93] High Order Functions tutorial Added basic information about high order functuions --- .../higher_order_functions.md | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/docs/JavaScript_Basics/higher_order_functions.md b/docs/JavaScript_Basics/higher_order_functions.md index 8768c4a..84e605a 100644 --- a/docs/JavaScript_Basics/higher_order_functions.md +++ b/docs/JavaScript_Basics/higher_order_functions.md @@ -1 +1,26 @@ -# Higher Order Functions \ No newline at end of file +# Higher Order Functions + +Higher-order functions are functions that take other functions as arguments or return functions as their results. + +Taking an other function as an argument is often referred as a callback function, because it is called back by the higher-order function. This is a concept that Javascript uses a lot. + +For example, the map function on arrays is a higher order function. The map function takes a function as an argument. + +```javascript +const list = [1, 2, 3, 4, 5 ]; +const double = n => n * 2 + +[1, 2, 3, 4].map(double) // [ 2, 4, 6, 8, 10 ] +``` + + +Or, with an anonymous function: +```javascript +const newList = list.map(function (item, index, list) { + return item * 2; +}); +// [ 2, 4, 6, 8, 10 ] +``` +The map function is one of the many higher-order functions built into the language. sort, reduce, filter, forEach are other examples of higher-order functions built into the language. + +Higher-order functions allows you to write simpler and more elegant code. From 7572f24835ff5785d57efe1e56a80a8f51e1e6cb Mon Sep 17 00:00:00 2001 From: Yuriy Degtyar Date: Fri, 25 Oct 2019 21:38:52 +0300 Subject: [PATCH 03/93] replace variable declarations with var to modern let and const --- JavaScript_Advance/callback.js | 2 +- JavaScript_Advance/cookies.js | 2 +- JavaScript_Advance/do_while_loop.js | 2 +- JavaScript_Advance/while_loop.js | 2 +- JavaScript_Basics/arrays.js | 10 +++++----- JavaScript_Basics/bugs.js | 4 ++-- JavaScript_Basics/exercise_1_using_arrays.js | 2 +- JavaScript_Basics/filter.js | 2 +- JavaScript_Basics/iife.js | 2 +- JavaScript_Basics/map.js | 2 +- JavaScript_Basics/reduce.js | 9 ++++----- JavaScript_Basics/strict_mode.js | 10 +++++----- JavaScript_Basics/this.js | 4 ++-- 13 files changed, 26 insertions(+), 27 deletions(-) diff --git a/JavaScript_Advance/callback.js b/JavaScript_Advance/callback.js index e2dec33..c428a93 100644 --- a/JavaScript_Advance/callback.js +++ b/JavaScript_Advance/callback.js @@ -62,7 +62,7 @@ transformNumber(10, (num) => { * passed to the `resolve()` function, will get passed to the function passed to `.then()` * function. Look at the following example from MDN official documents: */ -var p1 = new Promise((resolve, reject) => { +const p1 = new Promise((resolve, reject) => { resolve("Success!"); // or // reject(new Error("Error!")); diff --git a/JavaScript_Advance/cookies.js b/JavaScript_Advance/cookies.js index 17c3a63..708f235 100644 --- a/JavaScript_Advance/cookies.js +++ b/JavaScript_Advance/cookies.js @@ -6,7 +6,7 @@ console.log("Simple usage:" + document.cookie); // #2 Get a cookie with the name 'actor' document.cookie = "movie=Jungle Book"; document.cookie = "actor=Balu"; -var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)actor\s*\=\s*([^;]*).*$)|^.*$/, "$1"); +const cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)actor\s*\=\s*([^;]*).*$)|^.*$/, "$1"); console.log("Cookie with the name 'actor':" + cookieValue); // #3 Set cookie and execute code only once if cookie doesn't exist yet diff --git a/JavaScript_Advance/do_while_loop.js b/JavaScript_Advance/do_while_loop.js index fe4a8b9..ca82206 100644 --- a/JavaScript_Advance/do_while_loop.js +++ b/JavaScript_Advance/do_while_loop.js @@ -10,7 +10,7 @@ do { */ -var n = 1; +let n = 1; do { console.log("n is less than 6. n = " + n); diff --git a/JavaScript_Advance/while_loop.js b/JavaScript_Advance/while_loop.js index ac99790..c6f461f 100644 --- a/JavaScript_Advance/while_loop.js +++ b/JavaScript_Advance/while_loop.js @@ -10,7 +10,7 @@ */ -var n = 1; +let n = 1; while (n < 6) { console.log("n is less than 6. n = " + n); diff --git a/JavaScript_Basics/arrays.js b/JavaScript_Basics/arrays.js index 05cc3fb..1657417 100644 --- a/JavaScript_Basics/arrays.js +++ b/JavaScript_Basics/arrays.js @@ -27,26 +27,26 @@ console.log(easyMethod); // Output [ 'Swapnil Satish Shinde', 76, true ] // The pop() method removes the last element from an array: -var fruits = ["Banana", "Orange", "Apple", "Mango"]; +const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.pop(); // Removes the last element ("Mango") from fruits and output is ["Banana","Orange","Apple"] // Shifting is equivalent to popping, working on the first element instead of the last. // The shift() method removes the first array element and "shifts" all other elements to a lower index. -var cars = ["Acura", "Audi", "Bugatti", "Honda"]; +const cars = ["Acura", "Audi", "Bugatti", "Honda"]; cars.shift(); // Removes the first element ("Acura") from cars and output is ["Audi","Bugatti","Honda"] // The length property provides an easy way to append a new element to an array: -var mobiles = ["Apple", "Nokia", "Samsung", "Sony"]; +const mobiles = ["Apple", "Nokia", "Samsung", "Sony"]; mobiles[mobiles.length] = "HTC"; // Appends "HTC" to mobiles and output is ["Apple", "Nokia", "Samsung", "Sony", "HTC"] // delete will delete the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined: -var myArray = ["a", "b", "c", "d"]; +const myArray = ["a", "b", "c", "d"]; delete myArray[0]; "The first value is: " + myArray[0]; // The first value is: undefined // Using delete may leave undefined holes in the array. Use pop() or shift() instead. // The splice() method removes items from array and/or adds items to array and returns the removed items: -var names = ["Anne", "Belle", "Chloe", "Diane", "Ella", "Frances"]; +const names = ["Anne", "Belle", "Chloe", "Diane", "Ella", "Frances"]; names.splice(4, 1); // This removes 1 item from index 4 // returns "Ella" diff --git a/JavaScript_Basics/bugs.js b/JavaScript_Basics/bugs.js index 18da994..2a428c2 100644 --- a/JavaScript_Basics/bugs.js +++ b/JavaScript_Basics/bugs.js @@ -1,8 +1,8 @@ -var obj = { +const obj = { name: "Some name" }; -var name = null; +const name = null; console.log(typeof obj); // object; console.log(typeof name); // object; \ No newline at end of file diff --git a/JavaScript_Basics/exercise_1_using_arrays.js b/JavaScript_Basics/exercise_1_using_arrays.js index 99d8c9e..f7788fd 100644 --- a/JavaScript_Basics/exercise_1_using_arrays.js +++ b/JavaScript_Basics/exercise_1_using_arrays.js @@ -1,4 +1,4 @@ -var array = [1, 0.16, "Random", function () { +const array = [1, 0.16, "Random", function () { console.log("this is function in an array"); }, { Key: "Answer" }, false]; diff --git a/JavaScript_Basics/filter.js b/JavaScript_Basics/filter.js index 9bdb4e8..166f18b 100644 --- a/JavaScript_Basics/filter.js +++ b/JavaScript_Basics/filter.js @@ -21,5 +21,5 @@ function isBigEnough (value) { return value >= 10; } -var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); +const filtered = [12, 5, 8, 130, 44].filter(isBigEnough); // filtered is [12, 130, 44] \ No newline at end of file diff --git a/JavaScript_Basics/iife.js b/JavaScript_Basics/iife.js index c9fcb7d..c8a01fd 100644 --- a/JavaScript_Basics/iife.js +++ b/JavaScript_Basics/iife.js @@ -7,6 +7,6 @@ Can be used as shown below:-- */ (function (value) { - var modified = value + 4; + const modified = value + 4; console.log(modified); }(3)); \ No newline at end of file diff --git a/JavaScript_Basics/map.js b/JavaScript_Basics/map.js index 8c933cb..fcdfb83 100644 --- a/JavaScript_Basics/map.js +++ b/JavaScript_Basics/map.js @@ -1,5 +1,5 @@ // Let's create an array of numbers that we want to get the square of each number in the array -var numbers = [1, 2, 3, 4, 5]; +const numbers = [1, 2, 3, 4, 5]; // pass a function to map const square = numbers.map(function (num) { diff --git a/JavaScript_Basics/reduce.js b/JavaScript_Basics/reduce.js index 84ca2b8..702f4b5 100644 --- a/JavaScript_Basics/reduce.js +++ b/JavaScript_Basics/reduce.js @@ -5,11 +5,10 @@ the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator. */ -var pokemon = ["squirtle", "charmander", "bulbasaur"]; +const pokemon = ["squirtle", "charmander", "bulbasaur"]; -var pokeLength = - pokemon.reduce(function (previous, current) { - return previous + current.length; - }, 0); +const pokeLength = pokemon.reduce(function (previous, current) { + return previous + current.length; +}, 0); // Outputs 27 \ No newline at end of file diff --git a/JavaScript_Basics/strict_mode.js b/JavaScript_Basics/strict_mode.js index ad1b060..8eca404 100644 --- a/JavaScript_Basics/strict_mode.js +++ b/JavaScript_Basics/strict_mode.js @@ -2,20 +2,20 @@ // examples taken from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode // Assignment to a non-writable global -var undefined = 5; // throws a TypeError -var Infinity = 5; // throws a TypeError +const undefined = 5; // throws a TypeError +const Infinity = 5; // throws a TypeError // Assignment to a non-writable property -var obj1 = {}; +const obj1 = {}; Object.defineProperty(obj1, "x", { value: 42, writable: false }); obj1.x = 9; // throws a TypeError // Assignment to a getter-only property -var obj2 = { get x () { return 17; } }; +const obj2 = { get x () { return 17; } }; obj2.x = 5; // throws a TypeError // Assignment to a new property on a non-extensible object -var fixed = {}; +const fixed = {}; Object.preventExtensions(fixed); fixed.newProp = "ohai"; // throws a TypeError diff --git a/JavaScript_Basics/this.js b/JavaScript_Basics/this.js index 208ed19..edd549c 100644 --- a/JavaScript_Basics/this.js +++ b/JavaScript_Basics/this.js @@ -1,7 +1,7 @@ console.log(this); // This gives empty object // Output {} -var aa = 1; +const aa = 1; console.log(global.aa); // Global scope is accessible to every where // Output undefined @@ -19,7 +19,7 @@ console.log(a); // console.log(b) // Output ReferenceError: b is not defined as b is defined using let it is going to be declared only in that block const help = () => { - var a = 4; + const a = 4; const b = 2; // variables defined by let and const are accessible to there scope only console.log(a); // This will not get printed unless and until function is called }; From 585692630db40e38ae7257c66b1e3ce2c5c97288 Mon Sep 17 00:00:00 2001 From: Swap76 Date: Sat, 26 Oct 2019 00:58:00 +0530 Subject: [PATCH 04/93] Minor changes --- docs/JavaScript_Advance/bind.md | 15 ++++++++------- docs/JavaScript_Advance/callback.md | 2 +- docs/JavaScript_Advance/express.md | 9 +-------- docs/JavaScript_Advance/map_object.md | 3 +-- docs/JavaScript_Advance/set_function.md | 2 ++ 5 files changed, 13 insertions(+), 18 deletions(-) diff --git a/docs/JavaScript_Advance/bind.md b/docs/JavaScript_Advance/bind.md index 8d69a83..1ac863c 100644 --- a/docs/JavaScript_Advance/bind.md +++ b/docs/JavaScript_Advance/bind.md @@ -1,6 +1,6 @@ - +### Bind Method *The **bind()** method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.* - +```js let module = { x: 42, getX: function() { @@ -11,11 +11,12 @@ let unboundGetX = module.getX; console.log(unboundGetX()); +``` +The above function gets invoked at the global scope -> The above function gets invoked at the global scope -> expected output: undefined - +output: undefined +```js let boundGetX = unboundGetX.bind(module); console.log(boundGetX()); - -> expected output: 42 +``` +output: 42 diff --git a/docs/JavaScript_Advance/callback.md b/docs/JavaScript_Advance/callback.md index c180f11..f64944f 100644 --- a/docs/JavaScript_Advance/callback.md +++ b/docs/JavaScript_Advance/callback.md @@ -1,4 +1,4 @@ - +### Callback Functions Callback functions are derived from a programming paradigm called `functional programming`. This basically can be concluded to this sentence: You can pass (`closure`) functions as an argument to another function. diff --git a/docs/JavaScript_Advance/express.md b/docs/JavaScript_Advance/express.md index a42433f..b0655c1 100644 --- a/docs/JavaScript_Advance/express.md +++ b/docs/JavaScript_Advance/express.md @@ -1,8 +1 @@ -#### install -```sh -npm i -``` -#### run -```sh -node ./JavaScript_Advance/express.js -``` \ No newline at end of file +# Express \ No newline at end of file diff --git a/docs/JavaScript_Advance/map_object.md b/docs/JavaScript_Advance/map_object.md index 70203a8..0d04c90 100644 --- a/docs/JavaScript_Advance/map_object.md +++ b/docs/JavaScript_Advance/map_object.md @@ -1,6 +1,5 @@ +# Map Objects - -**Map : Object** *Maps allow associating keys and values similar to normal Objects except Maps allow any Object to be used as a key instead of just Strings and Symbols. Maps use get() and set() methods to access the values stored in the Map. A Map are often called a HashTable or a Dictionary in other languages.* diff --git a/docs/JavaScript_Advance/set_function.md b/docs/JavaScript_Advance/set_function.md index 0e5cb1e..f7eabad 100644 --- a/docs/JavaScript_Advance/set_function.md +++ b/docs/JavaScript_Advance/set_function.md @@ -1,3 +1,5 @@ +# Set Function + In JavaScript, a setter can be used to execute a function whenever a specified property is attempted to be changed. Setters are most often used in conjunction with getters to create a type of pseudo-property. From 480cbcc35ed8aee670015a42e4ce04fe1724bf81 Mon Sep 17 00:00:00 2001 From: Swapnil Satish Shinde <37082605+Swap76@users.noreply.github.com> Date: Sat, 26 Oct 2019 01:11:21 +0530 Subject: [PATCH 05/93] Update map_object.js --- JavaScript_Advance/map_object.js | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/JavaScript_Advance/map_object.js b/JavaScript_Advance/map_object.js index 7219d42..9494adb 100644 --- a/JavaScript_Advance/map_object.js +++ b/JavaScript_Advance/map_object.js @@ -5,7 +5,7 @@ key instead of just Strings and Symbols. Maps use get() and set() methods to acc A Map are often called a HashTable or a Dictionary in other languages. */ -const map = new Map(); +let map = new Map(); map.set("1", "str1"); // a string key map.set(1, "num1"); // a numeric key @@ -20,12 +20,12 @@ alert(map.size); // 3 // Map can also use objects as keys. -const john = { +let john = { name: "John" }; // for every user, let's store their visits count -const visitsCountMap = new Map(); +let visitsCountMap = new Map(); // john is the key for the map visitsCountMap.set(john, 123); @@ -40,23 +40,23 @@ map.values() – returns an iterable for values, map.entries() */ -const recipeMap = new Map([ +let recipeMap = new Map([ ["cucumber", 500], ["tomatoes", 350], ["onion", 50] ]); // iterate over keys (vegetables) -for (const vegetable of recipeMap.keys()) { +for (let vegetable of recipeMap.keys()) { alert(vegetable); // cucumber, tomatoes, onion } // iterate over values (amounts) -for (const amount of recipeMap.values()) { +for (let amount of recipeMap.values()) { alert(amount); // 500, 350, 50 } // iterate over [key, value] entries -for (const entry of recipeMap) { // the same as of recipeMap.entries() +for (let entry of recipeMap) { // the same as of recipeMap.entries() alert(entry); // cucumber,500 (and so on) -} \ No newline at end of file +} From d15a6373586a1dedb56f2121a81dbeee6759b000 Mon Sep 17 00:00:00 2001 From: Swapnil Satish Shinde <37082605+Swap76@users.noreply.github.com> Date: Sat, 26 Oct 2019 01:14:19 +0530 Subject: [PATCH 06/93] Update set_object.js --- JavaScript_Advance/set_object.js | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/JavaScript_Advance/set_object.js b/JavaScript_Advance/set_object.js index a513294..bacecfd 100644 --- a/JavaScript_Advance/set_object.js +++ b/JavaScript_Advance/set_object.js @@ -15,14 +15,14 @@ testSet.clear(); // testSet [] // Iterating Sets -const iterSet = new Set([1, "blue", 125, "right"]); +let iterSet = new Set([1, "blue", 125, "right"]); // Using for..of -for (const item of iterSet) console.log(item); // output: 1, "blue", 125, "right" -for (const item of iterSet.keys()) console.log(item); // same output -for (const item of iterSet.values()) console.log(item); // same output -for (const item of iterSet.entries()) console.log(item); // output: [1, 1], ["blue", "blue"], ...etc +for (let item of iterSet) console.log(item); // output: 1, "blue", 125, "right" +for (let item of iterSet.keys()) console.log(item); // same output +for (let item of iterSet.values()) console.log(item); // same output +for (let item of iterSet.entries()) console.log(item); // output: [1, 1], ["blue", "blue"], ...etc // Using for..each @@ -30,28 +30,28 @@ iterSet.forEach(value => console.log(value)); // output: 1, "blue", 125, "right" // Creating a Set from an Array -const array = [1, 2, 3, "Alehop"]; -const arrToSet = new Set(array); +let array = [1, 2, 3, "Alehop"]; +let arrToSet = new Set(array); console.log(arrToSet); // output: [1, 2, 3, "Alehop"] // Deleting duplicated elements in an Array using Set and spread operator -const dupArray = [1, 2, 2, "yes", "no", "yes", 69, 420]; -const notDupArray = [...new Set(dupArray)]; +let dupArray = [1, 2, 2, "yes", "no", "yes", 69, 420]; +let notDupArray = [...new Set(dupArray)]; console.log(notDupArray); // output: [1, 2, "yes", "no", 69, 420] // Creating a Set form an String -const text = "Nice"; -const strToSet = new Set(text); +let text = "Nice"; +let strToSet = new Set(text); console.log(strToSet); // output: ["N", "i", "c", "e"] // Deleting duplicated letters in a string -const dupText = "Niceeee"; -const notDupText = [...new Set(dupText)].join(""); +let dupText = "Niceeee"; +let notDupText = [...new Set(dupText)].join(""); -console.log(notDupText); // output: "Nice" \ No newline at end of file +console.log(notDupText); // output: "Nice" From 46fe6452d04800cf0f3bdaebfc1583714dfcc1d4 Mon Sep 17 00:00:00 2001 From: Swapnil Satish Shinde <37082605+Swap76@users.noreply.github.com> Date: Sat, 26 Oct 2019 01:16:20 +0530 Subject: [PATCH 07/93] Update continue_break.js --- JavaScript_Basics/continue_break.js | 34 ++++++++++++++--------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/JavaScript_Basics/continue_break.js b/JavaScript_Basics/continue_break.js index b186c6f..c0ea6f1 100644 --- a/JavaScript_Basics/continue_break.js +++ b/JavaScript_Basics/continue_break.js @@ -13,24 +13,24 @@ while (helloWorld.length > 0) { const color = "red"; switch (color) { -case "red": -case "yellow": -case "blue": - console.log(color + " is a primary color"); - break; -case "green": -case "purple": -case "orange": - console.log(color + " is a secondary color"); - break; -default: - console.log("Sorry, I don't know this color..."); - break; + case "red": + case "yellow": + case "blue": + console.log(color + " is a primary color"); + break; + case "green": + case "purple": + case "orange": + console.log(color + " is a secondary color"); + break; + default: + console.log("Sorry, I don't know this color..."); + break; } // Will output: *'red is a primary color'*. -const array = [1, 2, 3, 4, 5]; -const array2 = []; +let array = [1, 2, 3, 4, 5]; +let array2 = []; firstFor: for (let i = 0; i < array.length; i++) { for (let j = 0; j < array.length; j++) { if (array[i] * array[j] > 5) { break firstFor; } @@ -50,7 +50,7 @@ for (let i = 0; i < 5; i++) { console.log(result1); // Will output: *0124*, the digit `3` is ommited because of the continue statement. -const result2 = []; +let result2 = []; firstFor: for (let i = 0; i < 5; i++) { let numbers = ""; for (let j = 0; j < 2; j++) { @@ -60,4 +60,4 @@ firstFor: for (let i = 0; i < 5; i++) { result2.push(numbers.trim()); } console.log(result2); -// Will output: *'["0 1", "1 2", "2 3", "4 5"]'* with 'continue firstFor' and *'["0 1", "1 2", "2 3", "", "4 5"]'* with a simple continue statement. \ No newline at end of file +// Will output: *'["0 1", "1 2", "2 3", "4 5"]'* with 'continue firstFor' and *'["0 1", "1 2", "2 3", "", "4 5"]'* with a simple continue statement. From 7c9fab316f78c44bf4a6f4b6f7afd42a603889ce Mon Sep 17 00:00:00 2001 From: Swapnil Satish Shinde <37082605+Swap76@users.noreply.github.com> Date: Sat, 26 Oct 2019 01:19:48 +0530 Subject: [PATCH 08/93] Update switch_case.js --- JavaScript_Basics/switch_case.js | 142 +++++++++++++++---------------- 1 file changed, 71 insertions(+), 71 deletions(-) diff --git a/JavaScript_Basics/switch_case.js b/JavaScript_Basics/switch_case.js index dc188bc..be9439a 100644 --- a/JavaScript_Basics/switch_case.js +++ b/JavaScript_Basics/switch_case.js @@ -12,14 +12,14 @@ Syntax; switch (expression) { -case x: - // code block - break; -case y: - // code block - break; -default: + case x: // code block + break; + case y: + // code block + break; + default: + // code block } // This is how it works: @@ -35,26 +35,26 @@ default: // This example uses the weekday number to calculate the weekday name: switch (new Date().getDay()) { -case 0: - day = "Sunday"; - break; -case 1: - day = "Monday"; - break; -case 2: - day = "Tuesday"; - break; -case 3: - day = "Wednesday"; - break; -case 4: - day = "Thursday"; - break; -case 5: - day = "Friday"; - break; -case 6: - day = "Saturday"; + case 0: + day = "Sunday"; + break; + case 1: + day = "Monday"; + break; + case 2: + day = "Tuesday"; + break; + case 3: + day = "Wednesday"; + break; + case 4: + day = "Thursday"; + break; + case 5: + day = "Friday"; + break; + case 6: + day = "Saturday"; } /** @@ -81,14 +81,14 @@ case 6: // If today is neither Saturday (6) nor Sunday (0), write a default message: switch (new Date().getDay()) { -case 6: - text = "Today is Saturday"; - break; -case 0: - text = "Today is Sunday"; - break; -default: - text = "Looking forward to the Weekend"; + case 6: + text = "Today is Saturday"; + break; + case 0: + text = "Today is Sunday"; + break; + default: + text = "Looking forward to the Weekend"; } // The result of text will be: @@ -99,15 +99,15 @@ default: // Example switch (new Date().getDay()) { -default: - text = "Looking forward to the Weekend"; - break; -case 6: - text = "Today is Saturday"; - break; -case 0: - text = "Today is Sunday"; -} + default: + text = "Looking forward to the Weekend"; + break; + case 6: + text = "Today is Saturday"; + break; + case 0: + text = "Today is Sunday"; + } // If default is not the last case in the switch block, remember to end the default case with a break. @@ -119,16 +119,16 @@ case 0: // Example switch (new Date().getDay()) { -case 4: -case 5: - text = "Soon it is Weekend"; - break; -case 0: -case 6: - text = "It is Weekend"; - break; -default: - text = "Looking forward to the Weekend"; + case 4: + case 5: + text = "Soon it is Weekend"; + break; + case 0: + case 6: + text = "It is Weekend"; + break; + default: + text = "Looking forward to the Weekend"; } // Switching Details @@ -147,17 +147,17 @@ default: // In this example there will be no match for x: -Example; +Example: var x = "0"; switch (x) { -case 0: - text = "Off"; - break; -case 1: - text = "On"; - break; -default: - text = "No value found"; + case 0: + text = "Off"; + break; + case 1: + text = "On"; + break; + default: + text = "No value found"; } /** Exercise for You Complete it */ @@ -165,11 +165,11 @@ default: // Create a switch statement that will alert "Hello" if fruits is "banana", and "Welcome" if fruits is "apple". switch (fruits) { -case "Banana": - alert("Hello"); - break; - -case "Apple": - alert("Welcome"); - break; -} \ No newline at end of file + case "Banana": + alert("Hello"); + break; + + case "Apple": + alert("Welcome"); + break; +} From d6e2d2a552e06f7adefff4ced4870499afa24c44 Mon Sep 17 00:00:00 2001 From: Swapnil Satish Shinde <37082605+Swap76@users.noreply.github.com> Date: Sat, 26 Oct 2019 01:20:32 +0530 Subject: [PATCH 09/93] Update variables.js --- JavaScript_Basics/variables.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/JavaScript_Basics/variables.js b/JavaScript_Basics/variables.js index 49c335b..75d80a1 100644 --- a/JavaScript_Basics/variables.js +++ b/JavaScript_Basics/variables.js @@ -1,7 +1,7 @@ // There is only 3 types of variables in javascript -const a = "Swapnil"; // New type introduced in ES6. Value of let can change any time. +let a = "Swapnil"; // New type introduced in ES6. Value of let can change any time. const pi = 3.14;// New type introduced in ES6. Value of pi now cannot be changed as this is defined as const. -var b = 26;// This is Deprecated as this creates many problems in future. \ No newline at end of file +var b = 26;// This is Deprecated as this creates many problems in future. From 1287bfdb6c9ad6a18bc6b3302f887e91860767bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=96mer=20F=2E=20=C3=87?= Date: Fri, 25 Oct 2019 22:52:13 +0300 Subject: [PATCH 10/93] Update arrow_function.md --- docs/JavaScript_Advance/arrow_function.md | 24 ++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/docs/JavaScript_Advance/arrow_function.md b/docs/JavaScript_Advance/arrow_function.md index 91c9ac4..355c3b9 100644 --- a/docs/JavaScript_Advance/arrow_function.md +++ b/docs/JavaScript_Advance/arrow_function.md @@ -1 +1,23 @@ -# Arrow Function +# Arrow Function +An arrow function expression is a syntactically compact alternative to a regular function expression. + +Example: +```javascript +// Regular function +function greet(name){ + console.log("Hello " + name); +} + +// Arrow function equivalent +const greet = name => { + console.log("Hello " + name) +} +``` +Both functions above are equivalent to each other. + +If we have more than one function argument then we should put them in paranthesis like this: +```javascript +const exampleFunc = (name,age,eyeColor) => { + // ... +} +``` From 90937a385a7c2a7aa59aa2237ead71d1fbbe7f6c Mon Sep 17 00:00:00 2001 From: merkur0 Date: Fri, 25 Oct 2019 21:59:25 +0200 Subject: [PATCH 11/93] Add documentation for Array.prototype.some() --- docs/JavaScript_Basics/some.md | 49 ++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 docs/JavaScript_Basics/some.md diff --git a/docs/JavaScript_Basics/some.md b/docs/JavaScript_Basics/some.md new file mode 100644 index 0000000..81cc05a --- /dev/null +++ b/docs/JavaScript_Basics/some.md @@ -0,0 +1,49 @@ +# Array.prototype.some() + +This method returns true if at least one element in the array passes the test in the provided function. + +**Note:** This method returns false if used on an empty array. + +The `some` method will iterate over the elements in the given array until it finds an element that, when provided as an argument to the callback function, returns a truthy value (a value that, when converted to Boolean, becomes `true`). +When that happens, the method stops and returns false. +If none of the elements in the given array pass the test, this method returns false. + +The callback function can take up to three arguments: +The value of the current element, it's index (optional), and the array object being traversed (optional). + +## Example + +The following code tests two differents arrays of numbers to see if any of the numbers is bigger than 10. + + +```js +function isBiggerThan10(element) { + return element > 10; +} + +[2, 5, 8, 1, 4].some(isBiggerThan10); // returns false +[12, 5, 8, 1, 4].some(isBiggerThan10); // returns true +``` +The above can also be written like this: + +```js +[2, 5, 8, 1, 4].some(function(element) { + return element > 10; +}); // returns false + +[12, 5, 8, 1, 4].some(function(element) { + return element > 10; +}); // returns true +``` + +Or with an arrow function: + +```js +[2, 5, 8, 1, 4].some((element) => { + return element > 10; +}); // returns false + +[12, 5, 8, 1, 4].some((element) => { + return element > 10; +}); // returns true +``` \ No newline at end of file From 9001c59422f61f0fff39d703c328073b6f9fd444 Mon Sep 17 00:00:00 2001 From: Nigel Yong <23243585+niyonx@users.noreply.github.com> Date: Fri, 25 Oct 2019 16:37:27 -0400 Subject: [PATCH 12/93] Updated Step 1 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4b476e6..081769f 100644 --- a/README.md +++ b/README.md @@ -15,9 +15,9 @@ $ npm run lint:fix This repository uses [Docsify](https://docsify.js.org) for generating documentation website on the fly. **Steps:** -1. Install `docsify-cli` +1. Install dependencies ``` - npm i docsify-cli + npm install ``` 2. Then run the following command to serve the documentation. ``` From b0b0d8581de67b7aa6febda22d58fc917d864533 Mon Sep 17 00:00:00 2001 From: homerli Date: Fri, 25 Oct 2019 14:22:38 -0700 Subject: [PATCH 13/93] new code added --- JavaScript_Advance/arrow_function.js | 27 ++++++++++++++++++--------- JavaScript_Advance/event_loop.js | 12 +++++++++++- JavaScript_Advance/filtering_array.js | 17 ++++++++++++++++- JavaScript_Advance/hoisting.js | 9 ++++++++- JavaScript_Advance/promises.js | 25 +++++++++++++++++++++++-- JavaScript_Advance/while_loop.js | 7 ++++++- 6 files changed, 82 insertions(+), 15 deletions(-) diff --git a/JavaScript_Advance/arrow_function.js b/JavaScript_Advance/arrow_function.js index e63098f..cde4bf6 100644 --- a/JavaScript_Advance/arrow_function.js +++ b/JavaScript_Advance/arrow_function.js @@ -6,7 +6,7 @@ let info = { firstName: "Swapnil", lastName: "Shinde", getFullName: () => { - return(`My name is ${this.firstName} ${this.lastName}`); // Arrow functions don't have "this" property + return (`My name is ${this.firstName} ${this.lastName}`); // Arrow functions don't have "this" property } } @@ -17,7 +17,7 @@ let newInfo = { firstName: "Swapnil", lastName: "Shinde", getFullName: () => { - return(`My name is ${newInfo.firstName} ${newInfo.lastName}`); // If we are using arrow function then directly use the variables as shown + return (`My name is ${newInfo.firstName} ${newInfo.lastName}`); // If we are using arrow function then directly use the variables as shown } } @@ -39,24 +39,33 @@ console.log((new Student).getName()) // Gives error for node versions before 12. class StudentInfo { - constructor (firstName,lastName, age, branch, college){ - this.firstName = firstName; + constructor(firstName, lastName, age, branch, college) { + this.firstName = firstName; this.lastName = lastName; - this.age = age; + this.age = age; this.branch = branch; this.college = college; }; getFullName = () => { // Returns full name using string interpolation - return(`My name is ${this.firstName} ${this.lastName}`); // If we are using arrow function then directly use the variables as shown + return (`My name is ${this.firstName} ${this.lastName}`); // If we are using arrow function then directly use the variables as shown }; getBranch = () => { // Returns Branch - return(this.branch); + return (this.branch); }; } -let Swapnil = new StudentInfo("Swapnil", "Shinde",19, "Computer", "Sies"); // This way we can create new objects with arguments +let Swapnil = new StudentInfo("Swapnil", "Shinde", 19, "Computer", "Sies"); // This way we can create new objects with arguments -console.log(Swapnil.getFullName()); // Output My name is Swapnil Shinde \ No newline at end of file +console.log(Swapnil.getFullName()); // Output My name is Swapnil Shinde + +//settimeout with arrow function +setTimeout(function () { + console.log("hello world"); +}, 1000); +//another example of settimeout with arrow function +setTimeout(() => { + console.log("hello world"); +}, 0); diff --git a/JavaScript_Advance/event_loop.js b/JavaScript_Advance/event_loop.js index 99e4a14..26dcfac 100644 --- a/JavaScript_Advance/event_loop.js +++ b/JavaScript_Advance/event_loop.js @@ -4,4 +4,14 @@ setTimeout(() => { console.log("Last statement"); // This statement gets printed first -// This enables the non blocking using event based management \ No newline at end of file +// This enables the non blocking using event based management + +console.log("a"); +setTimeout(() => { + console.log("b") +}, 2000); +console.log("c"); +setTimeout(() => { + console.log("d"); +}, 0) +//except answer : a , c , d , b \ No newline at end of file diff --git a/JavaScript_Advance/filtering_array.js b/JavaScript_Advance/filtering_array.js index 08a1bf4..b33a6ba 100644 --- a/JavaScript_Advance/filtering_array.js +++ b/JavaScript_Advance/filtering_array.js @@ -2,4 +2,19 @@ const animals = ["cats", "dogs", "bunnies", "birds"]; const start_with_b = animals.filter(name => name.indexOf("b") === 0); -console.log(start_with_b); // ['bunnies', 'birds'] \ No newline at end of file +console.log(start_with_b); // ['bunnies', 'birds'] + +//function of filter (basic callback for filter) +const arr = [1, 3, 42, 2, 4, 5]; +function filter(array, callback) { + let callback_list = []; + for (let i of array) { + callback_list.push(callback(i)); + } + return callback_list; +} +//modifyable callback function +function callback(num) { + return Math.pow(num, 2); +} +console.log(filter(arr, callback)); diff --git a/JavaScript_Advance/hoisting.js b/JavaScript_Advance/hoisting.js index 1ac7ebf..eb6f91a 100644 --- a/JavaScript_Advance/hoisting.js +++ b/JavaScript_Advance/hoisting.js @@ -23,4 +23,11 @@ elem.innerHTML = x; // Display x in the element /* Conclusion :Example 1 gives the same result as Example 2 so, Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function) -*/ \ No newline at end of file +*/ + +console.log(foo); +let foo = 'foo'; //unable to print due to the hoisting behaviour + +console.log(ok); +var ok = 'this is printing'//var is hoisted + diff --git a/JavaScript_Advance/promises.js b/JavaScript_Advance/promises.js index 9fcb2c9..e3dc8f2 100644 --- a/JavaScript_Advance/promises.js +++ b/JavaScript_Advance/promises.js @@ -40,7 +40,7 @@ getAsyncDataWithPromises() .then(data => { // ... use data }).catch(e => { - // ... handle exception + // ... handle exception }); // promises promise the nodejs main thread that i'm going to come after doing a particular task @@ -77,4 +77,25 @@ asyncCall // appended with ' bar' to become 'foo bar' .then(val => `${val} bar`) // console logs 'foo bar' - .then(console.log); \ No newline at end of file + .then(console.log); + +//promise.all();\ +const fs = require('fs'); +const dir = __dirname + '/text/'; +var promisesarray = ["Text file content start after this : "]; +function readfile() { + fs.readdir(dir, 'utf-8', (err, File) => { + File.forEach(file => { + promisesarray.push(new Promise((resolve, reject) => { + fs.readFile(dir + file, 'utf-8', (err, data) => { + if (err) reject(err); + else resolve(data); + }); + })); + }); + Promise.all(promisesarray).then(data => { + console.log(data); + }) + }); +} +readfile(); \ No newline at end of file diff --git a/JavaScript_Advance/while_loop.js b/JavaScript_Advance/while_loop.js index ac99790..eaa757c 100644 --- a/JavaScript_Advance/while_loop.js +++ b/JavaScript_Advance/while_loop.js @@ -15,4 +15,9 @@ var n = 1; while (n < 6) { console.log("n is less than 6. n = " + n); n++; -} \ No newline at end of file +} + +var sum = 1; +do { + console.log(`sum now is ${sum++}`); +} while (sum <= 100); From 3865ebaacc8774842ba366fcb734e4f270c003a1 Mon Sep 17 00:00:00 2001 From: arthursvpb Date: Sat, 26 Oct 2019 00:45:20 -0300 Subject: [PATCH 14/93] adding basic javascript exercise --- docs/Exercise/JavaScript_Basics/Exercise-2.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 docs/Exercise/JavaScript_Basics/Exercise-2.md diff --git a/docs/Exercise/JavaScript_Basics/Exercise-2.md b/docs/Exercise/JavaScript_Basics/Exercise-2.md new file mode 100644 index 0000000..41bd50e --- /dev/null +++ b/docs/Exercise/JavaScript_Basics/Exercise-2.md @@ -0,0 +1,5 @@ +1. **Write** a JavaScript program to get the `current date`. + +*Expected Output*: + +**mm-dd-yyyy**, **mm/dd/yyyy** or **dd-mm-yyyy**, **dd/mm/yyyy** From 8a14e392d1d3adbeeb299109b98365958746edd4 Mon Sep 17 00:00:00 2001 From: Dinanath Date: Sat, 26 Oct 2019 14:48:18 +1100 Subject: [PATCH 15/93] Added content to prototype advanced content Explained basics about prototype and prototypal inheritance in JavaScript with the example provided in the code and additional examples. Some more info can be added in future. --- docs/JavaScript_Advance/prototype.md | 99 +++++++++++++++++++++++++++- 1 file changed, 98 insertions(+), 1 deletion(-) diff --git a/docs/JavaScript_Advance/prototype.md b/docs/JavaScript_Advance/prototype.md index 140ce77..6cf5ce2 100644 --- a/docs/JavaScript_Advance/prototype.md +++ b/docs/JavaScript_Advance/prototype.md @@ -1 +1,98 @@ -# Prototype \ No newline at end of file +# Prototype + +[Prototype-based programming](https://en.wikipedia.org/wiki/Prototype-based_programming) and prototypal inheritance are very important concepts to learn in JavaScript programming language. It is very similar to object-oriented programming model where you can inherit the functions and properties of the parent class. JavaScript did not have class-based inheritance until the introduction of ES6 ([6th Edition - ECMAScript 2015](https://en.wikipedia.org/wiki/ECMAScript#6th_Edition_-_ECMAScript_2015)). Objects in javascript are mutable, so it allows its properties to be modified or reassigned. An important idea about the prototype is the prototype chain. An object or a function initially points to its default prototype. + +Let's look at a basic example. When you create an object `car` using the `{}` notation. In the diagram below, when we created an object, it has by default inherited the methods (behaviors or functions) and properties of the Prototype Object. The magic is happening through `__proto__` property which appeared in the object. We did not add it while creating. It was attached by the prototypal feature of the language. + +![Car object](https://i.imgur.com/XjSv8MP.png) + +Let's see if we can invoke or call those functions against our object which is the `car`. + +```javascript= +// lets create the car object +let car = { + make: 'Audi', + model: 'A8', + wheels: 4 +} + +console.log(car.toString()) +// [out] "[object Object]" + +console.log(car.valueOf()) +// [out] {make: "Audi", model: "A8", wheels: 4} + +``` + +As you can see in the code snippet above, we have not created those functions but they were inherited by the car object from `Object`. What we understand from this is that any object or function can look for values or methods which are defined in `__proto__` + +Let us take another example. This time we will create a constructor function `Person` and attach additional methods to the prototype to add additional features. + +```javascript= +// Prototypes are an extension for objects in javascript +// we use to encapsulate certain functionality to an Object (like a Class) + +// first create an Object Person +// that receive the name and lastName + +function Person (firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +// We user the prototype keyword to add some functionality to this Person Object + +// add a method getName that return the name +Person.prototype.getName = function () { + return this.firstName; +}; + +// add a method getLastName that return the lastName +Person.prototype.getLastName = function () { + return this.lastName; +}; + +// add a method getFullName that return the name + lastName +Person.prototype.getFullName = function () { + return this.firstName + " " + this.lastName; +}; + +// add a method getFormalName +Person.prototype.getFormalName = function () { + return this.lastName + ", " + this.firstName; +}; + +// these methods appear in the __proto__ property +// of an Object instance of Person + +const max = new Person("Max", "Payne"); + +console.log(max.getName()); +// [out] Max + +console.log(max.getLastName()); +// [out] Payne + +console.log(max.getFullName()); +// [out] Max Payne + +console.log(max.getFormalName()); +// [out] Payne, Max +``` + +Now you may be a little confused with the above example. We are introducing another piece to the puzzle, `prototype` property. In the above example, the function `Person` (also known as constructor function as it returns an object) gets to be the prototype of the object `max`. When you add additional functions to the prototype, they apply to the object `max` as well. + +![Object max and its prototype](https://i.imgur.com/JifUNJj.png) + +The diagram above shows that `max` has a `__proto__` which is pointing to the `prototype` of `Person`. Let's see if it matches. + +![](https://i.imgur.com/b9zKCWY.png) + +Looks similar, let us compare. Enter following code in the console (only after you have already executed the Person and max related code snippet above) + +```javascript= +max.__proto__ === Person.prototype +// [out] true +``` + +And guess what? the chain does not end there, `Person.prototype` has a property `__proto__` which now points to `Object`. From 7fdc601de40881abb801d637cf0e53ad530358f2 Mon Sep 17 00:00:00 2001 From: Travis Allen Date: Fri, 25 Oct 2019 22:35:54 -0600 Subject: [PATCH 16/93] Added JavaScript_Advance lesson on recursion --- JavaScript_Advance/recursion.js | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 JavaScript_Advance/recursion.js diff --git a/JavaScript_Advance/recursion.js b/JavaScript_Advance/recursion.js new file mode 100644 index 0000000..7cff8fd --- /dev/null +++ b/JavaScript_Advance/recursion.js @@ -0,0 +1,32 @@ +// Recursion is when a function calls itself. +// Recursion gives us an interesting way to write algorithms that can solve complicated problems. + +// Take for example factorials which is just an integer times each of the integers below it: so 5 factorial (also written 5!) is just 5 * 4 * 3 * 2 * 1. +// If we want to write an algorithm that can calculate the factorial of any given number without using recursion, we could do something like this: + +function calcuateFactorialWithoutRecursion(num) { + let total = num; + let nextNumber = num - 1 + while(nextNumber >= 1) { + total = total * nextNumber; + nextNumber-- // decrease the next number by 1 + } + return total; +} + +// calcuateFactorialWithoutRecursion(5) // 120 +// 5 * 4 * 3 * 2 * 1 = 120 + +// We can write the same function this way using recursion: +function calculateFactorialWithRecursion(num) { + if(num === 1) { // This step is critical. The num parameter will keep decreasing until it gets to 1. + // Once the function gets called with 1 as a parameter, the function will return without calling itself. + return num; + } + return num * calculateFactorialWithRecursion(num - 1); +} + +calculateFactorialWithRecursion(7) // 5040 +// 7 * 6 * 5 * 4 * 3 * 2 * 1 = 5040 + +// See how clean recursion made this algorithm! From d7880a8392435141758ab934e7a4823524030d33 Mon Sep 17 00:00:00 2001 From: Andrew McAuliffe Date: Fri, 25 Oct 2019 23:57:12 -0500 Subject: [PATCH 17/93] Update spread_&_rest.md Update it using code examples from JavaScript_Advance/spread_&_rest.js. --- docs/JavaScript_Advance/spread_&_rest.md | 65 ++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/docs/JavaScript_Advance/spread_&_rest.md b/docs/JavaScript_Advance/spread_&_rest.md index cc776fc..7271f40 100644 --- a/docs/JavaScript_Advance/spread_&_rest.md +++ b/docs/JavaScript_Advance/spread_&_rest.md @@ -1 +1,66 @@ # Spread & Rest +JavaScript version ES6 introduced two new pieces of functionality which utilize the three-dot notation ("..."): the spread operator and the rest parameter. + +## Spread +The spread operator can be used to expand arrays and objects into multiple elements. The following example combines two arrays into one using the spread operator on the original two arrays. Spreading them out into the new array creates that array using all of the elements of the original two arrays. +```javascript +const array1 = [1, 2, 3, 4, 5, 6]; + +const array2 = [6, 7, 8, 9, 10]; + +const combinedArray = [...array1, ...array2]; + +console.log(combinedArray); +/* Output +[ + 1, 2, 3, + 4, 5, 6, + 6, 7, 8, + 9, 10 +] */ +``` +The spread operator can also be used on objects. In the following example, two objects are combined into one new object. +```javascript +const obj1 = { + name: "Swapnil", + branch: "Comps" +}; + +const obj2 = { + age: 19, + college: "SIES" +}; + +const finalObj = { ...obj1, ...obj2 }; + +console.log(finalObj); +/* Output +{ name: 'Swapnil', branch: 'Comps', age: 19, college: 'SIES' } +*/ +``` + +## Rest +The rest parameter is essentially the opposite of the spread operator. While spread allows you to expand a collection into its individual elements, rest allows you to combine elements back into a collection. In the following example, the remaining (or "rest") of the elements in the original array are combined into a new array called *remaining* because they represent the rest of the elements in the *marks* array. +```javascript +const marks = [1, 2, 3, 4, 5, 6, 7, 8, 9]; // Array Declaration + +const [first, second, third, ...remaining] = marks; + +console.log(first, second, third); // Output 1 2 3 + +console.log(remaining); // Output [ 4, 5, 6, 7, 8, 9 ] +``` + +The rest parameter can also be used with objects. In this example, the rest of the elements within the *a* object (aside from the *name* and *age* object properties) are included in the new *unwanted* object. +```javascript +const a = { + name: "Swapnil", + branch: "Comps", + age: 19, + college: "SIES" +}; + +const { name, age, ...unwanted } = a; // Here in unwanted all key and values expect the name and age will come this is different than arrays + +console.log(unwanted); // Output { branch: 'Comps', college: 'SIES' } +``` From 014933f3e5edc3d3cf57f09964682c3e60a417be Mon Sep 17 00:00:00 2001 From: Travis Allen Date: Fri, 25 Oct 2019 23:04:26 -0600 Subject: [PATCH 18/93] added documentation on destructuring --- docs/JavaScript_Advance/destructuring.md | 34 ++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/docs/JavaScript_Advance/destructuring.md b/docs/JavaScript_Advance/destructuring.md index 6c74076..b549bf6 100644 --- a/docs/JavaScript_Advance/destructuring.md +++ b/docs/JavaScript_Advance/destructuring.md @@ -1 +1,35 @@ # Destructuring + +## What is destructuring? + +Destructuring is a quick and clean way to assign a property on an object to a variable made available as part of ES2015 (ES6). Lets say that we have the following object: + +```js +const a = { // Suppose this is the object coming from server then + name: "Swapnil", + age: 19, + college: "SIES" +}; +``` + +If we want to assign the name property of this object to a variable called `name`, we could do this: + +```js +const name = a.name; +``` + +This works just fine until we want to assign each property of its object to it's own variable: + +```js +const name = a.name; +const age = a.age; +const college = a.college; +``` + +This is a bit repetative and now with ES6 destructuring assignment, completely unnecessary. We can now do this: + +```js +const { name, age, college } = a; +``` + +This may look a bit weird, but let's walk through it together. You can see that the open bracket directly follows the `const`, followed by the three different properties that we are assigning to variables by the same name. In essence what we are doing is extracting the value of `name`, `age`, and `college` from the `a` object and assigning those values to `const` variables by the exact same name. \ No newline at end of file From 728df2299db0babc84fb2fba8d75ebeaec701976 Mon Sep 17 00:00:00 2001 From: Swapnil Satish Shinde <37082605+Swap76@users.noreply.github.com> Date: Sat, 26 Oct 2019 11:04:55 +0530 Subject: [PATCH 19/93] Update arrow_function.js --- JavaScript_Advance/arrow_function.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/JavaScript_Advance/arrow_function.js b/JavaScript_Advance/arrow_function.js index cde4bf6..39aea3e 100644 --- a/JavaScript_Advance/arrow_function.js +++ b/JavaScript_Advance/arrow_function.js @@ -61,11 +61,12 @@ let Swapnil = new StudentInfo("Swapnil", "Shinde", 19, "Computer", "Sies"); // T console.log(Swapnil.getFullName()); // Output My name is Swapnil Shinde -//settimeout with arrow function +//settimeout without arrow function setTimeout(function () { console.log("hello world"); }, 1000); -//another example of settimeout with arrow function + +//settimeout with arrow function setTimeout(() => { console.log("hello world"); }, 0); From 25592446758db9f44bc7712a501e5aca1e0636a9 Mon Sep 17 00:00:00 2001 From: Swapnil Satish Shinde <37082605+Swap76@users.noreply.github.com> Date: Sat, 26 Oct 2019 11:09:37 +0530 Subject: [PATCH 20/93] Update prototype.md --- docs/JavaScript_Advance/prototype.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/JavaScript_Advance/prototype.md b/docs/JavaScript_Advance/prototype.md index 6cf5ce2..9a1e6df 100644 --- a/docs/JavaScript_Advance/prototype.md +++ b/docs/JavaScript_Advance/prototype.md @@ -8,7 +8,7 @@ Let's look at a basic example. When you create an object `car` using the `{}` no Let's see if we can invoke or call those functions against our object which is the `car`. -```javascript= +```javascript // lets create the car object let car = { make: 'Audi', @@ -28,7 +28,7 @@ As you can see in the code snippet above, we have not created those functions bu Let us take another example. This time we will create a constructor function `Person` and attach additional methods to the prototype to add additional features. -```javascript= +```javascript // Prototypes are an extension for objects in javascript // we use to encapsulate certain functionality to an Object (like a Class) @@ -90,7 +90,7 @@ The diagram above shows that `max` has a `__proto__` which is pointing to the `p Looks similar, let us compare. Enter following code in the console (only after you have already executed the Person and max related code snippet above) -```javascript= +```javascript max.__proto__ === Person.prototype // [out] true ``` From c90f606e162d8856347eb9984a1754ca372c5290 Mon Sep 17 00:00:00 2001 From: Your Name Date: Sat, 26 Oct 2019 11:41:00 +0530 Subject: [PATCH 21/93] New Commit --- docs/JavaScript_Basics/arrays.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/JavaScript_Basics/arrays.md b/docs/JavaScript_Basics/arrays.md index fc0f050..d8dceb6 100644 --- a/docs/JavaScript_Basics/arrays.md +++ b/docs/JavaScript_Basics/arrays.md @@ -15,3 +15,7 @@ The splice() method removes items from array and/or adds items to array and retu The concat() method returns a new array of two or more arrays joined together. The slice() method returns a new array from a selected range. + +The unshift() method Add elements at the front of an Array. + +The every() function is used when you need to validate each element of a given array. \ No newline at end of file From 3f74c346981b9afe15d6f5ce19f3b60586176be8 Mon Sep 17 00:00:00 2001 From: Your Name Date: Sat, 26 Oct 2019 11:45:43 +0530 Subject: [PATCH 22/93] New Commit --- docs/JavaScript_Basics/objects.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/docs/JavaScript_Basics/objects.md b/docs/JavaScript_Basics/objects.md index 2e79c08..9995c75 100644 --- a/docs/JavaScript_Basics/objects.md +++ b/docs/JavaScript_Basics/objects.md @@ -1 +1,21 @@ # Objects +In JavaScript, almost "everything" is an object. + +-Booleans can be objects (if defined with the new keyword) +-Numbers can be objects (if defined with the new keyword) +-Strings can be objects (if defined with the new keyword) +-Dates are always objects +-Maths are always objects +-Regular expressions are always objects +-Arrays are always objects. +-Functions are always objects +-Objects are always objects + +All JavaScript values, except primitives, are objects. +Objects are variables too. But objects can contain many values. + +The values are written as name : value pairs (name and value separated by a colon). +Example: + +var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; + From de5f420cd17996f29004d3ba121972d7c911e274 Mon Sep 17 00:00:00 2001 From: Swap76 Date: Sat, 26 Oct 2019 11:58:51 +0530 Subject: [PATCH 23/93] Changed names of exercise files --- docs/Exercise/JavaScript_Basics/Exercise-2.md | 5 ----- docs/Exercise/JavaScript_Basics/date.md | 5 +++++ docs/Exercise/JavaScript_Basics/{Exercise-1.md => object.md} | 0 docs/index.html | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) delete mode 100644 docs/Exercise/JavaScript_Basics/Exercise-2.md create mode 100644 docs/Exercise/JavaScript_Basics/date.md rename docs/Exercise/JavaScript_Basics/{Exercise-1.md => object.md} (100%) diff --git a/docs/Exercise/JavaScript_Basics/Exercise-2.md b/docs/Exercise/JavaScript_Basics/Exercise-2.md deleted file mode 100644 index 41bd50e..0000000 --- a/docs/Exercise/JavaScript_Basics/Exercise-2.md +++ /dev/null @@ -1,5 +0,0 @@ -1. **Write** a JavaScript program to get the `current date`. - -*Expected Output*: - -**mm-dd-yyyy**, **mm/dd/yyyy** or **dd-mm-yyyy**, **dd/mm/yyyy** diff --git a/docs/Exercise/JavaScript_Basics/date.md b/docs/Exercise/JavaScript_Basics/date.md new file mode 100644 index 0000000..44d4aa9 --- /dev/null +++ b/docs/Exercise/JavaScript_Basics/date.md @@ -0,0 +1,5 @@ +**Write** a JavaScript program to get the `current date`. + +**Expected Output**: + +**mm-dd-yyyy**, **mm/dd/yyyy** or **dd-mm-yyyy**, **dd/mm/yyyy** diff --git a/docs/Exercise/JavaScript_Basics/Exercise-1.md b/docs/Exercise/JavaScript_Basics/object.md similarity index 100% rename from docs/Exercise/JavaScript_Basics/Exercise-1.md rename to docs/Exercise/JavaScript_Basics/object.md diff --git a/docs/index.html b/docs/index.html index cb1dc3a..b65146d 100644 --- a/docs/index.html +++ b/docs/index.html @@ -24,4 +24,4 @@ - + \ No newline at end of file From a1f3214efc5c1fb54744a9bf4ffd9d36a5f3977c Mon Sep 17 00:00:00 2001 From: Swap76 Date: Sat, 26 Oct 2019 12:35:40 +0530 Subject: [PATCH 24/93] Files moved to appropriate locations --- JavaScript_Advance/event_loop.js | 6 +- JavaScript_Advance/hoisting.js | 5 +- JavaScript_Advance/promises.js | 14 +- JavaScript_Advance/recursion.js | 18 +-- JavaScript_Advance/while_loop.js | 2 +- JavaScript_Basics/continue_break.js | 34 ++--- JavaScript_Basics/date.js | 5 +- JavaScript_Basics/switch_case.js | 140 +++++++++--------- .../browser_object_model.md | 0 .../JavaScript_Advance}/do_while_loop.md | 3 +- .../dom_manipulation_html.md | 0 .../JavaScript_Advance}/while_loop.md | 0 .../JavaScript_Basics}/number_methods.md | 0 scripts/build-sidebar.js | 51 ++++--- 14 files changed, 137 insertions(+), 141 deletions(-) rename {JavaScript_Advance => docs/JavaScript_Advance}/browser_object_model.md (100%) rename {JavaScript_Advance => docs/JavaScript_Advance}/do_while_loop.md (86%) rename {JavaScript_Advance => docs/JavaScript_Advance}/dom_manipulation_html.md (100%) rename {JavaScript_Advance => docs/JavaScript_Advance}/while_loop.md (100%) rename {JavaScript_Basics => docs/JavaScript_Basics}/number_methods.md (100%) diff --git a/JavaScript_Advance/event_loop.js b/JavaScript_Advance/event_loop.js index 26dcfac..c507359 100644 --- a/JavaScript_Advance/event_loop.js +++ b/JavaScript_Advance/event_loop.js @@ -8,10 +8,10 @@ console.log("Last statement"); // This statement gets printed first console.log("a"); setTimeout(() => { - console.log("b") + console.log("b"); }, 2000); console.log("c"); setTimeout(() => { console.log("d"); -}, 0) -//except answer : a , c , d , b \ No newline at end of file +}, 0); +// except answer : a , c , d , b \ No newline at end of file diff --git a/JavaScript_Advance/hoisting.js b/JavaScript_Advance/hoisting.js index eb6f91a..b2a6c78 100644 --- a/JavaScript_Advance/hoisting.js +++ b/JavaScript_Advance/hoisting.js @@ -26,8 +26,7 @@ so, Hoisting is JavaScript's default behavior of moving all declarations to the */ console.log(foo); -let foo = 'foo'; //unable to print due to the hoisting behaviour +const foo = "foo"; // unable to print due to the hoisting behaviour console.log(ok); -var ok = 'this is printing'//var is hoisted - +var ok = "this is printing";// var is hoisted \ No newline at end of file diff --git a/JavaScript_Advance/promises.js b/JavaScript_Advance/promises.js index e3dc8f2..24adc73 100644 --- a/JavaScript_Advance/promises.js +++ b/JavaScript_Advance/promises.js @@ -79,15 +79,15 @@ asyncCall // console logs 'foo bar' .then(console.log); -//promise.all();\ -const fs = require('fs'); -const dir = __dirname + '/text/'; +// promise.all();\ +const fs = require("fs"); +const dir = __dirname + "/text/"; var promisesarray = ["Text file content start after this : "]; -function readfile() { - fs.readdir(dir, 'utf-8', (err, File) => { +function readfile () { + fs.readdir(dir, "utf-8", (err, File) => { File.forEach(file => { promisesarray.push(new Promise((resolve, reject) => { - fs.readFile(dir + file, 'utf-8', (err, data) => { + fs.readFile(dir + file, "utf-8", (err, data) => { if (err) reject(err); else resolve(data); }); @@ -95,7 +95,7 @@ function readfile() { }); Promise.all(promisesarray).then(data => { console.log(data); - }) + }); }); } readfile(); \ No newline at end of file diff --git a/JavaScript_Advance/recursion.js b/JavaScript_Advance/recursion.js index 7cff8fd..cd82f7f 100644 --- a/JavaScript_Advance/recursion.js +++ b/JavaScript_Advance/recursion.js @@ -4,12 +4,12 @@ // Take for example factorials which is just an integer times each of the integers below it: so 5 factorial (also written 5!) is just 5 * 4 * 3 * 2 * 1. // If we want to write an algorithm that can calculate the factorial of any given number without using recursion, we could do something like this: -function calcuateFactorialWithoutRecursion(num) { +function calcuateFactorialWithoutRecursion (num) { let total = num; - let nextNumber = num - 1 - while(nextNumber >= 1) { - total = total * nextNumber; - nextNumber-- // decrease the next number by 1 + let nextNumber = num - 1; + while (nextNumber >= 1) { + total = total * nextNumber; + nextNumber--; // decrease the next number by 1 } return total; } @@ -18,15 +18,15 @@ function calcuateFactorialWithoutRecursion(num) { // 5 * 4 * 3 * 2 * 1 = 120 // We can write the same function this way using recursion: -function calculateFactorialWithRecursion(num) { - if(num === 1) { // This step is critical. The num parameter will keep decreasing until it gets to 1. +function calculateFactorialWithRecursion (num) { + if (num === 1) { // This step is critical. The num parameter will keep decreasing until it gets to 1. // Once the function gets called with 1 as a parameter, the function will return without calling itself. return num; } return num * calculateFactorialWithRecursion(num - 1); } -calculateFactorialWithRecursion(7) // 5040 +calculateFactorialWithRecursion(7); // 5040 // 7 * 6 * 5 * 4 * 3 * 2 * 1 = 5040 -// See how clean recursion made this algorithm! +// See how clean recursion made this algorithm! \ No newline at end of file diff --git a/JavaScript_Advance/while_loop.js b/JavaScript_Advance/while_loop.js index 6597754..feaa084 100644 --- a/JavaScript_Advance/while_loop.js +++ b/JavaScript_Advance/while_loop.js @@ -20,4 +20,4 @@ while (n < 6) { var sum = 1; do { console.log(`sum now is ${sum++}`); -} while (sum <= 100); +} while (sum <= 100); \ No newline at end of file diff --git a/JavaScript_Basics/continue_break.js b/JavaScript_Basics/continue_break.js index c0ea6f1..b186c6f 100644 --- a/JavaScript_Basics/continue_break.js +++ b/JavaScript_Basics/continue_break.js @@ -13,24 +13,24 @@ while (helloWorld.length > 0) { const color = "red"; switch (color) { - case "red": - case "yellow": - case "blue": - console.log(color + " is a primary color"); - break; - case "green": - case "purple": - case "orange": - console.log(color + " is a secondary color"); - break; - default: - console.log("Sorry, I don't know this color..."); - break; +case "red": +case "yellow": +case "blue": + console.log(color + " is a primary color"); + break; +case "green": +case "purple": +case "orange": + console.log(color + " is a secondary color"); + break; +default: + console.log("Sorry, I don't know this color..."); + break; } // Will output: *'red is a primary color'*. -let array = [1, 2, 3, 4, 5]; -let array2 = []; +const array = [1, 2, 3, 4, 5]; +const array2 = []; firstFor: for (let i = 0; i < array.length; i++) { for (let j = 0; j < array.length; j++) { if (array[i] * array[j] > 5) { break firstFor; } @@ -50,7 +50,7 @@ for (let i = 0; i < 5; i++) { console.log(result1); // Will output: *0124*, the digit `3` is ommited because of the continue statement. -let result2 = []; +const result2 = []; firstFor: for (let i = 0; i < 5; i++) { let numbers = ""; for (let j = 0; j < 2; j++) { @@ -60,4 +60,4 @@ firstFor: for (let i = 0; i < 5; i++) { result2.push(numbers.trim()); } console.log(result2); -// Will output: *'["0 1", "1 2", "2 3", "4 5"]'* with 'continue firstFor' and *'["0 1", "1 2", "2 3", "", "4 5"]'* with a simple continue statement. +// Will output: *'["0 1", "1 2", "2 3", "4 5"]'* with 'continue firstFor' and *'["0 1", "1 2", "2 3", "", "4 5"]'* with a simple continue statement. \ No newline at end of file diff --git a/JavaScript_Basics/date.js b/JavaScript_Basics/date.js index 063ea87..fcb0ad9 100644 --- a/JavaScript_Basics/date.js +++ b/JavaScript_Basics/date.js @@ -6,7 +6,7 @@ console.log(date); // current time and date in your local time zone // Create a date object const dateWithYear = new Date(2019, 10, 10, 22, 10, 0); // takes year, month, date, hour, minute, second, millisecond as arguments -console.log(dateWithYear); //OUtput : Sun Nov 10 2019 22:10:00 GMT+0530 +console.log(dateWithYear); // Output : Sun Nov 10 2019 22:10:00 GMT+0530 const dateString = new Date("October 10, 2019 11:13:00"); console.log(dateString); // Output : creates a new date object from date string @@ -30,11 +30,10 @@ date.getMonth(); // 9 (month of a date as a number (0-11)) date.getTime(); // 1570726799950 (the number of milliseconds since midnight Jan 1 1970, and a specified date) - // Manipulate a date date.setFullYear(2020, 10, 3); // Set the date to November 3, 2020 date.setMonth(4); // Set the month to 4 (May) -date.setTime(1332403882588); // Thu Mar 22 2012 13:41:22 GMT+0530 +date.setTime(1332403882588); // Thu Mar 22 2012 13:41:22 GMT+0530 \ No newline at end of file diff --git a/JavaScript_Basics/switch_case.js b/JavaScript_Basics/switch_case.js index be9439a..b7f045e 100644 --- a/JavaScript_Basics/switch_case.js +++ b/JavaScript_Basics/switch_case.js @@ -12,13 +12,13 @@ Syntax; switch (expression) { - case x: - // code block - break; - case y: - // code block - break; - default: +case x: + // code block + break; +case y: + // code block + break; +default: // code block } @@ -35,26 +35,26 @@ switch (expression) { // This example uses the weekday number to calculate the weekday name: switch (new Date().getDay()) { - case 0: - day = "Sunday"; - break; - case 1: - day = "Monday"; - break; - case 2: - day = "Tuesday"; - break; - case 3: - day = "Wednesday"; - break; - case 4: - day = "Thursday"; - break; - case 5: - day = "Friday"; - break; - case 6: - day = "Saturday"; +case 0: + day = "Sunday"; + break; +case 1: + day = "Monday"; + break; +case 2: + day = "Tuesday"; + break; +case 3: + day = "Wednesday"; + break; +case 4: + day = "Thursday"; + break; +case 5: + day = "Friday"; + break; +case 6: + day = "Saturday"; } /** @@ -81,14 +81,14 @@ switch (new Date().getDay()) { // If today is neither Saturday (6) nor Sunday (0), write a default message: switch (new Date().getDay()) { - case 6: - text = "Today is Saturday"; - break; - case 0: - text = "Today is Sunday"; - break; - default: - text = "Looking forward to the Weekend"; +case 6: + text = "Today is Saturday"; + break; +case 0: + text = "Today is Sunday"; + break; +default: + text = "Looking forward to the Weekend"; } // The result of text will be: @@ -99,15 +99,15 @@ switch (new Date().getDay()) { // Example switch (new Date().getDay()) { - default: - text = "Looking forward to the Weekend"; - break; - case 6: - text = "Today is Saturday"; - break; - case 0: - text = "Today is Sunday"; - } +default: + text = "Looking forward to the Weekend"; + break; +case 6: + text = "Today is Saturday"; + break; +case 0: + text = "Today is Sunday"; +} // If default is not the last case in the switch block, remember to end the default case with a break. @@ -119,16 +119,16 @@ switch (new Date().getDay()) { // Example switch (new Date().getDay()) { - case 4: - case 5: - text = "Soon it is Weekend"; - break; - case 0: - case 6: - text = "It is Weekend"; - break; - default: - text = "Looking forward to the Weekend"; +case 4: +case 5: + text = "Soon it is Weekend"; + break; +case 0: +case 6: + text = "It is Weekend"; + break; +default: + text = "Looking forward to the Weekend"; } // Switching Details @@ -150,14 +150,14 @@ switch (new Date().getDay()) { Example: var x = "0"; switch (x) { - case 0: - text = "Off"; - break; - case 1: - text = "On"; - break; - default: - text = "No value found"; +case 0: + text = "Off"; + break; +case 1: + text = "On"; + break; +default: + text = "No value found"; } /** Exercise for You Complete it */ @@ -165,11 +165,11 @@ switch (x) { // Create a switch statement that will alert "Hello" if fruits is "banana", and "Welcome" if fruits is "apple". switch (fruits) { - case "Banana": - alert("Hello"); - break; - - case "Apple": - alert("Welcome"); - break; -} +case "Banana": + alert("Hello"); + break; + +case "Apple": + alert("Welcome"); + break; +} \ No newline at end of file diff --git a/JavaScript_Advance/browser_object_model.md b/docs/JavaScript_Advance/browser_object_model.md similarity index 100% rename from JavaScript_Advance/browser_object_model.md rename to docs/JavaScript_Advance/browser_object_model.md diff --git a/JavaScript_Advance/do_while_loop.md b/docs/JavaScript_Advance/do_while_loop.md similarity index 86% rename from JavaScript_Advance/do_while_loop.md rename to docs/JavaScript_Advance/do_while_loop.md index ceca9a4..69aaae2 100644 --- a/JavaScript_Advance/do_while_loop.md +++ b/docs/JavaScript_Advance/do_while_loop.md @@ -7,5 +7,4 @@ do { statement - } while (condition) - +} while (condition) \ No newline at end of file diff --git a/JavaScript_Advance/dom_manipulation_html.md b/docs/JavaScript_Advance/dom_manipulation_html.md similarity index 100% rename from JavaScript_Advance/dom_manipulation_html.md rename to docs/JavaScript_Advance/dom_manipulation_html.md diff --git a/JavaScript_Advance/while_loop.md b/docs/JavaScript_Advance/while_loop.md similarity index 100% rename from JavaScript_Advance/while_loop.md rename to docs/JavaScript_Advance/while_loop.md diff --git a/JavaScript_Basics/number_methods.md b/docs/JavaScript_Basics/number_methods.md similarity index 100% rename from JavaScript_Basics/number_methods.md rename to docs/JavaScript_Basics/number_methods.md diff --git a/scripts/build-sidebar.js b/scripts/build-sidebar.js index f56e275..62728d3 100644 --- a/scripts/build-sidebar.js +++ b/scripts/build-sidebar.js @@ -1,45 +1,44 @@ -const fs = require('fs'); +const fs = require("fs"); -const documentationFolder = 'docs'; +const documentationFolder = "docs"; -async function getFiles(directory) { - const files = []; - const dir = fs.opendirSync(directory); +async function getFiles (directory) { + const files = []; + const dir = fs.opendirSync(directory); - for await (const dirent of dir) { - files.push(dirent.name); - } + for await (const dirent of dir) { + files.push(dirent.name); + } - return files.sort(); + return files.sort(); } -function filenameToTitle(filename) { - return filename.split('.').shift().replace(/_/g, ' '); +function filenameToTitle (filename) { + return filename.split(".").shift().replace(/_/g, " "); } -async function buildSection(directory) { - const files = await getFiles(`${documentationFolder}/${directory}`); - const title = filenameToTitle(directory); - const content = [ `- ${title}` ]; +async function buildSection (directory) { + const files = await getFiles(`${documentationFolder}/${directory}`); + const title = filenameToTitle(directory); + const content = [`- ${title}`]; - for (let file of files) { - content.push(`\t- [${filenameToTitle(file)}](${directory}/${file})`); - } + for (const file of files) { + content.push(`\t- [${filenameToTitle(file)}](${directory}/${file})`); + } - return content.join('\n'); + return content.join("\n"); } -async function buildSidebar(watchEventType) { - if (watchEventType == 'change') - return; +async function buildSidebar (watchEventType) { + if (watchEventType == "change") { return; } - console.log('Building _sidebar.md'); - const content = await buildSection('JavaScript_Basics') + '\n' + await buildSection('JavaScript_Advance'); + console.log("Building _sidebar.md"); + const content = await buildSection("JavaScript_Basics") + "\n" + await buildSection("JavaScript_Advance"); - fs.writeFileSync(`${documentationFolder}/_sidebar.md`, content); + fs.writeFileSync(`${documentationFolder}/_sidebar.md`, content); } fs.watch(`${documentationFolder}/JavaScript_Basics`, buildSidebar); fs.watch(`${documentationFolder}/JavaScript_Advance`, buildSidebar); -buildSidebar(); +buildSidebar(); \ No newline at end of file From 77d8e021b9c222f5a79e637a4209cd3b02c2559a Mon Sep 17 00:00:00 2001 From: Swap76 Date: Sat, 26 Oct 2019 12:48:44 +0530 Subject: [PATCH 25/93] Added rule of no-var in eslint --- .eslintrc.js | 3 ++- JavaScript_Advance/filtering_array.js | 22 ++++++++++----------- JavaScript_Advance/map_object.js | 16 +++++++-------- JavaScript_Advance/promises.js | 2 +- JavaScript_Advance/set_object.js | 28 +++++++++++++-------------- JavaScript_Advance/while_loop.js | 2 +- JavaScript_Basics/variables.js | 6 +++++- 7 files changed, 42 insertions(+), 37 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index f18fd69..a2d7ce0 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -6,6 +6,7 @@ module.exports = { "quotes": ["error", "double"], "semi": ["error", "always"], "eol-last": ["error", "never"], - "no-multiple-empty-lines": ["error", { max: 1 }] + "no-multiple-empty-lines": ["error", { max: 1 }], + "no-var": ["error"] } }; diff --git a/JavaScript_Advance/filtering_array.js b/JavaScript_Advance/filtering_array.js index b33a6ba..0a5bff8 100644 --- a/JavaScript_Advance/filtering_array.js +++ b/JavaScript_Advance/filtering_array.js @@ -4,17 +4,17 @@ const start_with_b = animals.filter(name => name.indexOf("b") === 0); console.log(start_with_b); // ['bunnies', 'birds'] -//function of filter (basic callback for filter) +// function of filter (basic callback for filter) const arr = [1, 3, 42, 2, 4, 5]; -function filter(array, callback) { - let callback_list = []; - for (let i of array) { - callback_list.push(callback(i)); - } - return callback_list; +function filter (array, callback) { + const callback_list = []; + for (const i of array) { + callback_list.push(callback(i)); + } + return callback_list; } -//modifyable callback function -function callback(num) { - return Math.pow(num, 2); +// modifyable callback function +function callback (num) { + return Math.pow(num, 2); } -console.log(filter(arr, callback)); +console.log(filter(arr, callback)); \ No newline at end of file diff --git a/JavaScript_Advance/map_object.js b/JavaScript_Advance/map_object.js index 9494adb..7219d42 100644 --- a/JavaScript_Advance/map_object.js +++ b/JavaScript_Advance/map_object.js @@ -5,7 +5,7 @@ key instead of just Strings and Symbols. Maps use get() and set() methods to acc A Map are often called a HashTable or a Dictionary in other languages. */ -let map = new Map(); +const map = new Map(); map.set("1", "str1"); // a string key map.set(1, "num1"); // a numeric key @@ -20,12 +20,12 @@ alert(map.size); // 3 // Map can also use objects as keys. -let john = { +const john = { name: "John" }; // for every user, let's store their visits count -let visitsCountMap = new Map(); +const visitsCountMap = new Map(); // john is the key for the map visitsCountMap.set(john, 123); @@ -40,23 +40,23 @@ map.values() – returns an iterable for values, map.entries() */ -let recipeMap = new Map([ +const recipeMap = new Map([ ["cucumber", 500], ["tomatoes", 350], ["onion", 50] ]); // iterate over keys (vegetables) -for (let vegetable of recipeMap.keys()) { +for (const vegetable of recipeMap.keys()) { alert(vegetable); // cucumber, tomatoes, onion } // iterate over values (amounts) -for (let amount of recipeMap.values()) { +for (const amount of recipeMap.values()) { alert(amount); // 500, 350, 50 } // iterate over [key, value] entries -for (let entry of recipeMap) { // the same as of recipeMap.entries() +for (const entry of recipeMap) { // the same as of recipeMap.entries() alert(entry); // cucumber,500 (and so on) -} +} \ No newline at end of file diff --git a/JavaScript_Advance/promises.js b/JavaScript_Advance/promises.js index 24adc73..d2af04b 100644 --- a/JavaScript_Advance/promises.js +++ b/JavaScript_Advance/promises.js @@ -82,7 +82,7 @@ asyncCall // promise.all();\ const fs = require("fs"); const dir = __dirname + "/text/"; -var promisesarray = ["Text file content start after this : "]; +const promisesarray = ["Text file content start after this : "]; function readfile () { fs.readdir(dir, "utf-8", (err, File) => { File.forEach(file => { diff --git a/JavaScript_Advance/set_object.js b/JavaScript_Advance/set_object.js index bacecfd..a513294 100644 --- a/JavaScript_Advance/set_object.js +++ b/JavaScript_Advance/set_object.js @@ -15,14 +15,14 @@ testSet.clear(); // testSet [] // Iterating Sets -let iterSet = new Set([1, "blue", 125, "right"]); +const iterSet = new Set([1, "blue", 125, "right"]); // Using for..of -for (let item of iterSet) console.log(item); // output: 1, "blue", 125, "right" -for (let item of iterSet.keys()) console.log(item); // same output -for (let item of iterSet.values()) console.log(item); // same output -for (let item of iterSet.entries()) console.log(item); // output: [1, 1], ["blue", "blue"], ...etc +for (const item of iterSet) console.log(item); // output: 1, "blue", 125, "right" +for (const item of iterSet.keys()) console.log(item); // same output +for (const item of iterSet.values()) console.log(item); // same output +for (const item of iterSet.entries()) console.log(item); // output: [1, 1], ["blue", "blue"], ...etc // Using for..each @@ -30,28 +30,28 @@ iterSet.forEach(value => console.log(value)); // output: 1, "blue", 125, "right" // Creating a Set from an Array -let array = [1, 2, 3, "Alehop"]; -let arrToSet = new Set(array); +const array = [1, 2, 3, "Alehop"]; +const arrToSet = new Set(array); console.log(arrToSet); // output: [1, 2, 3, "Alehop"] // Deleting duplicated elements in an Array using Set and spread operator -let dupArray = [1, 2, 2, "yes", "no", "yes", 69, 420]; -let notDupArray = [...new Set(dupArray)]; +const dupArray = [1, 2, 2, "yes", "no", "yes", 69, 420]; +const notDupArray = [...new Set(dupArray)]; console.log(notDupArray); // output: [1, 2, "yes", "no", 69, 420] // Creating a Set form an String -let text = "Nice"; -let strToSet = new Set(text); +const text = "Nice"; +const strToSet = new Set(text); console.log(strToSet); // output: ["N", "i", "c", "e"] // Deleting duplicated letters in a string -let dupText = "Niceeee"; -let notDupText = [...new Set(dupText)].join(""); +const dupText = "Niceeee"; +const notDupText = [...new Set(dupText)].join(""); -console.log(notDupText); // output: "Nice" +console.log(notDupText); // output: "Nice" \ No newline at end of file diff --git a/JavaScript_Advance/while_loop.js b/JavaScript_Advance/while_loop.js index feaa084..c9f8e5b 100644 --- a/JavaScript_Advance/while_loop.js +++ b/JavaScript_Advance/while_loop.js @@ -17,7 +17,7 @@ while (n < 6) { n++; } -var sum = 1; +let sum = 1; do { console.log(`sum now is ${sum++}`); } while (sum <= 100); \ No newline at end of file diff --git a/JavaScript_Basics/variables.js b/JavaScript_Basics/variables.js index 75d80a1..5dcee3f 100644 --- a/JavaScript_Basics/variables.js +++ b/JavaScript_Basics/variables.js @@ -1,7 +1,11 @@ +/* eslint no-var: "off" */ + // There is only 3 types of variables in javascript let a = "Swapnil"; // New type introduced in ES6. Value of let can change any time. +a = "Swap76"; + const pi = 3.14;// New type introduced in ES6. Value of pi now cannot be changed as this is defined as const. -var b = 26;// This is Deprecated as this creates many problems in future. +var b = 26;// This is Deprecated as this creates many problems in future. \ No newline at end of file From 4f80f43f51284f55df0db17680081b27c7b76094 Mon Sep 17 00:00:00 2001 From: frahmadani Date: Sat, 26 Oct 2019 15:25:58 +0700 Subject: [PATCH 26/93] Add info on FS Module - Issue #206 --- docs/JavaScript_Advance/fs_module.md | 56 +++++++++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/docs/JavaScript_Advance/fs_module.md b/docs/JavaScript_Advance/fs_module.md index 21adac6..efa69df 100644 --- a/docs/JavaScript_Advance/fs_module.md +++ b/docs/JavaScript_Advance/fs_module.md @@ -1 +1,55 @@ -# fs Module +# FS Module +FS is an inbuilt module in NodeJS used to perform operations on files and directories. There are two ways to do an FS operation: synchronous and asynchronous. The FS library sends event data continuously using NodeJS EventEmitter. + +To use FS module, first import it with the following syntax. +```js +const fs = require("fs"); +``` +To read from a file, web can use `createReadStream()` method. +```js +const content = fs.createReadStream("./resources/file/order.txt"); +``` +If we don't set the encoding type, the data will be printed out in the form of buffer. +``` + +``` +Set the encoding to use UTF-8. +```js +content.setEncoding("UTF8); +``` +Because the response object in this case is also a stream, we can listen to events happening on the file. +For example, here we are listening to the event when our file is successfully opened. +```js +content.on("open", () => { + console.log("File opened for reading"); +}); +``` +We can also listen to an event called `data` that will be called when data is present. +```fs +content.on("data", (data) => { + console.log(data); +}); +``` +We can also listen to the event when a file is closed. +```fs +content.on("close", () => { + console.log("File ends"); +}); +``` + +Working with above example, reading the `./resources/file/order.txt` file will results in the following ouput. + +``` +File opened for reading +arrowFunction +destructuring +spread and rest +timerFunction +eventloop + +promises +fsModule +File ends +``` + +In conclusion, createReadStream is similar to a publish-subscribe system where our stream is the subscriber and the file is the publisher, and as such can be implemented using MQTT. \ No newline at end of file From 77161509554a815892c8a78933c9dc0bb63f653e Mon Sep 17 00:00:00 2001 From: vlastik Date: Sat, 26 Oct 2019 01:31:07 -0700 Subject: [PATCH 27/93] Closes #194; Update splice_slice readme doc --- docs/JavaScript_Basics/splice_slice.md | 63 +++++++++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) diff --git a/docs/JavaScript_Basics/splice_slice.md b/docs/JavaScript_Basics/splice_slice.md index 9c356d1..f935f1d 100644 --- a/docs/JavaScript_Basics/splice_slice.md +++ b/docs/JavaScript_Basics/splice_slice.md @@ -1 +1,62 @@ -# Splice and Slice \ No newline at end of file +# Splice and Slice + +## Splice + + Splice is used to add and delete new elements at a specific index in an array. + +#### Example 1: Adding an element at specific index + +```javascript +let languages = ["C++", "Java", "Javascript", "R"]; +languages.splice(2, 0, "Python", "Pearl"); + ``` +This will add Python and Perl starting at index 2. +As of result we get an output of `["C++", "Java", "Python", "Pearl", "Javascript", "R"]` + +**NOTE**
+First argument denotes the Index of Array while second denotes +the number of elements we want to delete from the array. + +#### Example 2: Deleting and Adding an element at specific index + +```javascript +let languages = ["C++", "Java", "Javascript", "R"]; +languages.splice(2, 1, "Python", "Pearl"); + ``` + This will add Python and Perl starting at index 2 and delete one element which was at index 2 originally. + As of result we get an output of `["C++", "Java", "Python", "Pearl", "R"]` + + #### Example 3: Deleting an element at a specific index + +```javascript +let languages = ["C++", "Java", "Javascript", "R"]; +languages.splice(1, 1); + ``` +This will delete one element at index 1. +As of result we get an output of `["C++", "Javascript", "R"]` + +## Slice + +Slice is used to return a selected number of elements from an array depending on their index + +#### Example 1: Specifying index 1 and 2 as the arguments + +```javascript +let languages = ["C++", "Java", "Javascript", "R"]; +let coding = languages.slice(1, 2); + ``` + This will return elements from an array starting at index 1 and ending at index 2. As of result we get an output of `["Java", "Javascript"]` + + #### Example 2: Specifying index -3 and -1 as the arguments +```javascript +let languages = ["C++", "Java", "Javascript", "R"]; +let coding = languages.slice(-3, -1); + ``` + Since negative numbers are being used. We indicate an offset from the end of the sequence. The elements returned from the array starts at index -3 and ends at index -1. As of result we get an output of `["Java", "Javascript"]` + +**Explanation**
+``` + index-> 0 1 2 3 + ["C++", "Java", "Javascript", "R"] + -4 -3 -2 -1 +``` \ No newline at end of file From 9d39b60e77ac80a8709d81962c665a28235fa9e3 Mon Sep 17 00:00:00 2001 From: shahpranaf Date: Sat, 26 Oct 2019 14:15:38 +0530 Subject: [PATCH 28/93] Added info about Timer Functions in JavaScript and corrected one spelling mistake --- JavaScript_Advance/timer_functions.js | 8 +- docs/JavaScript_Advance/timer_function.md | 124 +++++++++++++++++++++- 2 files changed, 127 insertions(+), 5 deletions(-) diff --git a/JavaScript_Advance/timer_functions.js b/JavaScript_Advance/timer_functions.js index 8226cad..103dfc4 100644 --- a/JavaScript_Advance/timer_functions.js +++ b/JavaScript_Advance/timer_functions.js @@ -1,9 +1,9 @@ // setTimeout setInterval in both functions the time is specified in millisecond -// setTimeout This runs a code after given time starting form calling this method in program. +// setTimeout This runs a code after given time starting from calling this method in program. setTimeout(() => { - console.log("SetTimeout is Called"); + console.log("SetTimeout is Called"); }, 5000); // This will print SetTimeout is Called after 5sec after calling it // For stopping this we can use ClearTimeout @@ -11,12 +11,12 @@ setTimeout(() => { // setInterval This runs a code after specific interval of time till we stop the timer. starting = setInterval(() => { - console.log("SetInterval is Called"); + console.log("SetInterval is Called"); }, 3000); // This will print setInterval is Called after every 3sec // We can stop the interval and timeout using clearTimeout and clearInterval setTimeout(() => { - clearInterval(starting); + clearInterval(starting); }, 7000); // Output of this whole program is diff --git a/docs/JavaScript_Advance/timer_function.md b/docs/JavaScript_Advance/timer_function.md index 9e53e69..96cfd7c 100644 --- a/docs/JavaScript_Advance/timer_function.md +++ b/docs/JavaScript_Advance/timer_function.md @@ -1 +1,123 @@ -# Timer Function + +# Timer function + + + +Timer function allows us to execute a code at specified time intervals. + + + +There are two imporant methods : +1. setInterval(function, milliseconds) +2. setTimeout(function, milliseconds) + +We can run our code multiple times at particular time intervals. Let say we want to check the status of our website. We need to ping our website url after every minute. We can use setInterval method for this. + +If we want to delay the execution of our code then setTimeOut method can be used. For example, we want to popup a message box to user after 30 seconds of the page load. + + The `setTimeout()` and `setInterval()` are methods of the Window object. + +## setTimeout(function, milliseconds) + + The `setTimeout()` method runs a code after given time starting from calling this method in program.. + + The setTimeout function accepts two parameters: + + - *function * : a function to be executed + - *milliseconds *: the number of milliseconds to wait before execution + +```javascript + +setTimeout(() => { + + console.log("Heloooo 7 !!!"); + +}, 7000); /* This will print Hellooo !!! after 7 seconds */ + + +setTimeout(() => { + + console.log("Heloooo 3 !!!"); + +}, 3000); /* This will print Hellooo !!! after 3 seconds */ + +/* Output + +Heloooo 3!!! +Heloooo 7!!! + + */ + +``` + + ## Stopping the timer or Cancelling the setTimeout method + +We can stop execution of `setTimeout()` using `clearTimeout` method. This can only be done if the function has not already been executed. It uses the variable returned from `setTimeout()` + +```javascript +var1 = setTimeout(() => { + + console.log("Heloooo 7 !!!"); + +}, 7000); /* This will print Hellooo !!! after 7 seconds */ + + +var2 = setTimeout(() => { + + console.log("Heloooo 3 !!!"); + +}, 3000); /* This will print Hellooo !!! after 3 seconds */ + +clearTimeout(var1); /* this will not output Helooo 7 !!! */ + +/* Output + +Heloooo 3!!! + + */ +``` + + +## setInterval(function, milliseconds) + + The `setInterval()` method runs a given function after specific interval of time till we stop the timer. + + The setInterval function accepts two parameters: + + - *function * : a function to be executed + - *milliseconds *: the length of the timeinterval between each execution. + + + +```javascript + +// setInterval This runs a code after specific interval of time till we stop the timer. +starting = setInterval(() => { + +console.log("SetInterval is Called"); + +}, 3000); // This will print setInterval is Called after every 3sec + +/* Output + +SetInterval is Called +SetInterval is Called +SetInterval is Called +SetInterval is Called +. +. +. + */ + +``` + + ## Stopping the timer or Cancelling the setInterval method + +We can stop the interval and timeout using `clearInterval` method. It uses the variable returned from `setInterval` + +```javascript +clearInterval(starting); +``` + + + From 9a8c3a4c079ffc2c0a6cb9ac2b979afacde9af8c Mon Sep 17 00:00:00 2001 From: Aman sharma Date: Sat, 26 Oct 2019 15:21:49 +0530 Subject: [PATCH 29/93] Add datatypes doc Added Datatypes of javascript --- JavaScript_Basics/Datatypes.js | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 JavaScript_Basics/Datatypes.js diff --git a/JavaScript_Basics/Datatypes.js b/JavaScript_Basics/Datatypes.js new file mode 100644 index 0000000..25c73e7 --- /dev/null +++ b/JavaScript_Basics/Datatypes.js @@ -0,0 +1,3 @@ +var length = 16; // Number +var lastName = "Johnson"; // String +var x = { firstName: "John", lastName: "Doe" }; // Object \ No newline at end of file From 328427da816205c2efdae93ac39ba5c151ea0d9a Mon Sep 17 00:00:00 2001 From: Aman sharma Date: Sat, 26 Oct 2019 15:38:30 +0530 Subject: [PATCH 30/93] Add js hoisting Added javascript hoisting documentiaion. --- JavaScript_Basics/Hoisting.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 JavaScript_Basics/Hoisting.js diff --git a/JavaScript_Basics/Hoisting.js b/JavaScript_Basics/Hoisting.js new file mode 100644 index 0000000..b4dd508 --- /dev/null +++ b/JavaScript_Basics/Hoisting.js @@ -0,0 +1,24 @@ +/*JavaScript Declarations are Hoisted +In JavaScript, a variable can be declared after it has been used. + +In other words; a variable can be used before it has been declared. + +Example 1 gives the same result as Example 2:*/ + + +//Example 1 + +x = 5; // Assign 5 to x + +elem = document.getElementById("demo"); // Find an element +elem.innerHTML = x; // Display x in the element + +var x; // Declare x + +//Example 2 + +var x; // Declare x +x = 5; // Assign 5 to x + +elem = document.getElementById("demo"); // Find an element +elem.innerHTML = x; // Display x in the element \ No newline at end of file From 24f2604d31d0487d92459d1768cbf32137ba9246 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=96mer=20F=2E=20=C3=87?= Date: Sat, 26 Oct 2019 13:54:00 +0300 Subject: [PATCH 31/93] Update string_operation.md --- docs/JavaScript_Basics/string_operation.md | 25 ++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/docs/JavaScript_Basics/string_operation.md b/docs/JavaScript_Basics/string_operation.md index a14523a..72b9a97 100644 --- a/docs/JavaScript_Basics/string_operation.md +++ b/docs/JavaScript_Basics/string_operation.md @@ -1 +1,26 @@ # String Operation + +#### JavaScript strings are used for storing and manipulating text, just like in any other language. + +Strings are written inside quotes: +```javascript +const variableName = "Hello JavaScript"; +// or with single quotes +const variableName = 'Hello JavaScript'; +``` + +### Concatenation +First way of doing string concatenation is using **+** operator +```javascript +const name = "Richard"; + +const text = "Hello " + name; +console.log(text); // Hello Richard +``` +Or using **template literals**. More convenient way for manipulating strings contains many variables. +```javascript +const name = "Richard"; +// Use backticks ( ` ) inside quotes and put variables inside ${} +const text = `Hello ${Richard}`; +console.log(text); // Hello Richard +``` From d0b9d8db59f1131e6b99cc8a9e8b0b62272dd6d5 Mon Sep 17 00:00:00 2001 From: wojciech preficz Date: Sat, 26 Oct 2019 13:54:46 +0200 Subject: [PATCH 32/93] Add files via upload --- default_values.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 default_values.js diff --git a/default_values.js b/default_values.js new file mode 100644 index 0000000..7c7567d --- /dev/null +++ b/default_values.js @@ -0,0 +1,29 @@ +/* +A JavaScript function can have default parameter value. +Using default function parameters, you can initialize parameters with default values. +If you do not initialize a parameter with some value, then the default value of the parameter is undefined. +*/ + +const helpGST = (name, age) => { + console.log(name, age); +}; + +helpGST(); // Output will be undefined undefined + +const helpGSTWithDefaultValues = (name, age = 19) => { + console.log(name, age); +}; + +helpGSTWithDefaultValues("Swapnil"); // Output Swapnil 19 + +helpGSTWithDefaultValues("Vishal", 23); // Output Vishal 23 + +/* + You can also reuse default parameters to set another default parameter. +*/ + +const addOneToANumberAsDefault = (number1 = 1, number2 = number1 + 8) => { + console.log(number2); +}; + +addOneToANumberAsDefault(); // Output 9 \ No newline at end of file From 484df440bbd5f1391e52c2743b6db89cfb389225 Mon Sep 17 00:00:00 2001 From: GumpFlash Date: Sat, 26 Oct 2019 10:00:42 -0300 Subject: [PATCH 33/93] Update variables.md --- docs/JavaScript_Basics/variables.md | 72 +++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/docs/JavaScript_Basics/variables.md b/docs/JavaScript_Basics/variables.md index d9d249b..bd5bd6d 100644 --- a/docs/JavaScript_Basics/variables.md +++ b/docs/JavaScript_Basics/variables.md @@ -1 +1,73 @@ # Variables + +A variable is a value, can be changed, paired with an associated symbolic name, make your code more useful and easyful + +-------------------- + +In the Javascript has this types of variables: + +**Number** +```javascript +var exemple = 0; //Any number +``` + +**String** +```javascript +var exemple = "text"; //Any character in quotation marks +``` + +**Bool** +```javascript +var exemple = true; //or false +``` + +**Object** +```javascript +var exemple = {name:'carl',years:15}; //any object +``` + +**Array** +```javascript +var exemple = [1,"test"]; //list of any type of variable +``` + +**Class** +```javascript +var exemple = new Class(); //any classes +``` + +In the Javascript you don't need to declare the variable type. + +-------------------- + +There are also ways to declare the variable: + +**Var** +```javascript +if(true){ + var exemple = 1; //Declare like this + exemple = 2; //Can be changed + console.log(exemple); +} +console.log(exemple); //Is globally +``` + +**Let** +```javascript +if(true){ + let exemple = 1; //Declare like this + exemple = 2; //Can be changed + console.log(exemple); +} +console.log(exemple); //Isn't globally, just work in blocks +``` + +**Const** +```javascript +if(true){ + const exemple = 1; //Declare like this + exemple = 2; //Can't be changed, can only be declare one time + console.log(exemple); +} +console.log(exemple); //Is globally +``` From 0231156ef9613c2c3f44f02c2b42a84c13020136 Mon Sep 17 00:00:00 2001 From: NiyoEric Date: Sat, 26 Oct 2019 16:17:57 +0200 Subject: [PATCH 34/93] ft(readme): add a readme about destructuring in js --- docs/JavaScript_Advance/destructuring.md | 44 +++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/docs/JavaScript_Advance/destructuring.md b/docs/JavaScript_Advance/destructuring.md index b549bf6..d6b07ba 100644 --- a/docs/JavaScript_Advance/destructuring.md +++ b/docs/JavaScript_Advance/destructuring.md @@ -32,4 +32,46 @@ This is a bit repetative and now with ES6 destructuring assignment, completely u const { name, age, college } = a; ``` -This may look a bit weird, but let's walk through it together. You can see that the open bracket directly follows the `const`, followed by the three different properties that we are assigning to variables by the same name. In essence what we are doing is extracting the value of `name`, `age`, and `college` from the `a` object and assigning those values to `const` variables by the exact same name. \ No newline at end of file +This may look a bit weird, but let's walk through it together. You can see that the open bracket directly follows the `const`, followed by the three different properties that we are assigning to variables by the same name. In essence what we are doing is extracting the value of `name`, `age`, and `college` from the `a` object and assigning those values to `const` variables by the exact same name. + +## Destructuring and Assignment +There is a time when you want to destruct an item from an array and immediately name it, with javascript you can do it. + +```js +const { name: surname } = a; +``` +If you console the name and surname both will display print `Swapnil`. + +### Destructuring Array +Sometime data is saved in an array datastructure, we can destruct them if we want +```js +const array = [1, 2, 3, 4]; // Array Declaration +``` +How to access the items? we have options +> option 1 + +When we want to skip specific item +```js +const [first, second, , fourth] = array; // Array Destructuring +``` +Outoput is `1`, `2`, `4` // notice we skipped `third 3` +> Option 2 + +When you want all items from array +```js +const [first, second, third, fourth] = array; // Array Destructuring +``` +Outoput is `1`, `2`, `3`, `4` // all are printed + +Always check your array length before, and then use the power of destructuring. + +## Destructuring and Combination +We can use our destructuring skills to get a specific item and combine the rest data. How to do it? Basically we need to use javascript `Spread operator` + +```js +const bigArray = [ 1,2,3,4,5,6,6,7,8,9]; +``` +```js +const [firstItem, ...remainItems] = bigArray +``` +The output will be first item will be `1` and remaining items will be combained in array `[2, 3, 4, 5, 6, 6, 7, 8, 9]` \ No newline at end of file From 3be4c7bd192ea916e17235ab4d5a0f1a76e74328 Mon Sep 17 00:00:00 2001 From: NiyoEric Date: Sat, 26 Oct 2019 17:09:42 +0200 Subject: [PATCH 35/93] ft(readme): add a readme about nodejs express --- docs/JavaScript_Advance/express.md | 81 +++++++++++++++++++++++++++++- 1 file changed, 80 insertions(+), 1 deletion(-) diff --git a/docs/JavaScript_Advance/express.md b/docs/JavaScript_Advance/express.md index b0655c1..fe5e9e2 100644 --- a/docs/JavaScript_Advance/express.md +++ b/docs/JavaScript_Advance/express.md @@ -1 +1,80 @@ -# Express \ No newline at end of file +# Express + +## What is Express? +Express.js is a Node js web application server framework that helps to build single page and hybrid web application. +It is Fast, unopinionated, minimalist web framework, it means that developers have a right to design or structure the application how they want. + +## What can you do with Express? +You can build the following stacks + - MongoDB, Express.js, AngularJS, and Node.js. `MEAN` + - MongoDB, Express.js, React, and Node.js. `MERN` + - MongoDB, Express.js, Vue, and Node.js. `MEVN` + +## How to install Express? + > npm install express + +## How to configure port? +```js +const port = 3003; +``` +However, If port is taken there will be an issue when we deploy our project to server. it is better we to configure it dynamically. + +```js +const port = process.env.PORT || 3003; +``` + + +## How to import Express? +```js +const app = express(); +``` + +## How to access Route? +```js +const routes = express.Router(); +``` +Express has `Router` method that will help us to use `Http method`. for example `get`, `put`, `post` and `patch`. + +## get Methods +Get method is used to request a resource from the server. +```js +routes.get("/system_info", (req, res) => { + res.send("System on!"); +}); +``` +`"/system_info"` our routes. +`req` contains information about the http request. +`res` contains information about the http response. +`res.send("System on!");` is a message to display on screen after `get` request. + +## How to access data? +If we want to pass json data in our express app we need to configure it. lets say we are expecting `json` data. +```js +app.use(express.json()); +``` +## How to configure routes? +``` +app.use(routes); +``` +## How to start nodejs server? +```js +app.listen(port, () => console.log(`Server running in port ${port}`)); +``` + +*Full example* +```js +const express = require("express"); + +const port = 3003; +const app = express(); + +const routes = express.Router(); + +routes.get("/system_info", (req, res) => { + res.send("System on!"); +}); + +app.use(express.json()); +app.use(routes); +app.listen(port, () => console.log(`Server running in port ${port}`)); +``` \ No newline at end of file From e48966e355c4add2f70d26549ae1e763d6f90528 Mon Sep 17 00:00:00 2001 From: NiyoEric Date: Sat, 26 Oct 2019 17:46:36 +0200 Subject: [PATCH 36/93] Revert "ft(mistake): push on wrong PR" This reverts commit 3be4c7bd192ea916e17235ab4d5a0f1a76e74328. --- docs/JavaScript_Advance/express.md | 81 +----------------------------- 1 file changed, 1 insertion(+), 80 deletions(-) diff --git a/docs/JavaScript_Advance/express.md b/docs/JavaScript_Advance/express.md index fe5e9e2..b0655c1 100644 --- a/docs/JavaScript_Advance/express.md +++ b/docs/JavaScript_Advance/express.md @@ -1,80 +1 @@ -# Express - -## What is Express? -Express.js is a Node js web application server framework that helps to build single page and hybrid web application. -It is Fast, unopinionated, minimalist web framework, it means that developers have a right to design or structure the application how they want. - -## What can you do with Express? -You can build the following stacks - - MongoDB, Express.js, AngularJS, and Node.js. `MEAN` - - MongoDB, Express.js, React, and Node.js. `MERN` - - MongoDB, Express.js, Vue, and Node.js. `MEVN` - -## How to install Express? - > npm install express - -## How to configure port? -```js -const port = 3003; -``` -However, If port is taken there will be an issue when we deploy our project to server. it is better we to configure it dynamically. - -```js -const port = process.env.PORT || 3003; -``` - - -## How to import Express? -```js -const app = express(); -``` - -## How to access Route? -```js -const routes = express.Router(); -``` -Express has `Router` method that will help us to use `Http method`. for example `get`, `put`, `post` and `patch`. - -## get Methods -Get method is used to request a resource from the server. -```js -routes.get("/system_info", (req, res) => { - res.send("System on!"); -}); -``` -`"/system_info"` our routes. -`req` contains information about the http request. -`res` contains information about the http response. -`res.send("System on!");` is a message to display on screen after `get` request. - -## How to access data? -If we want to pass json data in our express app we need to configure it. lets say we are expecting `json` data. -```js -app.use(express.json()); -``` -## How to configure routes? -``` -app.use(routes); -``` -## How to start nodejs server? -```js -app.listen(port, () => console.log(`Server running in port ${port}`)); -``` - -*Full example* -```js -const express = require("express"); - -const port = 3003; -const app = express(); - -const routes = express.Router(); - -routes.get("/system_info", (req, res) => { - res.send("System on!"); -}); - -app.use(express.json()); -app.use(routes); -app.listen(port, () => console.log(`Server running in port ${port}`)); -``` \ No newline at end of file +# Express \ No newline at end of file From 24139c3221bea889a8092c9105184deee5334ed0 Mon Sep 17 00:00:00 2001 From: NiyoEric Date: Sat, 26 Oct 2019 17:55:11 +0200 Subject: [PATCH 37/93] ft(express): how to use express.js --- docs/JavaScript_Advance/express.md | 81 +++++++++++++++++++++++++++++- 1 file changed, 80 insertions(+), 1 deletion(-) diff --git a/docs/JavaScript_Advance/express.md b/docs/JavaScript_Advance/express.md index b0655c1..fe5e9e2 100644 --- a/docs/JavaScript_Advance/express.md +++ b/docs/JavaScript_Advance/express.md @@ -1 +1,80 @@ -# Express \ No newline at end of file +# Express + +## What is Express? +Express.js is a Node js web application server framework that helps to build single page and hybrid web application. +It is Fast, unopinionated, minimalist web framework, it means that developers have a right to design or structure the application how they want. + +## What can you do with Express? +You can build the following stacks + - MongoDB, Express.js, AngularJS, and Node.js. `MEAN` + - MongoDB, Express.js, React, and Node.js. `MERN` + - MongoDB, Express.js, Vue, and Node.js. `MEVN` + +## How to install Express? + > npm install express + +## How to configure port? +```js +const port = 3003; +``` +However, If port is taken there will be an issue when we deploy our project to server. it is better we to configure it dynamically. + +```js +const port = process.env.PORT || 3003; +``` + + +## How to import Express? +```js +const app = express(); +``` + +## How to access Route? +```js +const routes = express.Router(); +``` +Express has `Router` method that will help us to use `Http method`. for example `get`, `put`, `post` and `patch`. + +## get Methods +Get method is used to request a resource from the server. +```js +routes.get("/system_info", (req, res) => { + res.send("System on!"); +}); +``` +`"/system_info"` our routes. +`req` contains information about the http request. +`res` contains information about the http response. +`res.send("System on!");` is a message to display on screen after `get` request. + +## How to access data? +If we want to pass json data in our express app we need to configure it. lets say we are expecting `json` data. +```js +app.use(express.json()); +``` +## How to configure routes? +``` +app.use(routes); +``` +## How to start nodejs server? +```js +app.listen(port, () => console.log(`Server running in port ${port}`)); +``` + +*Full example* +```js +const express = require("express"); + +const port = 3003; +const app = express(); + +const routes = express.Router(); + +routes.get("/system_info", (req, res) => { + res.send("System on!"); +}); + +app.use(express.json()); +app.use(routes); +app.listen(port, () => console.log(`Server running in port ${port}`)); +``` \ No newline at end of file From 41ec30aea15202c422f70fdafb471b36aed5235b Mon Sep 17 00:00:00 2001 From: Swapnil Satish Shinde <37082605+Swap76@users.noreply.github.com> Date: Sat, 26 Oct 2019 23:38:50 +0530 Subject: [PATCH 38/93] Update objects.md --- docs/JavaScript_Basics/objects.md | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/docs/JavaScript_Basics/objects.md b/docs/JavaScript_Basics/objects.md index 9995c75..ccdf9be 100644 --- a/docs/JavaScript_Basics/objects.md +++ b/docs/JavaScript_Basics/objects.md @@ -2,20 +2,29 @@ In JavaScript, almost "everything" is an object. -Booleans can be objects (if defined with the new keyword) + -Numbers can be objects (if defined with the new keyword) + -Strings can be objects (if defined with the new keyword) + -Dates are always objects + -Maths are always objects + -Regular expressions are always objects --Arrays are always objects. + +-Arrays are always objects + -Functions are always objects + -Objects are always objects All JavaScript values, except primitives, are objects. + Objects are variables too. But objects can contain many values. The values are written as name : value pairs (name and value separated by a colon). -Example: +Example: var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; From c720efa396dda3d710679cc7c76fe3e076eb8d33 Mon Sep 17 00:00:00 2001 From: Cristian Garcia Date: Sat, 26 Oct 2019 13:11:40 -0500 Subject: [PATCH 39/93] Add info about Variables in JavaScript #197 --- docs/JavaScript_Basics/variables.md | 88 ++++++++++++++++++++++++++++- 1 file changed, 87 insertions(+), 1 deletion(-) diff --git a/docs/JavaScript_Basics/variables.md b/docs/JavaScript_Basics/variables.md index d9d249b..0640d45 100644 --- a/docs/JavaScript_Basics/variables.md +++ b/docs/JavaScript_Basics/variables.md @@ -1 +1,87 @@ -# Variables +# Variables + +## Datatypes +One of the most fundamental characteristics of a programming language is the set of data types it +supports. These are the type of values that can be represented and manipulated in a +programming language. +JavaScript allows you to work with three primitive data types − +Numbers, eg. 123, 120.50 etc. +Strings of text e.g. "This text string" etc. +Boolean e.g. true or false. +JavaScript also defines two trivial data types, null and undefined, each of which defines only a +single value. In addition to these primitive data types, JavaScript supports a composite data type +known as object. We will cover objects in detail in a separate chapter. +Note − Java does not make a distinction between integer values and floating-point values. All +numbers in JavaScript are represented as floating-point values. JavaScrip + +Like many other programming languages, JavaScript has variables. Variables can be thought of as +named containers. You can place data into these containers and then refer to the data simply by +naming the container. +Before you use a variable in a JavaScript program, you must declare it. Variables are declared with +the var keyword as follows. +```js + +``` +You can also declare multiple variables with the same var keyword as follows − +```js + +``` +Storing a value in a variable is called variable initialization. You can do variable initialization at +the time of variable creation or at a later point in time when you need that variable. +For instance, you might create a variable named money and assign the value 2000.50 to it later. +For another variable, you can assign a value at the time of initialization as follows. +```js + +``` +Note − Use the var keyword only for declaration or initialization, once for the life of any variable +name in a document. You should not re-declare same variable twice. +JavaScript is untyped language. This means that a JavaScript variable can hold a value of any +data type. Unlike many other languages, you don't have to tell JavaScript during variable +declaration what type of value the variable will hold. The value type of a variable can change +during the execution of a program and JavaScript takes care of it automatically. +JavaScript Variable Scope +The scope of a variable is the region of your program in which it is defined. JavaScript variables +have only two scopes. +Global Variables − A global variable has global scope which means it can be defined +anywhere in your JavaScript code. +Local Variables − A local variable will be visible only within a function where it is defined. +Function parameters are always local to that function. +Within the body of a function, a local variable takes precedence over a global variable with the +same name. If you declare a local variable or function parameter with the same name as a global +variable, you effectively hide the global variable. Take a look into the following example. +```js + +``` +This produces the following result − +local +JavaScript Variable Names +While naming your variables in JavaScript, keep the following rules in mind. +You should not use any of the JavaScript reserved keywords as a variable name. These +keywords are mentioned in the next section. For example, break or boolean variable names +are not valid. +JavaScript variable names should not start with a numeral 0 − 9. They must begin with a letter +or an underscore character. For example, 123test is an invalid variable name but _123test +is a valid one. +JavaScript variable names are case-sensitive. For example, Name and name are two +different variables. From 04dde4e594338dcb29f4cc93a84c7b748820cace Mon Sep 17 00:00:00 2001 From: Swapnil Satish Shinde <37082605+Swap76@users.noreply.github.com> Date: Sat, 26 Oct 2019 23:41:49 +0530 Subject: [PATCH 40/93] Update fs_module.md --- docs/JavaScript_Advance/fs_module.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/JavaScript_Advance/fs_module.md b/docs/JavaScript_Advance/fs_module.md index efa69df..e384430 100644 --- a/docs/JavaScript_Advance/fs_module.md +++ b/docs/JavaScript_Advance/fs_module.md @@ -25,13 +25,13 @@ content.on("open", () => { }); ``` We can also listen to an event called `data` that will be called when data is present. -```fs +```js content.on("data", (data) => { console.log(data); }); ``` We can also listen to the event when a file is closed. -```fs +```js content.on("close", () => { console.log("File ends"); }); @@ -52,4 +52,4 @@ fsModule File ends ``` -In conclusion, createReadStream is similar to a publish-subscribe system where our stream is the subscriber and the file is the publisher, and as such can be implemented using MQTT. \ No newline at end of file +In conclusion, createReadStream is similar to a publish-subscribe system where our stream is the subscriber and the file is the publisher, and as such can be implemented using MQTT. From 0b7de9708c4c333a6d3476ec52608fefa468286d Mon Sep 17 00:00:00 2001 From: Swapnil Satish Shinde <37082605+Swap76@users.noreply.github.com> Date: Sat, 26 Oct 2019 23:46:37 +0530 Subject: [PATCH 41/93] Update timer_function.md --- docs/JavaScript_Advance/timer_function.md | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/docs/JavaScript_Advance/timer_function.md b/docs/JavaScript_Advance/timer_function.md index 96cfd7c..391a7bf 100644 --- a/docs/JavaScript_Advance/timer_function.md +++ b/docs/JavaScript_Advance/timer_function.md @@ -1,12 +1,7 @@ - # Timer function - - Timer function allows us to execute a code at specified time intervals. - - There are two imporant methods : 1. setInterval(function, milliseconds) 2. setTimeout(function, milliseconds) @@ -111,7 +106,7 @@ SetInterval is Called ``` - ## Stopping the timer or Cancelling the setInterval method +## Stopping the timer or Cancelling the setInterval method We can stop the interval and timeout using `clearInterval` method. It uses the variable returned from `setInterval` From f406844f9544548e4408a74747a4b0f74e78ce0b Mon Sep 17 00:00:00 2001 From: Swapnil Satish Shinde <37082605+Swap76@users.noreply.github.com> Date: Sat, 26 Oct 2019 23:48:43 +0530 Subject: [PATCH 42/93] Delete Hoisting.js --- JavaScript_Basics/Hoisting.js | 24 ------------------------ 1 file changed, 24 deletions(-) delete mode 100644 JavaScript_Basics/Hoisting.js diff --git a/JavaScript_Basics/Hoisting.js b/JavaScript_Basics/Hoisting.js deleted file mode 100644 index b4dd508..0000000 --- a/JavaScript_Basics/Hoisting.js +++ /dev/null @@ -1,24 +0,0 @@ -/*JavaScript Declarations are Hoisted -In JavaScript, a variable can be declared after it has been used. - -In other words; a variable can be used before it has been declared. - -Example 1 gives the same result as Example 2:*/ - - -//Example 1 - -x = 5; // Assign 5 to x - -elem = document.getElementById("demo"); // Find an element -elem.innerHTML = x; // Display x in the element - -var x; // Declare x - -//Example 2 - -var x; // Declare x -x = 5; // Assign 5 to x - -elem = document.getElementById("demo"); // Find an element -elem.innerHTML = x; // Display x in the element \ No newline at end of file From fcd329697c2a5caad6cd3982ae287de824aeb82b Mon Sep 17 00:00:00 2001 From: Ale Date: Sat, 26 Oct 2019 13:20:05 -0500 Subject: [PATCH 43/93] Add info about identifiers names restricctions --- JavaScript_Basics/variables.js | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/JavaScript_Basics/variables.js b/JavaScript_Basics/variables.js index 5dcee3f..f5c499f 100644 --- a/JavaScript_Basics/variables.js +++ b/JavaScript_Basics/variables.js @@ -2,10 +2,18 @@ // There is only 3 types of variables in javascript -let a = "Swapnil"; // New type introduced in ES6. Value of let can change any time. +let userNickname = "Swapnil"; // New type introduced in ES6. Value of let can change any time. -a = "Swap76"; +userNickname = "Swap76"; -const pi = 3.14;// New type introduced in ES6. Value of pi now cannot be changed as this is defined as const. +const PI = 3.14;// New type introduced in ES6. Value of pi now cannot be changed as this is defined as const. -var b = 26;// This is Deprecated as this creates many problems in future. \ No newline at end of file +var day26 = 26;// This is Deprecated as this creates many problems in future. + + + +//Tips: *use significatives variables names, example: +// let a = "User's name" for let userNickName = "User's name" +//*CammelCase for a better understaning, JS has case sensitive. +//*Variables names must begin with a letter. +//*write constants with Upper case. \ No newline at end of file From 6e62c6ceb40bee2311ea49db61f548459b2940d0 Mon Sep 17 00:00:00 2001 From: Swapnil Satish Shinde <37082605+Swap76@users.noreply.github.com> Date: Sat, 26 Oct 2019 23:52:17 +0530 Subject: [PATCH 44/93] Update string_operation.md --- docs/JavaScript_Basics/string_operation.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/JavaScript_Basics/string_operation.md b/docs/JavaScript_Basics/string_operation.md index 72b9a97..bd59004 100644 --- a/docs/JavaScript_Basics/string_operation.md +++ b/docs/JavaScript_Basics/string_operation.md @@ -15,12 +15,15 @@ First way of doing string concatenation is using **+** operator const name = "Richard"; const text = "Hello " + name; + console.log(text); // Hello Richard ``` Or using **template literals**. More convenient way for manipulating strings contains many variables. ```javascript const name = "Richard"; + // Use backticks ( ` ) inside quotes and put variables inside ${} const text = `Hello ${Richard}`; + console.log(text); // Hello Richard ``` From 965ea61df2fcf4e71abc24524d498fd0c1dd0fc8 Mon Sep 17 00:00:00 2001 From: Swapnil Satish Shinde <37082605+Swap76@users.noreply.github.com> Date: Sun, 27 Oct 2019 00:02:25 +0530 Subject: [PATCH 45/93] Update express.md --- docs/JavaScript_Advance/express.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/JavaScript_Advance/express.md b/docs/JavaScript_Advance/express.md index fe5e9e2..a242feb 100644 --- a/docs/JavaScript_Advance/express.md +++ b/docs/JavaScript_Advance/express.md @@ -56,7 +56,7 @@ app.use(express.json()); ``` app.use(routes); ``` -## How to start nodejs server? +## How to start NodeJS server? ```js app.listen(port, () => console.log(`Server running in port ${port}`)); ``` @@ -77,4 +77,4 @@ routes.get("/system_info", (req, res) => { app.use(express.json()); app.use(routes); app.listen(port, () => console.log(`Server running in port ${port}`)); -``` \ No newline at end of file +``` From 686331e80de53022f521f2a80490e386d0f15456 Mon Sep 17 00:00:00 2001 From: Swapnil Satish Shinde <37082605+Swap76@users.noreply.github.com> Date: Sun, 27 Oct 2019 00:10:35 +0530 Subject: [PATCH 46/93] Update variables.md --- docs/JavaScript_Basics/variables.md | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/docs/JavaScript_Basics/variables.md b/docs/JavaScript_Basics/variables.md index 0640d45..e4e6877 100644 --- a/docs/JavaScript_Basics/variables.md +++ b/docs/JavaScript_Basics/variables.md @@ -4,19 +4,24 @@ One of the most fundamental characteristics of a programming language is the set of data types it supports. These are the type of values that can be represented and manipulated in a programming language. + JavaScript allows you to work with three primitive data types − Numbers, eg. 123, 120.50 etc. + Strings of text e.g. "This text string" etc. Boolean e.g. true or false. + JavaScript also defines two trivial data types, null and undefined, each of which defines only a single value. In addition to these primitive data types, JavaScript supports a composite data type known as object. We will cover objects in detail in a separate chapter. + Note − Java does not make a distinction between integer values and floating-point values. All -numbers in JavaScript are represented as floating-point values. JavaScrip +numbers in JavaScript are represented as floating-point values. Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container. + Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows. ```js @@ -48,17 +53,22 @@ For another variable, you can assign a value at the time of initialization as fo ``` Note − Use the var keyword only for declaration or initialization, once for the life of any variable name in a document. You should not re-declare same variable twice. + JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type. Unlike many other languages, you don't have to tell JavaScript during variable declaration what type of value the variable will hold. The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically. + JavaScript Variable Scope The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two scopes. + Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code. + Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function. + Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. Take a look into the following example. @@ -77,11 +87,14 @@ This produces the following result − local JavaScript Variable Names While naming your variables in JavaScript, keep the following rules in mind. + You should not use any of the JavaScript reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid. + JavaScript variable names should not start with a numeral 0 − 9. They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one. + JavaScript variable names are case-sensitive. For example, Name and name are two different variables. From af824992064b9d7c85b6c74fd38c8b1aae219413 Mon Sep 17 00:00:00 2001 From: Suryavamsi Tenneti Date: Sat, 26 Oct 2019 14:09:58 -0700 Subject: [PATCH 47/93] Added documentation for Looping an Object --- docs/JavaScript_Basics/looping_an_object.md | 49 ++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/docs/JavaScript_Basics/looping_an_object.md b/docs/JavaScript_Basics/looping_an_object.md index 18a6886..2f3de7f 100644 --- a/docs/JavaScript_Basics/looping_an_object.md +++ b/docs/JavaScript_Basics/looping_an_object.md @@ -1 +1,48 @@ -# Looping an object \ No newline at end of file +# Looping an object +A for...in loop iterates over properties of an object. + +```javascript +for (const key in studentObject) { + if (key === 105) { + console.log("The Student's name is ", studentObject[key]); + } +``` +In this code we are iterating over all the properties of the studentObject and if the property is __105__ we are logging to the console the value of that property. + +The issue with type of looping is that we need to check if the property belongs to the object. We can do this with **hasOwnProperty** +```javascript +for (const key in studentObject) { + if(studentObject.hasOwnProperty(key)){ + if (key === 105) { + console.log("The Student's name is ", studentObject[key]); + } + } + +``` + +We can also use other methods to convert an object into an array, loop through the array and check for a specific key. +- Object.keys +- Object.entries + +### Object.keys +We can use **Object.Keys** to convert into an array of property values and we can loop through the array as follows, +```javascript +const keys = Object.keys(studentObject) +for(const key of keys){ + if (key === 105) { + console.log("The Student's name is ", studentObject[key]); + } +} +``` + +### Object.entries +We can use **Object.Keys** to convert into an array of property values and we can loop through the array as follows, +```javascript +const entries = Object.entries(studentObject) +for(const [key, value] of keys){ + if (key === 105) { + console.log("The Student's name is ", value); + } +} +``` + From 7359553dfbe5cfb6feb21fbe512af0a9256aff32 Mon Sep 17 00:00:00 2001 From: ferdiaz93 Date: Sat, 26 Oct 2019 18:34:31 -0300 Subject: [PATCH 48/93] comments added and new console logs --- JavaScript_Basics/variables.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/JavaScript_Basics/variables.js b/JavaScript_Basics/variables.js index f5c499f..269973c 100644 --- a/JavaScript_Basics/variables.js +++ b/JavaScript_Basics/variables.js @@ -2,14 +2,16 @@ // There is only 3 types of variables in javascript -let userNickname = "Swapnil"; // New type introduced in ES6. Value of let can change any time. +var day26 = 26;// This is Deprecated as this creates many problems in future. +//Variables created with var can be rewrite but the most important problem is about the scope. +let userNickname = "Swapnil"; // New type introduced in ES6. Value of let can change any time. userNickname = "Swap76"; +console.log(userNickname) // Output {"Swap76"} const PI = 3.14;// New type introduced in ES6. Value of pi now cannot be changed as this is defined as const. - -var day26 = 26;// This is Deprecated as this creates many problems in future. - +PI = 2; // Output {Error: PI is read only} +console.log(PI) // Output {3.14} //Tips: *use significatives variables names, example: From 055a3bc600e53758c55b0052fbe70395c4f53068 Mon Sep 17 00:00:00 2001 From: Emmy Date: Sat, 26 Oct 2019 20:05:28 -0700 Subject: [PATCH 49/93] added explanation to arrow functions --- JavaScript_Advance/arrow_function.js | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/JavaScript_Advance/arrow_function.js b/JavaScript_Advance/arrow_function.js index 39aea3e..1dbd821 100644 --- a/JavaScript_Advance/arrow_function.js +++ b/JavaScript_Advance/arrow_function.js @@ -1,7 +1,19 @@ let a = () => { // This is arrow function came new in ES6 + //It assigns the function to variable a as the identifier with let instead and adds arrows before the curly braces. + }; + +let multiply = (num) => num * num + +//arrow functions also works without curly braces {} and can directly write expression after the arrows +// this is known as concise body as opposed to a block body (with {}); +//cannot be used with if statements, or an error will appear since it only takes one expression; +//ternary operators can be used with arrow functions as a more concise way to write if statements + + + let info = { firstName: "Swapnil", lastName: "Shinde", @@ -9,6 +21,8 @@ let info = { return (`My name is ${this.firstName} ${this.lastName}`); // Arrow functions don't have "this" property } } +//not having this. binding means it also cannot be called with new and used as a constructor + console.log(info.getFullName()); // Output My name is undefined undefined that's why we don't use this with arrow function @@ -31,7 +45,7 @@ class Student { } getName = () => { - return this.name; + return this.name; } } @@ -69,4 +83,4 @@ setTimeout(function () { //settimeout with arrow function setTimeout(() => { console.log("hello world"); -}, 0); +}, 0); //arrow functions provide better readability From 745b33c0f6e133810c7476fa09c79c7d5ff4bf27 Mon Sep 17 00:00:00 2001 From: Swapnil Satish Shinde <37082605+Swap76@users.noreply.github.com> Date: Sun, 27 Oct 2019 10:29:34 +0530 Subject: [PATCH 50/93] Update looping_an_object.md --- docs/JavaScript_Basics/looping_an_object.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/JavaScript_Basics/looping_an_object.md b/docs/JavaScript_Basics/looping_an_object.md index 2f3de7f..162ca30 100644 --- a/docs/JavaScript_Basics/looping_an_object.md +++ b/docs/JavaScript_Basics/looping_an_object.md @@ -6,6 +6,7 @@ for (const key in studentObject) { if (key === 105) { console.log("The Student's name is ", studentObject[key]); } +} ``` In this code we are iterating over all the properties of the studentObject and if the property is __105__ we are logging to the console the value of that property. @@ -17,7 +18,7 @@ for (const key in studentObject) { console.log("The Student's name is ", studentObject[key]); } } - +} ``` We can also use other methods to convert an object into an array, loop through the array and check for a specific key. @@ -30,8 +31,8 @@ We can use **Object.Keys** to convert into an array of property values and we ca const keys = Object.keys(studentObject) for(const key of keys){ if (key === 105) { - console.log("The Student's name is ", studentObject[key]); - } + console.log("The Student's name is ", studentObject[key]); + } } ``` @@ -41,8 +42,7 @@ We can use **Object.Keys** to convert into an array of property values and we ca const entries = Object.entries(studentObject) for(const [key, value] of keys){ if (key === 105) { - console.log("The Student's name is ", value); + console.log("The Student's name is ", value); } } ``` - From 8d824f7dfd3f7ac437a87483f0e860ad9c19eb5b Mon Sep 17 00:00:00 2001 From: Lindsay Chapin Date: Sat, 26 Oct 2019 23:30:46 -0600 Subject: [PATCH 51/93] working on conditional statement --- docs/JavaScript_Basics/condition_statments.md | 75 ++++++++++++++++++- 1 file changed, 74 insertions(+), 1 deletion(-) diff --git a/docs/JavaScript_Basics/condition_statments.md b/docs/JavaScript_Basics/condition_statments.md index 009b493..f2bf290 100644 --- a/docs/JavaScript_Basics/condition_statments.md +++ b/docs/JavaScript_Basics/condition_statments.md @@ -1 +1,74 @@ -# IF, ELSE IF, ELSE CONDITION \ No newline at end of file +# IF, ELSE IF, ELSE CONDITION +Conditional statements run specific blocks of code based on certain perimeters that you set. Like other code it reads top to bottom so the order that you put your conditions in matter. + +Example of an if/else if/else: +``` +if(this statement is true){ + do this +} else if (this statement is true){ + do this +} else{ + do this +} +``` +If's always come first and have a set of parenthesis with a statement in them that you are checking to see if it's true, if it is the code in the curly brackets is run, otherwise it would move on to the else if and see if that statement is true. If it is then it runs that block of code, if not then it would run the code in the else statement. Once a statement is deemed true and the code is run it doesn't continue to read through the code even if there is a more accurate statement lower down. A good example of where this matters would be the common coding challenge fizzbuzz. The idea of fizzbuzz is that you want to log all the numbers from 1-100 however if it's divisible by 3 print "fizz", 5 print "buzz", and if it's divisible by both 3 and 5 print "fizzbuzz". +If we write our if's the way the problem is stated we would would write: +``` +if(num % 3 == 0){ + console.log("fizz") +} else if(num % 5 == 0){ + console.log("buzz") +} else if(num % 3 == 0 && num % 5 == 0){ + console.log("fizzbuzz") +} else { + console.log(num) +} +``` +In this case every time we'd hit a number that should print fizzbuzz we'd get fizz because that is a truthful statement and it's not looking for a more correct answer. +To account for that we'd want to adjust our statement order to: +``` +if(num % 3 == 0 && num % 5 == 0){ + console.log("fizzbuzz") +} else if(num % 5 == 0){ + console.log("buzz") +} else if(num % 3 == 0){ + console.log("fizz") +} else { + console.log(num) +} +``` + +## What if we don't write else if but just another if? +Sometimes you see code that has a number of if's in a row but no else if's or else's in this case it's checking each condition in that case each if + +This code will only print "it's a number": +``` +var number = 2 +if(typeof number === "number"){ +console.log("it's a number") +} else if(number % 2 === 0){ +console.log("it's even") +} +``` +However this code will print both "it's a number" and "it's even" +``` +var number = 2 +if(typeof number === "number"){ +console.log("it's a number") +} +if(number % 2 === 0){ +console.log("it's even") +} +``` + +## What if we only have an if? +If there is only one if then it only does that code if the condition is true and nothing if it's false. + +For example: +``` +if(number % 2 === 0){ +console.log("it's even") +} +console.log(number) +``` +In this case if `number` From 39a50b50a8f5b2327adaf3a306ffe9653b924ea1 Mon Sep 17 00:00:00 2001 From: Lindsay Chapin Date: Sat, 26 Oct 2019 23:31:38 -0600 Subject: [PATCH 52/93] conditional statement --- docs/JavaScript_Basics/condition_statments.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/JavaScript_Basics/condition_statments.md b/docs/JavaScript_Basics/condition_statments.md index f2bf290..940c05f 100644 --- a/docs/JavaScript_Basics/condition_statments.md +++ b/docs/JavaScript_Basics/condition_statments.md @@ -71,4 +71,4 @@ console.log("it's even") } console.log(number) ``` -In this case if `number` +In this case if `number` is even it will print it's even and it will always print the number. From c527c740e899c7b6605f083aa026836a78f3c66e Mon Sep 17 00:00:00 2001 From: Lindsay Chapin Date: Sat, 26 Oct 2019 23:39:32 -0600 Subject: [PATCH 53/93] finishing conditionals --- docs/JavaScript_Basics/condition_statments.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/JavaScript_Basics/condition_statments.md b/docs/JavaScript_Basics/condition_statments.md index 940c05f..4340633 100644 --- a/docs/JavaScript_Basics/condition_statments.md +++ b/docs/JavaScript_Basics/condition_statments.md @@ -1,5 +1,5 @@ # IF, ELSE IF, ELSE CONDITION -Conditional statements run specific blocks of code based on certain perimeters that you set. Like other code it reads top to bottom so the order that you put your conditions in matter. +Conditional statements run specific blocks of code based on certain parameters that you set. Like other code it reads top to bottom so the order that you put your conditions in matter. Example of an if/else if/else: ``` @@ -11,7 +11,7 @@ if(this statement is true){ do this } ``` -If's always come first and have a set of parenthesis with a statement in them that you are checking to see if it's true, if it is the code in the curly brackets is run, otherwise it would move on to the else if and see if that statement is true. If it is then it runs that block of code, if not then it would run the code in the else statement. Once a statement is deemed true and the code is run it doesn't continue to read through the code even if there is a more accurate statement lower down. A good example of where this matters would be the common coding challenge fizzbuzz. The idea of fizzbuzz is that you want to log all the numbers from 1-100 however if it's divisible by 3 print "fizz", 5 print "buzz", and if it's divisible by both 3 and 5 print "fizzbuzz". +`If` always comes first and have a set of parenthesis with a statement in them that you are checking to see if it's true. If it is, the code in the curly brackets is run, otherwise it would move on to the `else if`, and see if that statement is true. If `else if` is true then it runs that block of code, if not then it would run the code in the `else` statement. Once a statement is deemed true and the code is run it doesn't continue to read through the code even if there is a more accurate statement lower down. A good example of where this matters would be the common coding challenge fizzbuzz. The idea of fizzbuzz is that you want to log all the numbers from 1-100 however if it's divisible by 3 print "fizz", 5 print "buzz", and if it's divisible by both 3 and 5 print "fizzbuzz". If we write our if's the way the problem is stated we would would write: ``` if(num % 3 == 0){ @@ -39,7 +39,7 @@ if(num % 3 == 0 && num % 5 == 0){ ``` ## What if we don't write else if but just another if? -Sometimes you see code that has a number of if's in a row but no else if's or else's in this case it's checking each condition in that case each if +Sometimes you see code that has a number of `if`'s in a row but no `else if`'s or `else`'s in this case it's checking each condition in that case each `if` This code will only print "it's a number": ``` @@ -62,7 +62,7 @@ console.log("it's even") ``` ## What if we only have an if? -If there is only one if then it only does that code if the condition is true and nothing if it's false. +If there is only one `if` then it only does that code `if` the condition is true and nothing if it's false. For example: ``` @@ -71,4 +71,4 @@ console.log("it's even") } console.log(number) ``` -In this case if `number` is even it will print it's even and it will always print the number. +In this case if `number` is even it will print it's even and it will always print the number. From dc34c5b06ba30e4755d8a75c841fe249a718b53f Mon Sep 17 00:00:00 2001 From: Anuradha <32791199+anuk79@users.noreply.github.com> Date: Sun, 27 Oct 2019 12:21:43 +0530 Subject: [PATCH 54/93] update higher_order_functions.md updated the higher_order_functions file to contain a basic tutorial flow for beginners --- JavaScript_Basics/higher_order_functions.js | 46 --------- JavaScript_Basics/higher_order_functions.md | 100 ++++++++++++++++++++ 2 files changed, 100 insertions(+), 46 deletions(-) delete mode 100644 JavaScript_Basics/higher_order_functions.js create mode 100644 JavaScript_Basics/higher_order_functions.md diff --git a/JavaScript_Basics/higher_order_functions.js b/JavaScript_Basics/higher_order_functions.js deleted file mode 100644 index d00da4e..0000000 --- a/JavaScript_Basics/higher_order_functions.js +++ /dev/null @@ -1,46 +0,0 @@ -// HIGHER ORDER FUNCTIONS FOR ARRAYS - -// the arrays in javascript have 3 main HOF -// SUCH MAP, FILTER AND REDUCE - -const list = [1, 2, 3, 4, 5]; - -// map - -// the map function iterate over an a list and return a new array -// the map receive a function that receives 3 arguments -// 1st arg is one by one the items in the list like "1" or "2" in the list example -// 2nc arg is the index of the item in the list (for "1" is 0, etc...) -// 3rd arg is the entire list [1,2,3,4,5] - -const newList = list.map(function (item, index, list) { - return item * 2; -}); - -// this return a new array with new values like [2, 4, 6, 8, 10] - -// filter - -// the filter function iterate over an a list and return a new array based on a condition -// the filter receive a function that receives 3 arguments -// 1st arg is one by one the items in the list like "1" or "2" in the list example -// 2nc arg is the index of the item in the list (for "1" is 0, etc...) -// 3rd arg is the entire list [1,2,3,4,5] - -const newListFiltered = list.map(function (item, index, list) { - // condition to return a value for the new array - return item % 2 === 0; -}) - -// this return a new array with some filtered values based on a condition [2, 4] -// because 2 and 4 the recidus is 0 - -// sort - -// the sort function iterate over an a list and return a new array sorted based on a comparefunction -// if you don't add a function sort numbers in incremental way and text in alphabetic way -// the sort receive a function that receives 3 arguments - - [1, 10, 2, 21].sort(); - -// this return [1, 10, 2, 21] \ No newline at end of file diff --git a/JavaScript_Basics/higher_order_functions.md b/JavaScript_Basics/higher_order_functions.md new file mode 100644 index 0000000..9643614 --- /dev/null +++ b/JavaScript_Basics/higher_order_functions.md @@ -0,0 +1,100 @@ +## HIGHER ORDER FUNCTIONS + +A **Higher Order function** or **HOF** is a function that receives a function as an argument or returns the function as output. + +There are some built-in HOF for Arrays in Javascript, such as + - *Array.prototype.map* + - *Array.prototype.filter* + - *Array.prototype.reduce*. + +Let's understand each of these through examples. + +We will use the below array `list` as the base array to operate over. + +``` + const list = [1, 2, 3, 4, 5]; +``` + +## 1. map + + - The **map** function iterates over an input array and returns a new array. + - It does not change the original array, but creates a new array. + - The map receives a callback function as its argument. This callback function receives 3 arguments + - 1st arg is the **elememt** of the array, like 1, 2, 3, 4, 5 + - 2nd arg is the **index** of the item in the list (index for first element is 0, and so on) + - 3rd arg is the original array [1,2,3,4,5] on which map is being called + +``` + const newList = list.map(function (item, index, list) { + return item * 2; + }); + + console.log(list); // prints [1, 2, 3, 4, 5] + console.log(newList); // prints [2, 4, 6, 8, 10] +``` + + +## 2. filter + + - the **filter** function iterates over an input array and returns a new array based on a condition + - the filter receive a callnack function as its argument. This callback functions receives 3 arguments: + - 1st arg is the **element** in the list like "1" or "2" in the list example + - 2nd arg is the **index** of the item in the list (index for first element is 0, and so on) + - 3rd arg is the original array [1,2,3,4,5] on which filter is being called + + ``` + // this filtered list will contain only even numbers + + const newListFiltered = list.filter(function (item, index, list) { + // filter will return the value if it satisfies the below condition + return item % 2 === 0; + }); + + console.log(list); // prints [1, 2, 3, 4, 5] + console.log(newList); // prints [2, 4] + +``` + +## 3. reduce + + - the **reduce** function iterates over an input array and returns a single output value + - it receives two arguments: + - a callback function, also called as **reducer** function + - an **initialValue** (this is optional parameter) + - the reducer function accepts four parameters: + - 1st arg is **accumulator** which contains the accumulated value which will be returned when the array is reduced. + If initalvalue is provided, accumulator will be equal to initialvalue, else it will be equal to the first element in the array + - 2nd arg is **currentValue** which points to the current value of the array which is being iterated over. + If initalvalue is provided, currentValue will be equal to the first element in the array, else it will be equal to the second element in the array + - 3rd arg is **index** which contains the index of the currentValue in the input array + - 4th arg is the **sourceArray** which is the input array on which reduce is called + +``` +// Example 1 +// this will return sum of all items in list. here, there is no initialvalue provided + +const sumOfListItems = list.reduce(function(accumulator, currentValue) { + return accumulator + currentValue; +}); + +console.log(list); // prints [1, 2, 3, 4, 5] +console.log(sumOfListItems); // prints 15 +``` + +``` +// Example 2 +// this will return sum of all items in list. here, the initialvalue is provided as 20 + +const newSumOfListItems = list.reduce(function(accumulator, currentValue) { + return accumulator + currentValue; +}, 20); + +console.log(list); // prints [1, 2, 3, 4, 5] +console.log(newSumOfListItems); // prints 35 (the sum of list items is 15, and the initial value was 20, so, 20 + 15 = 35) +``` + + + + + + From 3c7edcd5fdbcb940ea76372a826c6f07f6686496 Mon Sep 17 00:00:00 2001 From: Swapnil Satish Shinde <37082605+Swap76@users.noreply.github.com> Date: Sun, 27 Oct 2019 17:49:13 +0530 Subject: [PATCH 55/93] Update condition_statments.md --- docs/JavaScript_Basics/condition_statments.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/JavaScript_Basics/condition_statments.md b/docs/JavaScript_Basics/condition_statments.md index 4340633..559f20b 100644 --- a/docs/JavaScript_Basics/condition_statments.md +++ b/docs/JavaScript_Basics/condition_statments.md @@ -2,7 +2,7 @@ Conditional statements run specific blocks of code based on certain parameters that you set. Like other code it reads top to bottom so the order that you put your conditions in matter. Example of an if/else if/else: -``` +```js if(this statement is true){ do this } else if (this statement is true){ @@ -26,7 +26,7 @@ if(num % 3 == 0){ ``` In this case every time we'd hit a number that should print fizzbuzz we'd get fizz because that is a truthful statement and it's not looking for a more correct answer. To account for that we'd want to adjust our statement order to: -``` +```js if(num % 3 == 0 && num % 5 == 0){ console.log("fizzbuzz") } else if(num % 5 == 0){ @@ -42,7 +42,7 @@ if(num % 3 == 0 && num % 5 == 0){ Sometimes you see code that has a number of `if`'s in a row but no `else if`'s or `else`'s in this case it's checking each condition in that case each `if` This code will only print "it's a number": -``` +```js var number = 2 if(typeof number === "number"){ console.log("it's a number") @@ -51,7 +51,7 @@ console.log("it's even") } ``` However this code will print both "it's a number" and "it's even" -``` +```js var number = 2 if(typeof number === "number"){ console.log("it's a number") @@ -65,7 +65,7 @@ console.log("it's even") If there is only one `if` then it only does that code `if` the condition is true and nothing if it's false. For example: -``` +```js if(number % 2 === 0){ console.log("it's even") } From e1cee852c6b062e88f6845edfeec968278af2e14 Mon Sep 17 00:00:00 2001 From: shahpranaf Date: Sun, 27 Oct 2019 17:57:11 +0530 Subject: [PATCH 56/93] Added information on this keyword with examples --- docs/JavaScript_Basics/this.md | 106 ++++++++++++++++++++++++++++++++- 1 file changed, 105 insertions(+), 1 deletion(-) diff --git a/docs/JavaScript_Basics/this.md b/docs/JavaScript_Basics/this.md index 56cda30..d38215f 100644 --- a/docs/JavaScript_Basics/this.md +++ b/docs/JavaScript_Basics/this.md @@ -1 +1,105 @@ -# This + +# 'this' keyword + +JavaScript's 'this' keyword refers to the object it belongs to. It's values depends on where it is used. + + +## 'this' as global variable +If `this` is used alone, it refers to a global object. In browsers it refers to Window Object as Global Object. + +```javascript +var k = this; +console..log(k) + +/* Output + +Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …} + + */ + +``` + + ## 'this' in a function + +In JavaScript, by default the owner of the function is `this`. The value of this in a function refers to the object it belongs to. In below example, `this` refers to window object, so instead of printing '5' it refers to global value '10'. + +```javascript +var x =10; +function printX() { + var x = 5; + console.log(this.x) +} + +printX(); /* its like this.printX() or window.printX() */ + + +/* Output +10 /* this refers to global object so prints 10 */ + */ +``` + +## 'this' in function - strict mode + +if `use strict` mode is enabled, `this` don't refer to the global object by default. It gives `undefined` when a function is called without explicitly using `this` + +```javascript + +// setInterval This runs a code after specific interval of time till we stop the timer. +`use strict' +var x =10; +function printX() { + var x = 5; + console.log(this.x) +} +this.printX(); +printX(); + + +/* Output +10 // printX() called with this + Uncaught TypeError: Cannot read property 'x' of undefined // printX() called without this + */ + +``` + + ## 'this' in a method + +In JavaScript, `this` in a method refers to the object of which the method belongs to. In below example, the `printX` method belongs to person object. so `this` refers to person object. + +```javascript +var firstName = "John"; +var person = { + firstName: "Jenny", + printX : function() { + console.log(this.firstName) + } +} +person.printX(); + +/* Output + Jenny +*/ +``` + +## Explicit function binding +Calling `object A` method, using values of `object B` is called Explicit function binding. JavaScript provides two method `call()` and `apply()` + +For more details read on [call()](/JavaScript_Basics/call) and [apply()](/JavaScript_Basics/apply) . + + +```javascript +var personA = { + firstName: "Jenny", + printX : function() { + console.log(this.firstName) + } +} +var personB = { + firstName: "John" +} +personA.printX.call(personB); + +/* Output + John +*/ +``` \ No newline at end of file From a0136de55d3816267e6b6c259f3126056c56fe10 Mon Sep 17 00:00:00 2001 From: Swapnil Satish Shinde <37082605+Swap76@users.noreply.github.com> Date: Sun, 27 Oct 2019 19:23:25 +0530 Subject: [PATCH 57/93] Update this.md --- docs/JavaScript_Basics/this.md | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/docs/JavaScript_Basics/this.md b/docs/JavaScript_Basics/this.md index d38215f..0d9bedd 100644 --- a/docs/JavaScript_Basics/this.md +++ b/docs/JavaScript_Basics/this.md @@ -35,7 +35,7 @@ printX(); /* its like this.printX() or window.printX() */ /* Output 10 /* this refers to global object so prints 10 */ - */ +*/ ``` ## 'this' in function - strict mode @@ -43,7 +43,6 @@ printX(); /* its like this.printX() or window.printX() */ if `use strict` mode is enabled, `this` don't refer to the global object by default. It gives `undefined` when a function is called without explicitly using `this` ```javascript - // setInterval This runs a code after specific interval of time till we stop the timer. `use strict' var x =10; @@ -54,12 +53,10 @@ function printX() { this.printX(); printX(); - /* Output 10 // printX() called with this Uncaught TypeError: Cannot read property 'x' of undefined // printX() called without this */ - ``` ## 'this' in a method @@ -102,4 +99,4 @@ personA.printX.call(personB); /* Output John */ -``` \ No newline at end of file +``` From c91d0ec3b8216a565b80fe69cfb63a1f6ffcc9b8 Mon Sep 17 00:00:00 2001 From: Swap76 Date: Mon, 28 Oct 2019 08:25:05 +0530 Subject: [PATCH 58/93] Styling in Object updated --- docs/JavaScript_Basics/objects.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/docs/JavaScript_Basics/objects.md b/docs/JavaScript_Basics/objects.md index ccdf9be..f4818c5 100644 --- a/docs/JavaScript_Basics/objects.md +++ b/docs/JavaScript_Basics/objects.md @@ -26,5 +26,11 @@ Objects are variables too. But objects can contain many values. The values are written as name : value pairs (name and value separated by a colon). Example: -var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; - +```js +var person = { + firstName:"John", + lastName:"Doe", + age:50, + eyeColor:"blue" + }; +``` \ No newline at end of file From ed21989edcf16563f8c5fb931563f9b52ca944ae Mon Sep 17 00:00:00 2001 From: Nigel Yong <23243585+niyonx@users.noreply.github.com> Date: Sun, 27 Oct 2019 23:32:28 -0400 Subject: [PATCH 59/93] Created includes.js for includes method --- JavaScript_Basics/includes.js | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 JavaScript_Basics/includes.js diff --git a/JavaScript_Basics/includes.js b/JavaScript_Basics/includes.js new file mode 100644 index 0000000..c932730 --- /dev/null +++ b/JavaScript_Basics/includes.js @@ -0,0 +1,7 @@ +// Find substring in a string. Similar to contains in java. + +// Defining dummy variables +var string = "foo", substring1 = "oo", substring2="a"; + +console.log(string.includes(substring1)); // true +console.log(string.includes(substring2)); // false From 38ac7906ed97d10434211795a3e3b40eee1e4650 Mon Sep 17 00:00:00 2001 From: mtrigueros Date: Sun, 27 Oct 2019 22:05:08 -0600 Subject: [PATCH 60/93] Add exercise question for array methods in javascript --- docs/Exercise/JavaScript_Basics/array_method.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 docs/Exercise/JavaScript_Basics/array_method.md diff --git a/docs/Exercise/JavaScript_Basics/array_method.md b/docs/Exercise/JavaScript_Basics/array_method.md new file mode 100644 index 0000000..87869e5 --- /dev/null +++ b/docs/Exercise/JavaScript_Basics/array_method.md @@ -0,0 +1,4 @@ +1. **Create** an array called `numbers` +2. **Create** an empty array called `newArray` +3. **Iterate** through each element in the numbers array +4. **Alter** any element and put the altered value into the new array \ No newline at end of file From 109df800a33110c0b40b574d21c8bc1b2404e2c3 Mon Sep 17 00:00:00 2001 From: garrowp Date: Sun, 27 Oct 2019 22:50:16 -0600 Subject: [PATCH 61/93] Create if_else.md Created an exercise for if-else, see #254 --- docs/Exercise/JavaScript_Basics/if_else.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 docs/Exercise/JavaScript_Basics/if_else.md diff --git a/docs/Exercise/JavaScript_Basics/if_else.md b/docs/Exercise/JavaScript_Basics/if_else.md new file mode 100644 index 0000000..71bb0f9 --- /dev/null +++ b/docs/Exercise/JavaScript_Basics/if_else.md @@ -0,0 +1,13 @@ +**Write** a JavaScript program to determine if a number is positive, negative, or zero. + +**Example Input**: + +6 +0 +-20 + +**Expected Output**: + +"positive" +"zero" +"negative" From 63fd49aa8ce99c363182b33453470b375676c709 Mon Sep 17 00:00:00 2001 From: Andrew McAuliffe Date: Mon, 28 Oct 2019 00:29:49 -0500 Subject: [PATCH 62/93] Add object examples This commit adds object function property and property manipulation examples. --- docs/JavaScript_Basics/objects.md | 45 ++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/docs/JavaScript_Basics/objects.md b/docs/JavaScript_Basics/objects.md index f4818c5..eb0977b 100644 --- a/docs/JavaScript_Basics/objects.md +++ b/docs/JavaScript_Basics/objects.md @@ -33,4 +33,47 @@ var person = { age:50, eyeColor:"blue" }; -``` \ No newline at end of file +``` + +A function can be used as an object property: +```JavaScript +const objectWithFunction = { + name: "Swapnil", // We can omit the " " in keys but for string values it is necessary + rollno: 76, // We assign any type to keys + getfull: function () { // Don't use arrow function here as arrow functions don't have this property + console.log(`${this.name} ${this.rollno}`); + } +}; + +console.log(objectWithFunction); +// Output { name: 'Swapnil', rollno: 76, getfull: [Function: getfull] } + +objectWithFunction.getfull(); // Output Swapnil 76 +``` + +Object property values can be changed using dot notation: +```JavaScript +const a = { + name: "Swapnil", // We can omit the " " in keys but for string values it is necessary + rollno: 76 // We assign any type to keys +}; + +a.name = "Swapnil Satish Shinde"; // This way we can change a particular property of object + +console.log(a.name); // This way you can get the value of particular element +// Output Swapnil Satish Shinde +``` + +New properties can be added to an object after its creation: +```JavaScript +const canAddValue = { // This is normal object having 2 keys name and rollno + name: "Swapnil", + rollno: 76 +}; + +// We can add the keys we want any time into the object by directly assigning value to it +canAddValue.branch = "Computer"; + +console.log(canAddValue); +// Output { name: 'Swapnil', rollno: 76, branch: 'Computer' } +``` From 7048cddb226c229e636a462638c53dc5607264c1 Mon Sep 17 00:00:00 2001 From: Anuradha <32791199+anuk79@users.noreply.github.com> Date: Mon, 28 Oct 2019 11:37:52 +0530 Subject: [PATCH 63/93] revert deleting of higher_order_functions.js --- JavaScript_Basics/higher_order_functions.js | 46 +++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 JavaScript_Basics/higher_order_functions.js diff --git a/JavaScript_Basics/higher_order_functions.js b/JavaScript_Basics/higher_order_functions.js new file mode 100644 index 0000000..7708830 --- /dev/null +++ b/JavaScript_Basics/higher_order_functions.js @@ -0,0 +1,46 @@ +// HIGHER ORDER FUNCTIONS FOR ARRAYS + +// the arrays in javascript have 3 main HOF +// SUCH MAP, FILTER AND REDUCE + +const list = [1, 2, 3, 4, 5]; + +// map + +// the map function iterate over an a list and return a new array +// the map receive a function that receives 3 arguments +// 1st arg is one by one the items in the list like "1" or "2" in the list example +// 2nc arg is the index of the item in the list (for "1" is 0, etc...) +// 3rd arg is the entire list [1,2,3,4,5] + +const newList = list.map(function (item, index, list) { + return item * 2; +}); + +// this return a new array with new values like [2, 4, 6, 8, 10] + +// filter + +// the filter function iterate over an a list and return a new array based on a condition +// the filter receive a function that receives 3 arguments +// 1st arg is one by one the items in the list like "1" or "2" in the list example +// 2nc arg is the index of the item in the list (for "1" is 0, etc...) +// 3rd arg is the entire list [1,2,3,4,5] + +const newListFiltered = list.map(function (item, index, list) { + // condition to return a value for the new array + return item % 2 === 0; +}) + +// this return a new array with some filtered values based on a condition [2, 4] +// because 2 and 4 the recidus is 0 + +// sort + +// the sort function iterate over an a list and return a new array sorted based on a comparefunction +// if you don't add a function sort numbers in incremental way and text in alphabetic way +// the sort receive a function that receives 3 arguments + + [1, 10, 2, 21].sort(); + +// this return [1, 10, 2, 21] From 89f68352100b02e8370ef86bdb290d1e2b263f28 Mon Sep 17 00:00:00 2001 From: Daniel Na Date: Sun, 27 Oct 2019 23:20:36 -0700 Subject: [PATCH 64/93] if-else question added --- docs/Exercise/JavaScript_Basics/if-else.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 docs/Exercise/JavaScript_Basics/if-else.md diff --git a/docs/Exercise/JavaScript_Basics/if-else.md b/docs/Exercise/JavaScript_Basics/if-else.md new file mode 100644 index 0000000..a1ea98a --- /dev/null +++ b/docs/Exercise/JavaScript_Basics/if-else.md @@ -0,0 +1 @@ +Look up how to get the current time in Javascript. Based on this, create a series of if-else statements that will check against the current time and print either: "Good morning!" if it's from 6:00am-12:00pm, "Good afternoon!" if the time is between 12:00pm - 6:00pm, "Good evening!" if the time is from 6:00pm to Midnight, and "Good night!" if the time is from Midnight to 6:00am. If these instructions are ambiguous, use your judgement to solve the problem as you see fit. Note: Checking multiple boolean expressions is something we have yet to learn. You can wait until class Tuesday for us to go over them, however I encourage you to look them up in advanced: Check out the &&(and) || (or) operators to understand how to combine multiple boolean checks. \ No newline at end of file From 6b4169fbf324ca4197e49f458a8425ccef7c35bd Mon Sep 17 00:00:00 2001 From: "Andy (Cihang Hu)" Date: Sun, 27 Oct 2019 23:28:54 -0700 Subject: [PATCH 65/93] Create looping_objects.md Add two exercises for loop objects in JavaSCript --- .../JavaScript_Basics/looping_objects.md | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 docs/Exercise/JavaScript_Basics/looping_objects.md diff --git a/docs/Exercise/JavaScript_Basics/looping_objects.md b/docs/Exercise/JavaScript_Basics/looping_objects.md new file mode 100644 index 0000000..4e44613 --- /dev/null +++ b/docs/Exercise/JavaScript_Basics/looping_objects.md @@ -0,0 +1,32 @@ +1. Given an object +```js +const person = { + name: 'John Doe', + age: 26, + gender: 'Male' +} +``` +Write code to iterate through `person` object and output something like +``` +// person.name = John Doe +// person.age = 26 +// person.gender = Male +``` + +2. Given the following code +```js +function Dog (age) { + this.age = age; +} + +Dog.prototype = { + bark: () => console.log('woof') +} + +const dog = new Dog(2); +``` + +Write code to iterate through `dog` object and output something like +``` +// dog.age = 2 +``` From 4cfe5e12ed733663e9e540a47042df82e2679232 Mon Sep 17 00:00:00 2001 From: "Andy (Cihang Hu)" Date: Sun, 27 Oct 2019 23:45:55 -0700 Subject: [PATCH 66/93] Create higher_order_functions.md --- docs/Exercise/JavaScript_Basics/higher_order_functions.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 docs/Exercise/JavaScript_Basics/higher_order_functions.md diff --git a/docs/Exercise/JavaScript_Basics/higher_order_functions.md b/docs/Exercise/JavaScript_Basics/higher_order_functions.md new file mode 100644 index 0000000..6721b65 --- /dev/null +++ b/docs/Exercise/JavaScript_Basics/higher_order_functions.md @@ -0,0 +1,5 @@ +1. Write an function `square` which takes an array as input and return a new array use [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) method. +For example, `square([1,2,3,4])` should return `[1,4,9,16]`. + +2. Write an function `getOdd` which takes an array of number as input and return a new array contains only odd number use [filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) method. +For example, `getOdd([1,2,3,4,5])` should return `[1,3,5]`. From 20814c1ba79eff10d00cf72fbd1a71197921c7b8 Mon Sep 17 00:00:00 2001 From: bharath-b06 Date: Mon, 28 Oct 2019 12:35:25 +0530 Subject: [PATCH 67/93] added an exercise for for-each --- docs/Exercise/JavaScript_Basics/for_each.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 docs/Exercise/JavaScript_Basics/for_each.md diff --git a/docs/Exercise/JavaScript_Basics/for_each.md b/docs/Exercise/JavaScript_Basics/for_each.md new file mode 100644 index 0000000..b2c7c90 --- /dev/null +++ b/docs/Exercise/JavaScript_Basics/for_each.md @@ -0,0 +1,3 @@ +**Write** a Javascript program to iterate through all the elements of an arrray, your code should output the squares of each element in the array. + +`arr` = [21,32,37,13] From e5df676c176c8b0aa25a9cfb653752f89a5bd308 Mon Sep 17 00:00:00 2001 From: Swap76 Date: Mon, 28 Oct 2019 12:39:58 +0530 Subject: [PATCH 68/93] Moved solution of exercise to solutions folder --- .../Solution/JavaScript_Basics}/exercise_1_using_arrays.js | 0 .../Solution/JavaScript_Basics}/exercise_1_using_classes.js | 0 .../Solution/JavaScript_Basics}/exercise_1_using_object.js | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename {JavaScript_Basics => docs/Solution/JavaScript_Basics}/exercise_1_using_arrays.js (100%) rename {JavaScript_Basics => docs/Solution/JavaScript_Basics}/exercise_1_using_classes.js (100%) rename {JavaScript_Basics => docs/Solution/JavaScript_Basics}/exercise_1_using_object.js (100%) diff --git a/JavaScript_Basics/exercise_1_using_arrays.js b/docs/Solution/JavaScript_Basics/exercise_1_using_arrays.js similarity index 100% rename from JavaScript_Basics/exercise_1_using_arrays.js rename to docs/Solution/JavaScript_Basics/exercise_1_using_arrays.js diff --git a/JavaScript_Basics/exercise_1_using_classes.js b/docs/Solution/JavaScript_Basics/exercise_1_using_classes.js similarity index 100% rename from JavaScript_Basics/exercise_1_using_classes.js rename to docs/Solution/JavaScript_Basics/exercise_1_using_classes.js diff --git a/JavaScript_Basics/exercise_1_using_object.js b/docs/Solution/JavaScript_Basics/exercise_1_using_object.js similarity index 100% rename from JavaScript_Basics/exercise_1_using_object.js rename to docs/Solution/JavaScript_Basics/exercise_1_using_object.js From 894968325d574fa27e9ce113a450d8d37842bbe5 Mon Sep 17 00:00:00 2001 From: Swap76 Date: Mon, 28 Oct 2019 12:44:11 +0530 Subject: [PATCH 69/93] Moved Solutions into Exercise --- docs/Exercise/JavaScript_Basics/object.md | 109 ++++++++++++++++++ .../exercise_1_using_arrays.js | 23 ---- .../exercise_1_using_classes.js | 46 -------- .../exercise_1_using_object.js | 25 ---- 4 files changed, 109 insertions(+), 94 deletions(-) delete mode 100644 docs/Solution/JavaScript_Basics/exercise_1_using_arrays.js delete mode 100644 docs/Solution/JavaScript_Basics/exercise_1_using_classes.js delete mode 100644 docs/Solution/JavaScript_Basics/exercise_1_using_object.js diff --git a/docs/Exercise/JavaScript_Basics/object.md b/docs/Exercise/JavaScript_Basics/object.md index 88e1e0e..ec1189d 100644 --- a/docs/Exercise/JavaScript_Basics/object.md +++ b/docs/Exercise/JavaScript_Basics/object.md @@ -5,3 +5,112 @@ 3. **Implement** a class `Student`, which should contain his/her `first name`, `last name`, `age`, `college` and `bio`. 4. Encapsulate *(with getters and setters)* the user details **using class members**. + +# Answer + +### Solution Using Object +```js +const student = { + firstName: "Swapnil", + lastName: "Shinde", + age: 19, + college: "SIES", + bio: "Web developer" +}; + +getFullName = () => { + return `${student.firstName} ${student.lastName}`; +}; + +getBio = () => { + return student.bio; +}; + +getAllDetails = () => { + return `My name is ${student.firstName} ${student.lastName} \nMy age is ${student.age} \nMy college is ${student.college}, I am ${student.bio}.`; +}; + +console.log(getFullName()); // Output Swapnil Shinde + +console.log(getBio()); // Output Web developer + +console.log(getAllDetails()); // Output My name is Swapnil Shinde. My age is 19. My college is SIES, I am Web developer. +``` + +### Solution Using Classes +```js +class Student { + // Created the constructor for student + constructor (firstName, lastName, age, college, bio) { + this.firstName = firstName; + this.lastName = lastName; + this.age = age; + this.college = college; + this.bio = bio; + } + + // This method returns combined firstname and lastname + getFullName () { + return (`${this.firstName} ${this.lastName}`); + } + + // This method returns bio + getBio () { + return (`${this.bio}`); + } + + // This method returns All details + getAllDetails () { + return (`My name is ${this.firstName} ${this.lastName} \nMy age is ${this.age} \nMy college is ${this.college}, I am ${this.bio}.`); + } +} + +const Swapnil = new Student("Swapnil", "Shinde", 19, "SIES", "Web Developer"); // Created object with arguments + +console.log(Swapnil.getFullName()); // Output Swapnil Shinde + +console.log(Swapnil.getBio()); // Output Web Developer + +console.log(Swapnil.getAllDetails()); // Output My name is Swapnil Shinde. My age is 19. My college is SIES, I am Web Developer. + +console.log(Swapnil); // This returns the object only +/* + Output + +Student { + firstName: 'Swapnil', + lastName: 'Shinde', + age: 19, + college: 'SIES', + bio: 'Web Developer' +} +*/ +``` + +### Solution Using Arrays + +```js +const array = [1, 0.16, "Random", function () { + console.log("this is function in an array"); +}, { Key: "Answer" }, false]; + +console.log("Array can contain anything"); +console.log(array); +// add last +array.push("add last"); +console.log(array); +// remove last +array.pop(); +console.log(array); +// add first +array.shift("add first"); +console.log(array); + +// remove first +array.unshift(); +console.log(array); +// this element is function +array[2](); +// object inside array +console.log(array[3].Key); +``` \ No newline at end of file diff --git a/docs/Solution/JavaScript_Basics/exercise_1_using_arrays.js b/docs/Solution/JavaScript_Basics/exercise_1_using_arrays.js deleted file mode 100644 index f7788fd..0000000 --- a/docs/Solution/JavaScript_Basics/exercise_1_using_arrays.js +++ /dev/null @@ -1,23 +0,0 @@ -const array = [1, 0.16, "Random", function () { - console.log("this is function in an array"); -}, { Key: "Answer" }, false]; - -console.log("Array can contain anything"); -console.log(array); -// add last -array.push("add last"); -console.log(array); -// remove last -array.pop(); -console.log(array); -// add first -array.shift("add first"); -console.log(array); - -// remove first -array.unshift(); -console.log(array); -// this element is function -array[2](); -// object inside array -console.log(array[3].Key); \ No newline at end of file diff --git a/docs/Solution/JavaScript_Basics/exercise_1_using_classes.js b/docs/Solution/JavaScript_Basics/exercise_1_using_classes.js deleted file mode 100644 index 4866065..0000000 --- a/docs/Solution/JavaScript_Basics/exercise_1_using_classes.js +++ /dev/null @@ -1,46 +0,0 @@ -class Student { - // Created the constructor for student - constructor (firstName, lastName, age, college, bio) { - this.firstName = firstName; - this.lastName = lastName; - this.age = age; - this.college = college; - this.bio = bio; - } - - // This method returns combined firstname and lastname - getFullName () { - return (`${this.firstName} ${this.lastName}`); - } - - // This method returns bio - getBio () { - return (`${this.bio}`); - } - - // This method returns All details - getAllDetails () { - return (`My name is ${this.firstName} ${this.lastName} \nMy age is ${this.age} \nMy college is ${this.college}, I am ${this.bio}.`); - } -} - -const Swapnil = new Student("Swapnil", "Shinde", 19, "SIES", "Web Developer"); // Created object with arguments - -console.log(Swapnil.getFullName()); // Output Swapnil Shinde - -console.log(Swapnil.getBio()); // Output Web Developer - -console.log(Swapnil.getAllDetails()); // Output My name is Swapnil Shinde. My age is 19. My college is SIES, I am Web Developer. - -console.log(Swapnil); // This returns the object only -/* - Output - -Student { - firstName: 'Swapnil', - lastName: 'Shinde', - age: 19, - college: 'SIES', - bio: 'Web Developer' -} -*/ \ No newline at end of file diff --git a/docs/Solution/JavaScript_Basics/exercise_1_using_object.js b/docs/Solution/JavaScript_Basics/exercise_1_using_object.js deleted file mode 100644 index e400518..0000000 --- a/docs/Solution/JavaScript_Basics/exercise_1_using_object.js +++ /dev/null @@ -1,25 +0,0 @@ -const student = { - firstName: "Swapnil", - lastName: "Shinde", - age: 19, - college: "SIES", - bio: "Web developer" -}; - -getFullName = () => { - return `${student.firstName} ${student.lastName}`; -}; - -getBio = () => { - return student.bio; -}; - -getAllDetails = () => { - return `My name is ${student.firstName} ${student.lastName} \nMy age is ${student.age} \nMy college is ${student.college}, I am ${student.bio}.`; -}; - -console.log(getFullName()); // Output Swapnil Shinde - -console.log(getBio()); // Output Web developer - -console.log(getAllDetails()); // Output My name is Swapnil Shinde. My age is 19. My college is SIES, I am Web developer. \ No newline at end of file From 13f1bc64fc5aec79d1ab91b292fa141378ed9cc1 Mon Sep 17 00:00:00 2001 From: Swapnil Satish Shinde <37082605+Swap76@users.noreply.github.com> Date: Mon, 28 Oct 2019 13:24:21 +0530 Subject: [PATCH 70/93] Update and rename if-else.md to if_else.md --- docs/Exercise/JavaScript_Basics/if-else.md | 1 - docs/Exercise/JavaScript_Basics/if_else.md | 6 ++++++ 2 files changed, 6 insertions(+), 1 deletion(-) delete mode 100644 docs/Exercise/JavaScript_Basics/if-else.md create mode 100644 docs/Exercise/JavaScript_Basics/if_else.md diff --git a/docs/Exercise/JavaScript_Basics/if-else.md b/docs/Exercise/JavaScript_Basics/if-else.md deleted file mode 100644 index a1ea98a..0000000 --- a/docs/Exercise/JavaScript_Basics/if-else.md +++ /dev/null @@ -1 +0,0 @@ -Look up how to get the current time in Javascript. Based on this, create a series of if-else statements that will check against the current time and print either: "Good morning!" if it's from 6:00am-12:00pm, "Good afternoon!" if the time is between 12:00pm - 6:00pm, "Good evening!" if the time is from 6:00pm to Midnight, and "Good night!" if the time is from Midnight to 6:00am. If these instructions are ambiguous, use your judgement to solve the problem as you see fit. Note: Checking multiple boolean expressions is something we have yet to learn. You can wait until class Tuesday for us to go over them, however I encourage you to look them up in advanced: Check out the &&(and) || (or) operators to understand how to combine multiple boolean checks. \ No newline at end of file diff --git a/docs/Exercise/JavaScript_Basics/if_else.md b/docs/Exercise/JavaScript_Basics/if_else.md new file mode 100644 index 0000000..bdddb8f --- /dev/null +++ b/docs/Exercise/JavaScript_Basics/if_else.md @@ -0,0 +1,6 @@ +### Look up how to get the current time in Javascript. Based on this, create a series of if-else statements that will check against the current time and print either: + +- "Good morning!" if it's from 6:00am-12:00pm +- "Good afternoon!" if the time is between 12:00pm - 6:00pm +- "Good evening!" if the time is from 6:00pm to Midnight +- "Good night!" if the time is from Midnight to 6:00am. From 35648ec572d8d4677a935cd046edd78257a09778 Mon Sep 17 00:00:00 2001 From: Swapnil Satish Shinde <37082605+Swap76@users.noreply.github.com> Date: Mon, 28 Oct 2019 13:26:52 +0530 Subject: [PATCH 71/93] Update looping_objects.md --- docs/Exercise/JavaScript_Basics/looping_objects.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/Exercise/JavaScript_Basics/looping_objects.md b/docs/Exercise/JavaScript_Basics/looping_objects.md index 4e44613..323e3ef 100644 --- a/docs/Exercise/JavaScript_Basics/looping_objects.md +++ b/docs/Exercise/JavaScript_Basics/looping_objects.md @@ -7,10 +7,10 @@ const person = { } ``` Write code to iterate through `person` object and output something like -``` -// person.name = John Doe -// person.age = 26 -// person.gender = Male +```js +person.name = John Doe +person.age = 26 +person.gender = Male ``` 2. Given the following code @@ -27,6 +27,6 @@ const dog = new Dog(2); ``` Write code to iterate through `dog` object and output something like -``` -// dog.age = 2 +```js +dog.age = 2 ``` From dabb497fb24227eaedfbdd0c16cf2ed8f03c3ba4 Mon Sep 17 00:00:00 2001 From: Ahmed-Elbessfy Date: Mon, 28 Oct 2019 10:07:24 +0200 Subject: [PATCH 72/93] add forEach tutorial with 2 examples - explain what is forEach method - add 2 different examples of using forEach method --- JavaScript_Basics/forEach.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 JavaScript_Basics/forEach.js diff --git a/JavaScript_Basics/forEach.js b/JavaScript_Basics/forEach.js new file mode 100644 index 0000000..d277989 --- /dev/null +++ b/JavaScript_Basics/forEach.js @@ -0,0 +1,29 @@ +// JavaScript Array forEach() Method + +/* +-- forEach() method takes a callback function then loops through all the array elements and execute the callback function once for each array element +-- forEach() method DOES NOT modify the array and unlike map() method, forEach() DOES NOT return a new array +*/ +// assume we have an array of numbers and we need to get square of each number +const numbers = [5, 4, 6, 12, 23, 1, 72], squares = []; + +[5, 4, 6, 12, 23, 1, 72].forEach(n => { + squares.push(n * n) +}); + +console.log(squares); + +// expected output: Array [25, 16, 36, 144, 529, 1, 5184] + +/* +-- Another example using index of elements in the callback function +-- In this example, we create an Object from an Array +*/ +const users = ['John', 'Sally', 'Brad', 'Jack'], usersObj = {} + +users.forEach((user, index) => { + usersObj[index] = user +}) + +console.log(usersObj) +// expected output : Object {0: "John", 1: "Sally", 2: "Brad", 3: "Jack"} From 76f6942ba24400353b6a57f48448d09eade99344 Mon Sep 17 00:00:00 2001 From: Swap76 Date: Mon, 28 Oct 2019 13:41:43 +0530 Subject: [PATCH 73/93] Moved higher order components --- JavaScript_Basics/higher_order_functions.md | 100 ------------------ .../higher_order_functions.md | 98 ++++++++++++++--- 2 files changed, 83 insertions(+), 115 deletions(-) delete mode 100644 JavaScript_Basics/higher_order_functions.md diff --git a/JavaScript_Basics/higher_order_functions.md b/JavaScript_Basics/higher_order_functions.md deleted file mode 100644 index 9643614..0000000 --- a/JavaScript_Basics/higher_order_functions.md +++ /dev/null @@ -1,100 +0,0 @@ -## HIGHER ORDER FUNCTIONS - -A **Higher Order function** or **HOF** is a function that receives a function as an argument or returns the function as output. - -There are some built-in HOF for Arrays in Javascript, such as - - *Array.prototype.map* - - *Array.prototype.filter* - - *Array.prototype.reduce*. - -Let's understand each of these through examples. - -We will use the below array `list` as the base array to operate over. - -``` - const list = [1, 2, 3, 4, 5]; -``` - -## 1. map - - - The **map** function iterates over an input array and returns a new array. - - It does not change the original array, but creates a new array. - - The map receives a callback function as its argument. This callback function receives 3 arguments - - 1st arg is the **elememt** of the array, like 1, 2, 3, 4, 5 - - 2nd arg is the **index** of the item in the list (index for first element is 0, and so on) - - 3rd arg is the original array [1,2,3,4,5] on which map is being called - -``` - const newList = list.map(function (item, index, list) { - return item * 2; - }); - - console.log(list); // prints [1, 2, 3, 4, 5] - console.log(newList); // prints [2, 4, 6, 8, 10] -``` - - -## 2. filter - - - the **filter** function iterates over an input array and returns a new array based on a condition - - the filter receive a callnack function as its argument. This callback functions receives 3 arguments: - - 1st arg is the **element** in the list like "1" or "2" in the list example - - 2nd arg is the **index** of the item in the list (index for first element is 0, and so on) - - 3rd arg is the original array [1,2,3,4,5] on which filter is being called - - ``` - // this filtered list will contain only even numbers - - const newListFiltered = list.filter(function (item, index, list) { - // filter will return the value if it satisfies the below condition - return item % 2 === 0; - }); - - console.log(list); // prints [1, 2, 3, 4, 5] - console.log(newList); // prints [2, 4] - -``` - -## 3. reduce - - - the **reduce** function iterates over an input array and returns a single output value - - it receives two arguments: - - a callback function, also called as **reducer** function - - an **initialValue** (this is optional parameter) - - the reducer function accepts four parameters: - - 1st arg is **accumulator** which contains the accumulated value which will be returned when the array is reduced. - If initalvalue is provided, accumulator will be equal to initialvalue, else it will be equal to the first element in the array - - 2nd arg is **currentValue** which points to the current value of the array which is being iterated over. - If initalvalue is provided, currentValue will be equal to the first element in the array, else it will be equal to the second element in the array - - 3rd arg is **index** which contains the index of the currentValue in the input array - - 4th arg is the **sourceArray** which is the input array on which reduce is called - -``` -// Example 1 -// this will return sum of all items in list. here, there is no initialvalue provided - -const sumOfListItems = list.reduce(function(accumulator, currentValue) { - return accumulator + currentValue; -}); - -console.log(list); // prints [1, 2, 3, 4, 5] -console.log(sumOfListItems); // prints 15 -``` - -``` -// Example 2 -// this will return sum of all items in list. here, the initialvalue is provided as 20 - -const newSumOfListItems = list.reduce(function(accumulator, currentValue) { - return accumulator + currentValue; -}, 20); - -console.log(list); // prints [1, 2, 3, 4, 5] -console.log(newSumOfListItems); // prints 35 (the sum of list items is 15, and the initial value was 20, so, 20 + 15 = 35) -``` - - - - - - diff --git a/docs/JavaScript_Basics/higher_order_functions.md b/docs/JavaScript_Basics/higher_order_functions.md index 84e605a..77a718a 100644 --- a/docs/JavaScript_Basics/higher_order_functions.md +++ b/docs/JavaScript_Basics/higher_order_functions.md @@ -1,26 +1,94 @@ -# Higher Order Functions +## HIGHER ORDER FUNCTIONS -Higher-order functions are functions that take other functions as arguments or return functions as their results. +A **Higher Order function** or **HOF** is a function that receives a function as an argument or returns the function as output. -Taking an other function as an argument is often referred as a callback function, because it is called back by the higher-order function. This is a concept that Javascript uses a lot. +There are some built-in HOF for Arrays in Javascript, such as + - *Array.prototype.map* + - *Array.prototype.filter* + - *Array.prototype.reduce*. -For example, the map function on arrays is a higher order function. The map function takes a function as an argument. +Let's understand each of these through examples. -```javascript -const list = [1, 2, 3, 4, 5 ]; -const double = n => n * 2 +We will use the below array `list` as the base array to operate over. -[1, 2, 3, 4].map(double) // [ 2, 4, 6, 8, 10 ] ``` + const list = [1, 2, 3, 4, 5]; +``` + +## 1. map + + - The **map** function iterates over an input array and returns a new array. + - It does not change the original array, but creates a new array. + - The map receives a callback function as its argument. This callback function receives 3 arguments + - 1st arg is the **elememt** of the array, like 1, 2, 3, 4, 5 + - 2nd arg is the **index** of the item in the list (index for first element is 0, and so on) + - 3rd arg is the original array [1,2,3,4,5] on which map is being called + +``` + const newList = list.map(function (item, index, list) { + return item * 2; + }); + + console.log(list); // prints [1, 2, 3, 4, 5] + console.log(newList); // prints [2, 4, 6, 8, 10] +``` + + +## 2. filter + + - the **filter** function iterates over an input array and returns a new array based on a condition + - the filter receive a callnack function as its argument. This callback functions receives 3 arguments: + - 1st arg is the **element** in the list like "1" or "2" in the list example + - 2nd arg is the **index** of the item in the list (index for first element is 0, and so on) + - 3rd arg is the original array [1,2,3,4,5] on which filter is being called + + ``` + // this filtered list will contain only even numbers + const newListFiltered = list.filter(function (item, index, list) { + // filter will return the value if it satisfies the below condition + return item % 2 === 0; + }); -Or, with an anonymous function: -```javascript -const newList = list.map(function (item, index, list) { - return item * 2; + console.log(list); // prints [1, 2, 3, 4, 5] + console.log(newList); // prints [2, 4] + +``` + +## 3. reduce + + - the **reduce** function iterates over an input array and returns a single output value + - it receives two arguments: + - a callback function, also called as **reducer** function + - an **initialValue** (this is optional parameter) + - the reducer function accepts four parameters: + - 1st arg is **accumulator** which contains the accumulated value which will be returned when the array is reduced. + If initalvalue is provided, accumulator will be equal to initialvalue, else it will be equal to the first element in the array + - 2nd arg is **currentValue** which points to the current value of the array which is being iterated over. + If initalvalue is provided, currentValue will be equal to the first element in the array, else it will be equal to the second element in the array + - 3rd arg is **index** which contains the index of the currentValue in the input array + - 4th arg is the **sourceArray** which is the input array on which reduce is called + +``` +// Example 1 +// this will return sum of all items in list. here, there is no initialvalue provided + +const sumOfListItems = list.reduce(function(accumulator, currentValue) { + return accumulator + currentValue; }); -// [ 2, 4, 6, 8, 10 ] + +console.log(list); // prints [1, 2, 3, 4, 5] +console.log(sumOfListItems); // prints 15 ``` -The map function is one of the many higher-order functions built into the language. sort, reduce, filter, forEach are other examples of higher-order functions built into the language. -Higher-order functions allows you to write simpler and more elegant code. +``` +// Example 2 +// this will return sum of all items in list. here, the initialvalue is provided as 20 + +const newSumOfListItems = list.reduce(function(accumulator, currentValue) { + return accumulator + currentValue; +}, 20); + +console.log(list); // prints [1, 2, 3, 4, 5] +console.log(newSumOfListItems); // prints 35 (the sum of list items is 15, and the initial value was 20, so, 20 + 15 = 35) +``` \ No newline at end of file From dcca6fee8d83426d3ea37367ee943d8e3082f4fb Mon Sep 17 00:00:00 2001 From: Musawar Bajwa Date: Mon, 28 Oct 2019 04:17:22 -0400 Subject: [PATCH 74/93] added string.md --- docs/Exercise/JavaScript_Basics/string.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 docs/Exercise/JavaScript_Basics/string.md diff --git a/docs/Exercise/JavaScript_Basics/string.md b/docs/Exercise/JavaScript_Basics/string.md new file mode 100644 index 0000000..e69de29 From 6edeb6f0ef0ed2caec886cb0b906d71d54204b9c Mon Sep 17 00:00:00 2001 From: Musawar Bajwa Date: Mon, 28 Oct 2019 04:23:46 -0400 Subject: [PATCH 75/93] added exercise questions --- docs/Exercise/JavaScript_Basics/string.md | 30 +++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/docs/Exercise/JavaScript_Basics/string.md b/docs/Exercise/JavaScript_Basics/string.md index e69de29..ffde5c2 100644 --- a/docs/Exercise/JavaScript_Basics/string.md +++ b/docs/Exercise/JavaScript_Basics/string.md @@ -0,0 +1,30 @@ +1. **Write** a JavaScript function to convert a string in abbreviated form. + +**Example** +Test Data : +console.log(abbrev_name("Musa Bajwa")); +"Musa B." + +2. **Write** a JavaScript function to concatenates a given string n times (default is 1). + +**Example** +Test Data : +console.log(repeat('Lol!')); +console.log(repeat('Lol!',2)); +console.log(repeat('Lol!',3)); +"Lol!" +"Lol!Lol!" +"Lol!Lol!Lol!" + +3. **Write** a JavaScript function to strip leading and trailing spaces from a string. + +**Example** + +Test Data : +console.log(strip('cool ')); +console.log(strip(' cool')); +console.log(strip(' cool ')); +Output : +"cool" +"cool" +"cool" From fb0e70b59f73ef251ca2a276049caa24d9ce803d Mon Sep 17 00:00:00 2001 From: Adel Date: Mon, 28 Oct 2019 09:52:01 +0100 Subject: [PATCH 76/93] Added exercise question for bitwise operators in JS --- docs/Exercise/JavaScript_Basics/bitwise_operator.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 docs/Exercise/JavaScript_Basics/bitwise_operator.md diff --git a/docs/Exercise/JavaScript_Basics/bitwise_operator.md b/docs/Exercise/JavaScript_Basics/bitwise_operator.md new file mode 100644 index 0000000..6c45cd7 --- /dev/null +++ b/docs/Exercise/JavaScript_Basics/bitwise_operator.md @@ -0,0 +1,12 @@ +**Write** a Javascript program to return the numerical value corresponding to the bitwise AND of two values + + +**For example** yourFunction(5, 13) will return 5 + +**Why ?** + +
    +
  • 5 binary representation is equal to 0101
  • +
  • 13 binary representation is equal to 1101
  • +
  • 0101 AND 1101 = 0101 = 5 in decimal representation
  • +
\ No newline at end of file From 57f0a416d210a5aaa3a22e96936e1629fe04ce66 Mon Sep 17 00:00:00 2001 From: thakkar7 Date: Mon, 28 Oct 2019 17:25:22 +0530 Subject: [PATCH 77/93] Excercise for spilce() and slice() --- .../JavaScript_Basics/Splice_&_Slice.md | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 docs/Exercise/JavaScript_Basics/Splice_&_Slice.md diff --git a/docs/Exercise/JavaScript_Basics/Splice_&_Slice.md b/docs/Exercise/JavaScript_Basics/Splice_&_Slice.md new file mode 100644 index 0000000..5ecfc2f --- /dev/null +++ b/docs/Exercise/JavaScript_Basics/Splice_&_Slice.md @@ -0,0 +1,31 @@ +Questions on Splice: + +1. **write** the code/function(use splice()) to add "Saturday" inside daysOfTheWeek in the correct position if: +var daysOfTheWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Sunday"] + +**Expected Output**: + var daysOfTheWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday","Saturday", "Sunday"] + +2. Given var monthsOfTheYear = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] , write a code/function(use splice()) to remove all months beginning from May and including May. + +**Expected Output**: +monthsOfTheYear = [ 'January', 'February', 'March', 'April' ] + +3. Given var numbers = ['1','2','2','4','5'] , remove the repeated number and insert '3' such that the numbers are in ascending order. + +**Expected Output**: +numbers = ['1','2','3','4','5'] + +4. Does splice() modify the original array? + +Questions on Slice: + +1. **write** the code/function(use slice()) to extract "Saturday" from daysOfTheWeek array: +var daysOfTheWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday","Saturday", "Sunday"] + +2. What will citrus contain? + + var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; + var citrus = fruits.slice(-3,-2); + +3. Does slice() modify the original array? From 8d39e0c18d7a1677c45d79613128e76dbc56b74e Mon Sep 17 00:00:00 2001 From: Your Name Date: Mon, 28 Oct 2019 21:31:17 +0600 Subject: [PATCH 78/93] generators --- JavaScript_Advance/generators.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 JavaScript_Advance/generators.js diff --git a/JavaScript_Advance/generators.js b/JavaScript_Advance/generators.js new file mode 100644 index 0000000..c8fedb1 --- /dev/null +++ b/JavaScript_Advance/generators.js @@ -0,0 +1,30 @@ +/* + Generators are functions with the possibility of exit and subsequent entry. + Their execution context (variable values) is preserved on subsequent inputs. +*/ + +// Let's consider a simple example: +function* myGenerator() { + yield 5 + yield 6 +} + +// In the example above, we wrote a simple generator function with asteriks(*) notation. +// Next to the yield we put values that are going to be extracted from the function +// In order to extract them one by one, we should at first call myGenerator function + +const gen = myGenerator() + +// The returning value of myGenerator function is a object-iterator. It has next() method +// Which we may call to get the current generator function value: + +gen.next().value // 5 + +// We get the value field of 'next' method's returning value, wich is an object as well +// Let's call this again in order to get the next value: + +gen.next().value // 6 + +// After we iterate through all the values, the next value is going to be undefined. + +gen.next().value // undefined. From 56a3d6c9e3f5b6376ae2633b9ffa13054f072d34 Mon Sep 17 00:00:00 2001 From: Juan Carlos Ceniceros Date: Mon, 28 Oct 2019 09:41:53 -0600 Subject: [PATCH 79/93] Add information about Classes --- docs/JavaScript_Basics/classes.md | 165 ++++++++++++++++++++++++++++++ 1 file changed, 165 insertions(+) diff --git a/docs/JavaScript_Basics/classes.md b/docs/JavaScript_Basics/classes.md index 87846ef..e4280c5 100644 --- a/docs/JavaScript_Basics/classes.md +++ b/docs/JavaScript_Basics/classes.md @@ -1 +1,166 @@ # Classes + +JavaScript is a programming language based on **prototypes**. +Classes represent an improvement to the prototype-based inheritance, and provides a clearer and simpler syntax for creating objects and a new way to deal with inheritance. + +> By definition, a class represents a template for the creation of objects, they provides the values ​​for the initial state (variables) and the implementation of the behavior (functions or methods). + +## How to define a class + +One way to define a class is through a **[class declaration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/class)**, the syntax is as follows: + +```javascript +class Student { +  builder() {...} + +  methodA() {...} + +  methodB() {...} +} +``` + +The reserved word `class` is used, followed by the class name (`Student`) + +It is also possible to define a class through a **[class expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/class)**, which can be **anonymous** or **named**, the syntax is as follows: + +```javascript +// Anonymous +const Student = class { +  builder() {...} + +  methodA() {...} + +  methodB() {...} +} + +// Named +const Student = class TheStudent { +  builder() { ... } + +  methodA() {...} + +  methodB() {...} +} +``` + +> The maiin difference between a **declaration** and an **expression** is that an **expression** creates a local scope; this means that the class name `TheStudent` will only be visible and usable within the class body. + +## How to instantiate a class + +To instantiate a class, use the reserved keyword [`new`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new), in this way a new object of the class type will be created. + +```javascript +let Bill = new Student(); +``` + +## Class body + +Within the body of the class, there is a special method called [`constructor`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor), this special method is called every time the class is instantiated to create a new object, and serves to define the initial state of the created object, for instance: + +```javascript +class Student { +  // onlyname; // This should not have let or const only in classes +  constructor(name, age) { // name and age are arguments given to object at the time of creation of object +    this.name = name; // This initializes the local variable as name passed in argument +    this.age = age; // This initializes the local variable as age passed in argument +  } +} + +const Swapnil = new Student("Swapnil", 19); // This way we can create new objects with arguments +``` + +The previous example defines a class of type `Student`, which receives two arguments in the constructor: `name` and `age`, both arguments will define the initial state of the object in two internal variables of the class (called in the same way) `this.name = name` and `this.age = age`. + +> The body of the class is all the code that is between the curly braces `{}`. + + +## Class methods + +Class methods are defined as functions within the body of the class: + +```javascript +class StudentInfo { +  // college = "SIES"; // This is allowed above ES7, ES8 +  constructor(name) {// name and age are arguments given to object at the time of creation of object +    this.name = name; // This initializes the local variable as name passed in argument +    this.college = "SIES"; // We want the College to be same for all students that's why it is declared outside of constructor +  } + +  getNameAndCollege() {// This is a method in Student +    console.log(`${this.name} ${this.college}`); +  } +} +``` + +In the example, a method called `getNameAndCollege` has been defined, to invoke the method it's necessary to instantiate the class to create an object, and then perform the method call, as follows: + +```javascript +const SwapnilInfo = new StudentInfo("Swapnil Bio"); +SwapnilInfo.getNameAndCollege(); +``` + +### Static methids + +It's also possible to define define **[static methods](https://developer.mozilla.org/en-US/docs/Glossary/Static_method)**, [static methods](https://developer.mozilla.org/en-US/docs/Glossary/Static_method) can be called without needing to instantiate the class, for example + +```javascript +class StudentInfo { +  constructor(name) { +    this.name = name; +    this.college = "SIES"; +  } + +  getNameAndCollege() { +    console.log(`${this.name} ${this.college}`); +  } + +  static getGreeting() { +    console.log('Hello world'!); +  } +} + +StudentInfo.getGreeting(); +// logs on console "Hello world!" +``` + +The `getGreeting` method will log `Hello world!` in the console without creating an object with the keyword [`new`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new). + +### Getters and Setters + +It's also possible to define two types of special methods: **[getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get)** and **[setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set)**. +**[Setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set)** help us to assign a value to a class variable, and since it is a function, it is possible to add extra logic in the method as necessary. +**[Getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get)** help us to retrieve the value of a class variable, and same as **[setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set)**, they allow us to define some extra logic inside the method as necessary. + +```javascript +class StudentInfo { + constructor() { } + +  set name(name) { +    this.name = name.charAt(0).toUpperCase() + name.slice(1); +  } + +  get name() { +    console.log (`${this.name}`); +  } + +  set college() { +    this.college = college.toUpperCase(); +  } + +  get college() { +    console.log (`${this.name}`); +  } + +  static getGreeting() { +    console.log ('Hello world'); +  } +} + +let BillInfo = new StudentInfo(); + +BillInfo.name = "bill"; +console.log (BillInfo.name); // Logs "Bill" because the extra logic capitalize the first letter + +BillInfo.college = "sies"; +console.log (BillInfo.college); // Logs "SIES" because the extra logic capitalizes the whole string +``` From 0735fc85bcc3bc46b6abd4837751e29e9dbf2bb9 Mon Sep 17 00:00:00 2001 From: Juan Carlos Ceniceros Date: Mon, 28 Oct 2019 09:47:42 -0600 Subject: [PATCH 80/93] Fix some typos --- docs/JavaScript_Basics/classes.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/JavaScript_Basics/classes.md b/docs/JavaScript_Basics/classes.md index e4280c5..67559e3 100644 --- a/docs/JavaScript_Basics/classes.md +++ b/docs/JavaScript_Basics/classes.md @@ -101,7 +101,7 @@ SwapnilInfo.getNameAndCollege(); ### Static methids -It's also possible to define define **[static methods](https://developer.mozilla.org/en-US/docs/Glossary/Static_method)**, [static methods](https://developer.mozilla.org/en-US/docs/Glossary/Static_method) can be called without needing to instantiate the class, for example +It's also possible to define define **[static methods](https://developer.mozilla.org/en-US/docs/Glossary/Static_method)**, [static methods](https://developer.mozilla.org/en-US/docs/Glossary/Static_method) can be called without needing to instantiate the class, for instance: ```javascript class StudentInfo { @@ -143,7 +143,7 @@ class StudentInfo {     console.log (`${this.name}`);   } -  set college() { +  set college(college) {     this.college = college.toUpperCase();   } From 2a350a39b61e4f61278df692e64b9b8a66195285 Mon Sep 17 00:00:00 2001 From: deveshp530 Date: Mon, 28 Oct 2019 08:51:59 -0700 Subject: [PATCH 81/93] added anagram problem --- .../Exercise/JavaScript_Basics/two_strings.md | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 docs/Exercise/JavaScript_Basics/two_strings.md diff --git a/docs/Exercise/JavaScript_Basics/two_strings.md b/docs/Exercise/JavaScript_Basics/two_strings.md new file mode 100644 index 0000000..a64f4e0 --- /dev/null +++ b/docs/Exercise/JavaScript_Basics/two_strings.md @@ -0,0 +1,23 @@ +# Anagram + +given two strings as parameters, check whether you can make the first string into the second string. Assume the two strings have equal length + +# Example 1 + +String1 = 'team' +String2 = 'mate' + +should return return true because you can rearrange team to make mate + +# Example 2 + +String1 = 'angered' +String2 = 'enraged' + +Returns true + +# Example 3 +String1 = 'evils' +String2 = 'vile' + +return false since the length of two strings are not equal \ No newline at end of file From d8e30004fa15505aeeaed0989b0ad43000ccfabe Mon Sep 17 00:00:00 2001 From: Remco Date: Mon, 28 Oct 2019 17:50:18 +0100 Subject: [PATCH 82/93] Create reduce.md One exercise that aims to replicate the given example in the explanation, but with a different set of items. One other exercise to demonstrate that the accumulator can be anything by expecting an object. --- docs/Exercise/JavaScript_Basics/reduce.md | 53 +++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 docs/Exercise/JavaScript_Basics/reduce.md diff --git a/docs/Exercise/JavaScript_Basics/reduce.md b/docs/Exercise/JavaScript_Basics/reduce.md new file mode 100644 index 0000000..05fd5ad --- /dev/null +++ b/docs/Exercise/JavaScript_Basics/reduce.md @@ -0,0 +1,53 @@ +# Reduce exercises + +The reduce method allows you to "reduce" the contents of an Array into one value. + +## 1. Sum of prices +Write a function that sums up the prices in a shopping cart. + +```js +const items = [ + { name: 'Flour', price: 1 }, + { name: 'Tomatos', price: 4 }, + { name: 'Cucumbers', price: 2 }, + { name: 'Cheese', price: 7 }, + { name: 'Wine', price: 14 }, +]; + +const expectedResult = 28; +``` + +## 2. Grades by course +Given a list of grades with their course, return an object where the key is the name of the course and the value is a list of the corresponding grades. + +```js +const grades = [ + { course: 'Algebra', test: 1, grade: 'A'}, + { course: 'Algebra', test: 2, grade: 'C'}, + { course: 'Algebra', test: 3, grade: 'B'}, + { course: 'Algorithms & Datastructures', test: 1, grade: 'D'}, + { course: 'Algorithms & Datastructures', test: 2, grade: 'C'}, + { course: 'Algorithms & Datastructures', test: 3, grade: 'C+'}, + { course: 'English', test: 1, grade: 'B'}, + { course: 'English', test: 2, grade: 'C'}, + { course: 'English', test: 3, grade: 'B'}, +]; + +const expectedResult = { + 'Algebra': [ + { course: 'Algebra', test: 1, grade: 'A'}, + { course: 'Algebra', test: 2, grade: 'C'}, + { course: 'Algebra', test: 3, grade: 'B'}, + ], + 'Algorithms & Datastructures': [ + { course: 'Algorithms & Datastructures', test: 1, grade: 'D'}, + { course: 'Algorithms & Datastructures', test: 2, grade: 'C'}, + { course: 'Algorithms & Datastructures', test: 3, grade: 'C+'}, + ], + 'English': [ + { course: 'English', test: 1, grade: 'B'}, + { course: 'English', test: 2, grade: 'C'}, + { course: 'English', test: 3, grade: 'B'}, + ] +}; +``` From 1d2e6e73e7e582ced16732f0d8fb3c13cbc378df Mon Sep 17 00:00:00 2001 From: Remco Date: Mon, 28 Oct 2019 17:52:25 +0100 Subject: [PATCH 83/93] Update reduce.md The argument-name `previous` might be confusing as it might make someone think that it is the previous element in the array. --- docs/JavaScript_Basics/reduce.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/JavaScript_Basics/reduce.md b/docs/JavaScript_Basics/reduce.md index 1828407..126802d 100644 --- a/docs/JavaScript_Basics/reduce.md +++ b/docs/JavaScript_Basics/reduce.md @@ -6,10 +6,10 @@ for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator. ```js - var pokemon = ["Squirtle", "Charmander", "Bulbasaur"]; + var pokemon = ["Squirtle", "Charmander", "Bulbasaur"]; - var pokeLength = pokemon.reduce(function(previous, current) { - return previous + current.length; + var pokeLength = pokemon.reduce(function(accumulator, current) { + return accumulator + current.length; }, 0); ``` **Output** From 08b3471c13e23658b040f5ae5e114aaedf73d90c Mon Sep 17 00:00:00 2001 From: Swapnil Satish Shinde <37082605+Swap76@users.noreply.github.com> Date: Tue, 29 Oct 2019 00:36:09 +0530 Subject: [PATCH 84/93] Update .gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 031716b..0ebf002 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ node_modules package-lock.json docs/_sidebar.md +.DS_Store From 295d280f5f4167277cd3390544acbb8d88bf0d5b Mon Sep 17 00:00:00 2001 From: lajacl Date: Mon, 28 Oct 2019 14:33:08 -0500 Subject: [PATCH 85/93] Add comparison operators exercises, closes #247 --- .../JavaScript_Basics/comparison_operators.md | 119 ++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 docs/Exercise/JavaScript_Basics/comparison_operators.md diff --git a/docs/Exercise/JavaScript_Basics/comparison_operators.md b/docs/Exercise/JavaScript_Basics/comparison_operators.md new file mode 100644 index 0000000..5d79d3e --- /dev/null +++ b/docs/Exercise/JavaScript_Basics/comparison_operators.md @@ -0,0 +1,119 @@ +### Comparison Operators Exercises + + +**1. Choose the correct comparison operator to alert true, when x is greater than y.** + + x = 10; + y = 5; + alert(x :white_medium_square: y); + +
+SHOW ANSWER +> +
+ + +**2. Choose the correct comparison operator to alert true, when x is equal to y.** + + x = 10; + y = 10; + alert(x :white_medium_square: y); + +
+SHOW ANSWER +== OR === +
+ + +**3. Choose the correct comparison operator to alert true, when x is NOT equal to y.** + + x = 10; + y = 5; + alert(x :white_medium_square: y); + +
+SHOW ANSWER +!= OR !== +
+ + +**4. Choose the correct conditional (ternary) operator to alert "Too young" if age is less than 18, otherwise alert "Old enough".** + + var age = n; + var votingStatus = (age :white_medium_square: 18) :white_medium_square: "Too young" :white_medium_square: "Old enough"; + alert(votingStatus); + +
+SHOW ANSWER +< ? : +
+ + +**5. Will the output for this statement be true or false?** + + console.log(1 == 1); + +
+SHOW ANSWER +true +
+ + +**6. Will the output for this statement be true or false?** + + console.log(1 == "1"); + +
+SHOW ANSWER +true +
+ + +**7. Will the output for this statement be true or false?** + + console.log(1 === 1); + +
+SHOW ANSWER +true +
+ + +**8. Will the output for this statement be true or false?** + + console.log(1 === "1"); + +
+SHOW ANSWER +false +
+ + +**9. Will the output for this statement be true or false?** + + console.log(1 != "1"); + +
+SHOW ANSWER +false +
+ + +**10. Will the output for this statement be true or false?** + + console.log(1 !== "1"); + +
+SHOW ANSWER +true +
+ + +**11. What will the value of color be after the following statemnt is executed?** + + var color = 5 < 10 ? "red" : "blue"; + +
+SHOW ANSWER +"red" +
From 243cdb43164bf4edddc9df7125c5f5f7a3ab7e25 Mon Sep 17 00:00:00 2001 From: Alex Lewis Date: Mon, 28 Oct 2019 15:53:44 -0400 Subject: [PATCH 86/93] (feat): Adds documentation for inheritance per issue 189 This adds documentation for prototypal inheritance and gives a basic example, class based example, and functional example. --- JavaScript_Basics/inheritance.js | 146 ++++++++++++++++++++++-- docs/JavaScript_Basics/inheritance.md | 154 ++++++++++++++++++++++++++ 2 files changed, 291 insertions(+), 9 deletions(-) diff --git a/JavaScript_Basics/inheritance.js b/JavaScript_Basics/inheritance.js index f88e0e9..9c148f6 100644 --- a/JavaScript_Basics/inheritance.js +++ b/JavaScript_Basics/inheritance.js @@ -1,6 +1,63 @@ -// common functions are combined in a class to have less repetition in code +/* +// ==================================== +// ==================================== +// BASE INHERITANCE EXAMPLE +// ==================================== +// ==================================== +*/ -class Animals { // Animal class is created where the legs are defined 4 +let baseObject = { + a: 1, + b: 2 +} + +// Create a new object with baseObject as the prototype for extendedObject. +let extendedObject = Object.create(baseObject); + +// Define property c to the baseObject. +// This is not explicitly defined on extendedObject +// but is accessible via the [[Prototype]]. +baseObject.c = 3; + +// It appears that there are no properties on extendedObject +console.log(extendedObject) // {} + +// a and b were defined on the baseObject. +// The property looks up the prototype chain +// until the properties of a and b exist or null is encountered for [[Prototype]]. +console.log(extendedObject.a); // 1 +console.log(extendedObject.b); // 2 + +// Define d on the extendedObject +// this is not accessible to the baseObject +// as the [[Prototype]] inherits one way +extendedObject.d = 4; + +// We now see property d on extendedObject +console.log(extendedObject) // { d: 4 } + +// c is accessible because the prototype chain is "alive". +// As properties are added or deleted, they can be accessed +// by objects that share a prototype +console.log(extendedObject.c); // 3 + +// d is accessible on extendedObject where it was defined +// but is inaccessible to baseObject and returns undefined +console.log(extendedObject.d); // 4 +console.log(baseObject.d) // undefined + + +/* +// ==================================== +// ==================================== +// CLASS BASED INHERITANCE EXAMPLE +// ==================================== +// ==================================== +*/ + +// Animal class is defined with a property of legs and a method of getLegs +// which returns the current value of legs. +class Animal { constructor () { this.legs = 4; } @@ -10,15 +67,20 @@ class Animals { // Animal class is created where the legs are defined 4 } } -class Dog extends Animals { +// Dog inherits the base properties from Animal +// and adds its own property of age (which is not shared with Animal) +// and the methods getAge and getSound +class Dog extends Animal { constructor (age) { - super(); // As We have to also call the constructor of Animals if constructor is empty this automatically calls the super + + // We need to call super in order to instantiate the constructor on Animal. + // If super is not called, then legs would be inaccessible to the Dog class + super(); this.age = age; } - // we have inherited the animals so getLegs method is also there in Dog class getSound () { - return ("Bhow"); + return ("Bow"); } getAge () { @@ -26,10 +88,76 @@ class Dog extends Animals { } } -const tommy = new Dog(10); // Created Object of Dog class + // Create a new Dog object passing in 10 for the age parameter +const tommy = new Dog(10); +// Since the Dog class extends the Animal class +// tommy has access to the getLegs method console.log(tommy.getLegs()); // Output 4 -console.log(tommy.getSound()); // Bhow +console.log(tommy.getSound()); // Bow + +console.log(tommy.getAge()); // 10 + + +/* +// ==================================== +// ==================================== +// Function Based Inheritance Example +// ==================================== +// ==================================== +*/ + +// This function defines the base "constructor" for us and is +// comparable to the constructor function found in the class example +function Animal() { + this.legs = 4; +} + +// Adding the getLegs property to the prototype ensures that +// it will be inherited to any objects that are created from Animal +Animal.prototype.getLegs = function() { + return this.legs; +} + +// The Dog function acts as the constructor, but where is the super call +// that we use to call the constructor from Animal? +function Dog(age) { + // the call method is similar in function to calling the super method in the + // super method in the class based example. In this case, it instantiates the + // legs property + Animal.call(this); + + this.age = age; +} + +// We set the prototype of Dog to the prototype of Animal +// in order to have access to the getLegs method that is +// defined on Animal's prototype +Dog.prototype = Object.create(Animal.prototype); + +// Dog is set as the constructor property on the Dog prototype to +// match the object structure of the class example +Dog.prototype.constructor = Dog; + +// Define getSound method +Dog.prototype.getSound = function() { + return ("Bow"); +} + +// Define getAge method +Dog.prototype.getAge = function() { + return (this.age); +} + +// create new Dog with age 10 +const tommy = new Dog(10); + +console.log(tommy); // Dog { legs: 4, age: 10 } + +// call getLegs that was inherited from Animal +console.log(tommy.getLegs()); // 4 -console.log(tommy.getAge()); // 10 \ No newline at end of file +// call both getSound and getAge that are defined on Dog +console.log(tommy.getSound()); // Bow +console.log(tommy.getAge()); // 10 diff --git a/docs/JavaScript_Basics/inheritance.md b/docs/JavaScript_Basics/inheritance.md index 1384947..70d63fc 100644 --- a/docs/JavaScript_Basics/inheritance.md +++ b/docs/JavaScript_Basics/inheritance.md @@ -1 +1,155 @@ # Inheritance + +## Prototypal Inheritance +Inheritance in JavaScript is based on the prototypal model. This means that each object has a private property called its prototype, denoted as `[[Prototype]]` in the ECMAScript standard. Each prototype object has is own prototype until a value of null is reached. This is commonly referred to as the prototype chain. (`null` has no prototype) + +This is best demonstrated through example: +```javascript +let baseObject = { + a: 1, + b: 2 +} + +// Create a new object with baseObject as the prototype for extendedObject. +let extendedObject = Object.create(baseObject); + +// Define property c to the baseObject. +// This is not explicitly defined on extendedObject +// but is accessible via the [[Prototype]]. +baseObject.c = 3; + +// It appears that there are no properties on extendedObject +console.log(extendedObject) // {} + +// a and b were defined on the baseObject. +// The property looks up the prototype chain +// until the properties of a and b exist or null is encountered for [[Prototype]]. +console.log(extendedObject.a); // 1 +console.log(extendedObject.b); // 2 + +// Define d on the extendedObject +// this is not accessible to the baseObject +// as the [[Prototype]] inherits one way +extendedObject.d = 4; + +// We now see property d on extendedObject +console.log(extendedObject) // { d: 4 } + +// c is accessible because the prototype chain is "alive". +// As properties are added or deleted, they can be accessed +// by objects that share a prototype +console.log(extendedObject.c); // 3 + +// d is accessible on extendedObject where it was defined +// but is inaccessible to baseObject and returns undefined +console.log(extendedObject.d); // 4 +console.log(baseObject.d) // undefined +``` + +## Inheritance with Classes +Classes in JavaScript provide "syntactic sugar" for the prototypal model. Let's again look at this via example: + +```javascript +// Animal class is defined with a property of legs and a method of getLegs +// which returns the current value of legs. +class Animal { + constructor () { + this.legs = 4; + } + + getLegs () { // Function for getting legs + return (this.legs); + } +} + +// Dog inherits the base properties from Animal +// and adds its own property of age (which is not shared with Animal) +// and the methods getAge and getSound +class Dog extends Animal { + constructor (age) { + + // We need to call super in order to instantiate the constructor on Animal. + // If super is not called, then legs would be inaccessible to the Dog class + super(); + this.age = age; + } + + getSound () { + return ("Bow"); + } + + getAge () { + return (this.age); + } +} + + // Create a new Dog object passing in 10 for the age parameter +const tommy = new Dog(10); + +// Since the Dog class extends the Animal class +// tommy has access to the getLegs method +console.log(tommy.getLegs()); // Output 4 + +console.log(tommy.getSound()); // Bow + +console.log(tommy.getAge()); // 10 +``` +--- + +Now let's look at the same code but without the syntactic sugar of the `class` keyword: + +```javascript +// This function defines the base "constructor" for us and is +// comparable to the constructor function found in the class example +function Animal() { + this.legs = 4; +} + +// Adding the getLegs property to the prototype ensures that +// it will be inherited to any objects that are created from Animal +Animal.prototype.getLegs = function() { + return this.legs; +} + +// The Dog function acts as the constructor, but where is the super call +// that we use to call the constructor from Animal? +function Dog(age) { + // the call method is similar in function to calling the super method in the + // super method in the class based example. In this case, it instantiates the + // legs property + Animal.call(this); + + this.age = age; +} + +// We set the prototype of Dog to the prototype of Animal +// in order to have access to the getLegs method that is +// defined on Animal's prototype +Dog.prototype = Object.create(Animal.prototype); + +// Dog is set as the constructor property on the Dog prototype to +// match the object structure of the class example +Dog.prototype.constructor = Dog; + +// Define getSound method +Dog.prototype.getSound = function() { + return ("Bow"); +} + +// Define getAge method +Dog.prototype.getAge = function() { + return (this.age); +} + +// create new Dog with age 10 +const tommy = new Dog(10); + +console.log(tommy); // Dog { legs: 4, age: 10 } + +// call getLegs that was inherited from Animal +console.log(tommy.getLegs()); // 4 + +// call both getSound and getAge that are defined on Dog +console.log(tommy.getSound()); // Bow +console.log(tommy.getAge()); // 10 +``` From ea9f2da53f07616ec83edb6bcff3a747211c0406 Mon Sep 17 00:00:00 2001 From: Jonathan Goldfuss Date: Mon, 28 Oct 2019 16:09:43 -0400 Subject: [PATCH 87/93] added exercises for switch case --- JavaScript_Basics/switch_case.js | 176 ++++++++++++++++++------------- 1 file changed, 105 insertions(+), 71 deletions(-) diff --git a/JavaScript_Basics/switch_case.js b/JavaScript_Basics/switch_case.js index b7f045e..dff651a 100644 --- a/JavaScript_Basics/switch_case.js +++ b/JavaScript_Basics/switch_case.js @@ -12,14 +12,14 @@ Syntax; switch (expression) { -case x: + case x: + // code block + break; + case y: + // code block + break; + default: // code block - break; -case y: - // code block - break; -default: - // code block } // This is how it works: @@ -35,26 +35,26 @@ default: // This example uses the weekday number to calculate the weekday name: switch (new Date().getDay()) { -case 0: - day = "Sunday"; - break; -case 1: - day = "Monday"; - break; -case 2: - day = "Tuesday"; - break; -case 3: - day = "Wednesday"; - break; -case 4: - day = "Thursday"; - break; -case 5: - day = "Friday"; - break; -case 6: - day = "Saturday"; + case 0: + day = 'Sunday'; + break; + case 1: + day = 'Monday'; + break; + case 2: + day = 'Tuesday'; + break; + case 3: + day = 'Wednesday'; + break; + case 4: + day = 'Thursday'; + break; + case 5: + day = 'Friday'; + break; + case 6: + day = 'Saturday'; } /** @@ -81,14 +81,14 @@ case 6: // If today is neither Saturday (6) nor Sunday (0), write a default message: switch (new Date().getDay()) { -case 6: - text = "Today is Saturday"; - break; -case 0: - text = "Today is Sunday"; - break; -default: - text = "Looking forward to the Weekend"; + case 6: + text = 'Today is Saturday'; + break; + case 0: + text = 'Today is Sunday'; + break; + default: + text = 'Looking forward to the Weekend'; } // The result of text will be: @@ -99,14 +99,14 @@ default: // Example switch (new Date().getDay()) { -default: - text = "Looking forward to the Weekend"; - break; -case 6: - text = "Today is Saturday"; - break; -case 0: - text = "Today is Sunday"; + default: + text = 'Looking forward to the Weekend'; + break; + case 6: + text = 'Today is Saturday'; + break; + case 0: + text = 'Today is Sunday'; } // If default is not the last case in the switch block, remember to end the default case with a break. @@ -119,16 +119,16 @@ case 0: // Example switch (new Date().getDay()) { -case 4: -case 5: - text = "Soon it is Weekend"; - break; -case 0: -case 6: - text = "It is Weekend"; - break; -default: - text = "Looking forward to the Weekend"; + case 4: + case 5: + text = 'Soon it is Weekend'; + break; + case 0: + case 6: + text = 'It is Weekend'; + break; + default: + text = 'Looking forward to the Weekend'; } // Switching Details @@ -147,17 +147,16 @@ default: // In this example there will be no match for x: -Example: -var x = "0"; +Example: var x = '0'; switch (x) { -case 0: - text = "Off"; - break; -case 1: - text = "On"; - break; -default: - text = "No value found"; + case 0: + text = 'Off'; + break; + case 1: + text = 'On'; + break; + default: + text = 'No value found'; } /** Exercise for You Complete it */ @@ -165,11 +164,46 @@ default: // Create a switch statement that will alert "Hello" if fruits is "banana", and "Welcome" if fruits is "apple". switch (fruits) { -case "Banana": - alert("Hello"); - break; - -case "Apple": - alert("Welcome"); - break; -} \ No newline at end of file + case 'Banana': + alert('Hello'); + break; + + case 'Apple': + alert('Welcome'); + break; +} + +// Create a switch statement that will tell you what to wear based on the temperature outside. For temps below 50 degrees Fahrenheit, alert "Wear a coat." For temps between 51 and 70 degrees, alert "Bring a sweater." For temps above 70, alert "It should be warm." + +var temp = 49; + +switch (true) { + case temp <= 50: + 'Wear a coat.'; + break; + case temp > 50 && temp <= 70: + 'Bring a sweater.'; + break; + case temp > 70: + 'It should be warm.'; +} + +// Create a switch statement to determine who wins in a game of rocks, paper, scissors. + +var player1 = 'scissors'; +var player2 = 'paper'; + +switch (true) { + case player1 === 'paper' && player2 === 'rock': + case player1 === 'scissors' && player2 === 'paper': + case player1 === 'rock' && player2 === 'scissors': + 'Player 1 wins'; + break; + case player1 === 'rock' && player2 === 'paper': + case player1 === 'paper' && player2 === 'scissors': + case player1 === 'scissors' && player2 === 'rock': + 'Player 2 wins'; + break; + default: + 'Tie. Go again.'; +} From 3a1df4c5fe3f95a8f25f867fecd3cf77e67669d6 Mon Sep 17 00:00:00 2001 From: Igor Naperkovskiy Date: Mon, 28 Oct 2019 16:29:34 -0400 Subject: [PATCH 88/93] Added Inheritance question --- docs/Exercise/JavaScript_Basics/inheritance.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 docs/Exercise/JavaScript_Basics/inheritance.md diff --git a/docs/Exercise/JavaScript_Basics/inheritance.md b/docs/Exercise/JavaScript_Basics/inheritance.md new file mode 100644 index 0000000..8577316 --- /dev/null +++ b/docs/Exercise/JavaScript_Basics/inheritance.md @@ -0,0 +1 @@ +**Write** a Javascript function called Vehicle that has variables [Make and Model] in it. Then write another function called Car that calls Vehicle function and also add two more variables [Body and Trim]. Once that is done you can call Car function and see that it inherits from Vehicle. \ No newline at end of file From 141acefa45d81ef3b2b52b3e7755470d217c8ac4 Mon Sep 17 00:00:00 2001 From: lajacl Date: Mon, 28 Oct 2019 17:55:21 -0500 Subject: [PATCH 89/93] Remove emoji that isn't properly displaying --- .../JavaScript_Basics/comparison_operators.md | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/docs/Exercise/JavaScript_Basics/comparison_operators.md b/docs/Exercise/JavaScript_Basics/comparison_operators.md index 5d79d3e..ae629e9 100644 --- a/docs/Exercise/JavaScript_Basics/comparison_operators.md +++ b/docs/Exercise/JavaScript_Basics/comparison_operators.md @@ -1,11 +1,13 @@ ### Comparison Operators Exercises +***Note: __ = blank** -**1. Choose the correct comparison operator to alert true, when x is greater than y.** + +**1. Fill in the blank with the correct comparison operator to alert true, when x is greater than y.** x = 10; y = 5; - alert(x :white_medium_square: y); + alert(x __ y);
SHOW ANSWER @@ -13,11 +15,11 @@
-**2. Choose the correct comparison operator to alert true, when x is equal to y.** +**2. Fill in the blank with the correct comparison operator to alert true, when x is equal to y.** x = 10; y = 10; - alert(x :white_medium_square: y); + alert(x __ y);
SHOW ANSWER @@ -25,11 +27,11 @@
-**3. Choose the correct comparison operator to alert true, when x is NOT equal to y.** +**3. Fill in the blank with the correct comparison operator to alert true, when x is NOT equal to y.** x = 10; y = 5; - alert(x :white_medium_square: y); + alert(x __ y);
SHOW ANSWER @@ -37,10 +39,10 @@
-**4. Choose the correct conditional (ternary) operator to alert "Too young" if age is less than 18, otherwise alert "Old enough".** +**4. Fill in the three blanks with the correct conditional (ternary) operators to alert "Too young" if age is less than 18, otherwise alert "Old enough".** var age = n; - var votingStatus = (age :white_medium_square: 18) :white_medium_square: "Too young" :white_medium_square: "Old enough"; + var votingStatus = (age __ 18) __ "Too young" __ "Old enough"; alert(votingStatus);
@@ -109,7 +111,7 @@ true
-**11. What will the value of color be after the following statemnt is executed?** +**11. What will the value of the variable color be after the following statement is executed?** var color = 5 < 10 ? "red" : "blue"; From dd2f2fdd9dd0d07f8b99d1a7fd110b08844e1ba1 Mon Sep 17 00:00:00 2001 From: cindyle Date: Mon, 28 Oct 2019 16:35:02 -0700 Subject: [PATCH 90/93] added math random function and math round --- JavaScript_Basics/math.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/JavaScript_Basics/math.js b/JavaScript_Basics/math.js index 7d87893..e90bd45 100644 --- a/JavaScript_Basics/math.js +++ b/JavaScript_Basics/math.js @@ -13,7 +13,10 @@ Math.min(50, 50, 810, 2200, -900); // will return -900 Math.max(230, 250, 10, 300, -900); // will return 300 // round function -Math.random(); // returns a random number +Math.round(5.899); + +// returns a random number that is not an integer between 1 to 10. +Math.random() * (10 - 1) + 1; // Defining variables to carry out the mathematical functions on. value1 = 10; From fba8524b3907a8113880e16aaf197b2e5eaef2d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?La=C3=A9rcio=20Silva?= Date: Mon, 28 Oct 2019 23:28:41 -0300 Subject: [PATCH 91/93] Add how get evironment variable --- JavaScript_Advance/get_environment_variable.js | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 JavaScript_Advance/get_environment_variable.js diff --git a/JavaScript_Advance/get_environment_variable.js b/JavaScript_Advance/get_environment_variable.js new file mode 100644 index 0000000..59e5783 --- /dev/null +++ b/JavaScript_Advance/get_environment_variable.js @@ -0,0 +1,7 @@ +// Getting values of environment variables +// For example, getting username of machine +const ENV_VARIABLE_KEY = "USER"; + +const ENV_VARIABLE_VALUE = process.env[ENV_VARIABLE_KEY]; + +console.log(ENV_VARIABLE_VALUE); \ No newline at end of file From 7d3a18bea19b37aac52494538d322389b049803e Mon Sep 17 00:00:00 2001 From: Lindsay Chapin Date: Mon, 28 Oct 2019 20:56:12 -0600 Subject: [PATCH 92/93] loops --- docs/JavaScript_Basics/loops.md | 69 +++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 docs/JavaScript_Basics/loops.md diff --git a/docs/JavaScript_Basics/loops.md b/docs/JavaScript_Basics/loops.md new file mode 100644 index 0000000..708d677 --- /dev/null +++ b/docs/JavaScript_Basics/loops.md @@ -0,0 +1,69 @@ +# Loops +There are different four main types of loops in Javascript. All of them are a way move over a set of data and interact with it but they have different applications and syntax. + +## For Loops +For loops are the most common types of loops in JS. + +``` +var food = ["rice", "beans", "tortilla"] +for (var i = 0; i < food.length; i++){ + console.log("Burritos have " + food[i]) +} +``` + +This code will output: +`"Burritos have rice"` +`"Burritos have beans"` +`"Burritos have tortilla"` + +*But how is this happening?* +2 important things to remember: + - Arrays are 0 indexed + - the `.length` method counts the number of items in the array + +The syntax of the for loop says that we have a variable `i` that is equal to 0, as long as `i` is less than the length of food, and `i++` means every time we get through the code increase the value of `i` by one. So the first time through `food[i]` is equal to `food[0]` which is "rice", then `i` increases by one making it `food[1]` which is "beans". The third time through `i` = 2 which is `food[2]` which is "tortilla". When `i` increases this time it's equal to 3 which is not less than 3 so we have completed the for loop and the code would move on to whatever was below the for loop. +*An important thing to remember to make your i less than your length or you run the risk of causing an infinite loop.* + +## While Loops +While loops are less common than for loops but also very powerful. While loops say while this thing is true do this + +``` +var num = 0 +while(num < 5){ + console.log(num) + num++ +} +``` + +This code is running while num is less than 5. +If we had this code instead: + +``` +var num = 5 +while(num < 5){ + console.log(num) + num++ +} +``` +The while loop would never run because that condition is never true + +*An important thing to remember to make sure your condition has a way to be false or you will get an infinite loop.* + +## Do While Loops +Do While loops are similar to while loops but they will alway run once. + +``` +var num = 5 +do { + console.log(num) + num++ +} while(num < 5) +``` + +Even though this wouldn't run in a while loop a do while loops always run at least once so you would see `num` in the console + +*An important thing to remember to make sure your condition has a way to be false or you will get an infinite loop.* + + +## For In Loops +Our article [looping an object](./looping_an_object.md) covers for in loops. While these are primarily used with objects they can also be used with arrays. the down side of this is that you cannot access the index like you can with a regular for loop. If you need the index I'd suggest a regular for loop. From 248374815a29702a707b1c9662eef02f7438c680 Mon Sep 17 00:00:00 2001 From: Swapnil Satish Shinde <37082605+Swap76@users.noreply.github.com> Date: Tue, 29 Oct 2019 08:52:44 +0530 Subject: [PATCH 93/93] Update loops.md --- docs/JavaScript_Basics/loops.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/JavaScript_Basics/loops.md b/docs/JavaScript_Basics/loops.md index 708d677..d02a0ec 100644 --- a/docs/JavaScript_Basics/loops.md +++ b/docs/JavaScript_Basics/loops.md @@ -4,7 +4,7 @@ There are different four main types of loops in Javascript. All of them are a wa ## For Loops For loops are the most common types of loops in JS. -``` +```js var food = ["rice", "beans", "tortilla"] for (var i = 0; i < food.length; i++){ console.log("Burritos have " + food[i]) @@ -27,7 +27,7 @@ The syntax of the for loop says that we have a variable `i` that is equal to 0, ## While Loops While loops are less common than for loops but also very powerful. While loops say while this thing is true do this -``` +```js var num = 0 while(num < 5){ console.log(num) @@ -38,7 +38,7 @@ while(num < 5){ This code is running while num is less than 5. If we had this code instead: -``` +```js var num = 5 while(num < 5){ console.log(num) @@ -52,7 +52,7 @@ The while loop would never run because that condition is never true ## Do While Loops Do While loops are similar to while loops but they will alway run once. -``` +```js var num = 5 do { console.log(num)