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/.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 diff --git a/JavaScript_Advance/arrow_function.js b/JavaScript_Advance/arrow_function.js index e63098f..1dbd821 100644 --- a/JavaScript_Advance/arrow_function.js +++ b/JavaScript_Advance/arrow_function.js @@ -1,14 +1,28 @@ 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", 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 } } +//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 @@ -17,7 +31,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 } } @@ -31,7 +45,7 @@ class Student { } getName = () => { - return this.name; + return this.name; } } @@ -39,24 +53,34 @@ 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 + +//settimeout without arrow function +setTimeout(function () { + console.log("hello world"); +}, 1000); -console.log(Swapnil.getFullName()); // Output My name is Swapnil Shinde \ No newline at end of file +//settimeout with arrow function +setTimeout(() => { + console.log("hello world"); +}, 0); //arrow functions provide better readability 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/event_loop.js b/JavaScript_Advance/event_loop.js index 99e4a14..c507359 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..0a5bff8 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) { + 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); +} +console.log(filter(arr, callback)); \ No newline at end of file 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. 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 diff --git a/JavaScript_Advance/hoisting.js b/JavaScript_Advance/hoisting.js index 1ac7ebf..b2a6c78 100644 --- a/JavaScript_Advance/hoisting.js +++ b/JavaScript_Advance/hoisting.js @@ -23,4 +23,10 @@ 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); +const foo = "foo"; // unable to print due to the hoisting behaviour + +console.log(ok); +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 9fcb2c9..d2af04b 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/"; +const 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/recursion.js b/JavaScript_Advance/recursion.js new file mode 100644 index 0000000..cd82f7f --- /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! \ No newline at end of file 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/JavaScript_Advance/while_loop.js b/JavaScript_Advance/while_loop.js index ac99790..c9f8e5b 100644 --- a/JavaScript_Advance/while_loop.js +++ b/JavaScript_Advance/while_loop.js @@ -10,9 +10,14 @@ */ -var n = 1; +let n = 1; while (n < 6) { console.log("n is less than 6. n = " + n); n++; -} \ No newline at end of file +} + +let sum = 1; +do { + console.log(`sum now is ${sum++}`); +} while (sum <= 100); \ No newline at end of file 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 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/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/exercise_1_using_arrays.js b/JavaScript_Basics/exercise_1_using_arrays.js deleted file mode 100644 index 99d8c9e..0000000 --- a/JavaScript_Basics/exercise_1_using_arrays.js +++ /dev/null @@ -1,23 +0,0 @@ -var 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/JavaScript_Basics/exercise_1_using_classes.js b/JavaScript_Basics/exercise_1_using_classes.js deleted file mode 100644 index 4866065..0000000 --- a/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/JavaScript_Basics/exercise_1_using_object.js b/JavaScript_Basics/exercise_1_using_object.js deleted file mode 100644 index e400518..0000000 --- a/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 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/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"} diff --git a/JavaScript_Basics/higher_order_functions.js b/JavaScript_Basics/higher_order_functions.js index d00da4e..7708830 100644 --- a/JavaScript_Basics/higher_order_functions.js +++ b/JavaScript_Basics/higher_order_functions.js @@ -43,4 +43,4 @@ const newListFiltered = list.map(function (item, index, list) { [1, 10, 2, 21].sort(); -// this return [1, 10, 2, 21] \ No newline at end of file +// this return [1, 10, 2, 21] 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/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 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/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/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; 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/switch_case.js b/JavaScript_Basics/switch_case.js index dc188bc..dff651a 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,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.'; +} 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 }; diff --git a/JavaScript_Basics/variables.js b/JavaScript_Basics/variables.js index 49c335b..269973c 100644 --- a/JavaScript_Basics/variables.js +++ b/JavaScript_Basics/variables.js @@ -1,7 +1,21 @@ +/* eslint no-var: "off" */ + // There is only 3 types of variables in javascript -const a = "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. +PI = 2; // Output {Error: PI is read only} +console.log(PI) // Output {3.14} -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 +//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 diff --git a/README.md b/README.md index a6ea53d..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` globally. +1. Install dependencies ``` - npm i docsify-cli -g + npm install ``` 2. Then run the following command to serve the documentation. ``` 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 diff --git a/docs/Exercise/JavaScript_Basics/Exercise-1.md b/docs/Exercise/JavaScript_Basics/Exercise-1.md deleted file mode 100644 index 88e1e0e..0000000 --- a/docs/Exercise/JavaScript_Basics/Exercise-1.md +++ /dev/null @@ -1,7 +0,0 @@ -1. **Create** an object of class `Student` containing his/her `first name`, `last name`, `age`, `college` and `bio`. - -2. Encapsulate *(with getters and setters)* the user details **using normal functions**. - -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**. 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? 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 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 ?** + + \ No newline at end of file diff --git a/docs/Exercise/JavaScript_Basics/comparison_operators.md b/docs/Exercise/JavaScript_Basics/comparison_operators.md new file mode 100644 index 0000000..ae629e9 --- /dev/null +++ b/docs/Exercise/JavaScript_Basics/comparison_operators.md @@ -0,0 +1,121 @@ +### Comparison Operators Exercises + +***Note: __ = blank** + + +**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 __ y); + +
+SHOW ANSWER +> +
+ + +**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 __ y); + +
+SHOW ANSWER +== OR === +
+ + +**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 __ y); + +
+SHOW ANSWER +!= OR !== +
+ + +**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 __ 18) __ "Too young" __ "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 the variable color be after the following statement is executed?** + + var color = 5 < 10 ? "red" : "blue"; + +
+SHOW ANSWER +"red" +
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/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] 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]`. diff --git a/docs/Exercise/JavaScript_Basics/if_else.md b/docs/Exercise/JavaScript_Basics/if_else.md new file mode 100644 index 0000000..e9ed327 --- /dev/null +++ b/docs/Exercise/JavaScript_Basics/if_else.md @@ -0,0 +1,20 @@ +**Write** a JavaScript program to determine if a number is positive, negative, or zero. + +**Example Input**: + +6 +0 +-20 + +**Expected Output**: + +"positive" +"zero" +"negative" + +### 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. \ No newline at end of file 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 diff --git a/docs/Exercise/JavaScript_Basics/looping_objects.md b/docs/Exercise/JavaScript_Basics/looping_objects.md new file mode 100644 index 0000000..323e3ef --- /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 +```js +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 +```js +dog.age = 2 +``` diff --git a/docs/Exercise/JavaScript_Basics/object.md b/docs/Exercise/JavaScript_Basics/object.md new file mode 100644 index 0000000..ec1189d --- /dev/null +++ b/docs/Exercise/JavaScript_Basics/object.md @@ -0,0 +1,116 @@ +1. **Create** an object of class `Student` containing his/her `first name`, `last name`, `age`, `college` and `bio`. + +2. Encapsulate *(with getters and setters)* the user details **using normal functions**. + +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/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'}, + ] +}; +``` diff --git a/docs/Exercise/JavaScript_Basics/string.md b/docs/Exercise/JavaScript_Basics/string.md new file mode 100644 index 0000000..ffde5c2 --- /dev/null +++ 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" 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 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) => { + // ... +} +``` 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/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/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/destructuring.md b/docs/JavaScript_Advance/destructuring.md index 6c74076..d6b07ba 100644 --- a/docs/JavaScript_Advance/destructuring.md +++ b/docs/JavaScript_Advance/destructuring.md @@ -1 +1,77 @@ # 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. + +## 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 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/docs/JavaScript_Advance/express.md b/docs/JavaScript_Advance/express.md index a42433f..a242feb 100644 --- a/docs/JavaScript_Advance/express.md +++ b/docs/JavaScript_Advance/express.md @@ -1,8 +1,80 @@ -#### install -```sh -npm i -``` -#### run -```sh -node ./JavaScript_Advance/express.js -``` \ 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}`)); +``` diff --git a/docs/JavaScript_Advance/fs_module.md b/docs/JavaScript_Advance/fs_module.md index 21adac6..e384430 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. +```js +content.on("data", (data) => { + console.log(data); +}); +``` +We can also listen to the event when a file is closed. +```js +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. 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/prototype.md b/docs/JavaScript_Advance/prototype.md index 140ce77..9a1e6df 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`. 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. 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' } +``` diff --git a/docs/JavaScript_Advance/timer_function.md b/docs/JavaScript_Advance/timer_function.md index 9e53e69..391a7bf 100644 --- a/docs/JavaScript_Advance/timer_function.md +++ b/docs/JavaScript_Advance/timer_function.md @@ -1 +1,118 @@ -# 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); +``` + + + 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/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 diff --git a/docs/JavaScript_Basics/classes.md b/docs/JavaScript_Basics/classes.md index 87846ef..67559e3 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 instance: + +```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(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 +``` diff --git a/docs/JavaScript_Basics/condition_statments.md b/docs/JavaScript_Basics/condition_statments.md index 009b493..559f20b 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 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){ + do this +} else{ + do this +} +``` +`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){ + 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: +```js +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": +```js +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" +```js +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: +```js +if(number % 2 === 0){ +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. diff --git a/docs/JavaScript_Basics/higher_order_functions.md b/docs/JavaScript_Basics/higher_order_functions.md index 8768c4a..77a718a 100644 --- a/docs/JavaScript_Basics/higher_order_functions.md +++ b/docs/JavaScript_Basics/higher_order_functions.md @@ -1 +1,94 @@ -# Higher Order Functions \ No newline at end of file +## 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) +``` \ No newline at end of file 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 +``` diff --git a/docs/JavaScript_Basics/looping_an_object.md b/docs/JavaScript_Basics/looping_an_object.md index 18a6886..162ca30 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); + } +} +``` diff --git a/docs/JavaScript_Basics/loops.md b/docs/JavaScript_Basics/loops.md new file mode 100644 index 0000000..d02a0ec --- /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. + +```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 + +```js +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: + +```js +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. + +```js +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. 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/docs/JavaScript_Basics/objects.md b/docs/JavaScript_Basics/objects.md index 2e79c08..eb0977b 100644 --- a/docs/JavaScript_Basics/objects.md +++ b/docs/JavaScript_Basics/objects.md @@ -1 +1,79 @@ # 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: +```js +var person = { + firstName:"John", + lastName:"Doe", + age:50, + eyeColor:"blue" + }; +``` + +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' } +``` 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** 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 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 diff --git a/docs/JavaScript_Basics/string_operation.md b/docs/JavaScript_Basics/string_operation.md index a14523a..bd59004 100644 --- a/docs/JavaScript_Basics/string_operation.md +++ b/docs/JavaScript_Basics/string_operation.md @@ -1 +1,29 @@ # 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 +``` diff --git a/docs/JavaScript_Basics/this.md b/docs/JavaScript_Basics/this.md index 56cda30..0d9bedd 100644 --- a/docs/JavaScript_Basics/this.md +++ b/docs/JavaScript_Basics/this.md @@ -1 +1,102 @@ -# 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 +*/ +``` diff --git a/docs/JavaScript_Basics/variables.md b/docs/JavaScript_Basics/variables.md index d9d249b..8686b39 100644 --- a/docs/JavaScript_Basics/variables.md +++ b/docs/JavaScript_Basics/variables.md @@ -1 +1,172 @@ -# 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. + +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. + +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 +``` \ No newline at end of file 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 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