├── .gitignore ├── index.js ├── 03 Operators ├── images │ └── 01-01.png ├── 12- Exercise - Swapping Variables.js ├── 01- JavaScript Operators.md ├── 10- Operators Precedence.js ├── 03- Assignment Operators.js ├── 04- Comparison Operators.js ├── 06- Ternary Operator.js ├── 02- Arithmetic Operators.js ├── 05- Equality Operators.js ├── 07- Logical Operators.js ├── 11- Quiz.md ├── 08- Logical Operators with Non-booleans.js └── 09- Bitwise Operators.js ├── 01 Getting Started ├── js-basics.zip ├── images │ ├── 01-01.png │ └── 01-02.png ├── 06- JavaScript in Node.md ├── 03- Setting Up the Development Environment.md ├── 05- Separation of Concerns.md ├── 02- What is JavaScript.md └── 04- JavaScript in Browsers.md ├── 06 Arrays ├── 17- Exercise 1- Array from Range.js ├── 19- Exercise 3- Except.js ├── 22- Exercise 6- Get Max.js ├── 09- The Spread Operator.js ├── 18- Exercise 2- Includes.js ├── 14- Filtering an Array.js ├── 01- Introduction.js ├── 11- Joining Arrays.js ├── 06- Removing Elements.js ├── 20- Exercise 4- Moving an Element.js ├── 03- Finding Elements (Primitives).js ├── 21- Exercise 5- Count Occurrences.js ├── 16- Reducing an Array.js ├── 23- Exercise 7- Movies.js ├── 10- Iterating an Array.js ├── 15- Mapping an Array.js ├── 12- Sorting Arrays.js ├── 07- Emptying an Array.js ├── 05- Arrow Functions.js ├── 13- Testing the Elements of an Array.js ├── 04- Finding Elements (Reference Types).js ├── 02- Adding Elements.js └── 08- Combining and Slicing Arrays.js ├── 05 Objects ├── 15- Exercise 1- Address Object.js ├── 18- Exercise 4- Blog Post Object.js ├── 19- Exercise 5- Constructor Functions.js ├── 20- Exercise 6- Price Range Object.js ├── 04- Dynamic Nature of Objects.js ├── 16- Exercise 2- Factory and Constructor Functions.js ├── 10- Garbage Collection.js ├── 11- Math.js ├── 08- Enumerating Properties of an Object.js ├── 03- Constructor Functions.js ├── 17- Exercise 3- Object Equality.js ├── 13- Template Literals.js ├── 09- Cloning an Object.js ├── 06- Functions are Objects.js ├── 01- Basics.js ├── 14- Date.js ├── 05- Constructor Property.js ├── 07- Value vs Reference Types.js ├── 02- Factory Functions.js └── 12- String.js ├── index.html ├── 04 Control Flow ├── 10- Exercise 1- Max of Two Numbers.js ├── 11- Exercise 2- Landscape or Portrait.js ├── 19- Exercise 10- Stars.js ├── 16- Exercise 7- String Properties.js ├── 12- Exercise 3- FizzBuzz.js ├── 06- Infinite Loops.js ├── 17- Exercise 8- Sum of Multiples of 3 and 5.js ├── 15- Exercise 6- Count Truthy.js ├── 14- Exercise 5- Even and Odd Numbers.js ├── 08- For...of.js ├── 20- Exercise- Prime Numbers.js ├── 13- Exercise 4- Demerit Points.js ├── 07- For...in.js ├── 02- Switch...case.js ├── 04- While.js ├── 18- Exercise 9- Grade.js ├── 05- Do...while.js ├── 01- If...else.js ├── 09- Break and Continue.js └── 03- For.js ├── 02 Basics ├── 02- Constants.js ├── 08- Types of Functions.js ├── 03- Primitive Types.js ├── 04- Dynamic Typing.js ├── 07- Functions.js ├── 06- Arrays.js ├── 05- Objects.js └── 01- Variables.js ├── 07 Functions ├── 13- Exercise 2- Area of Circle.js ├── 12- Exercise 1- Sum of Arguments.js ├── 14- Exercise 3- Error Handling.js ├── 02- Hoisting.js ├── 03- Arguments.js ├── 04- The Rest Operator.js ├── 09- Let vs Var.js ├── 01- Function Declarations vs Expressions.js ├── 05- Default Parameters.js ├── 08- Local vs Global Scope.js ├── 06- Getters and Setters.js ├── 10- The this Keyword.js ├── 07- Try and Catch.js └── 11- Changing this.js └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | console.log("hello") -------------------------------------------------------------------------------- /03 Operators/images/01-01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jmschp/mosh-ultimate-javascript-mastery-series-part-1/HEAD/03 Operators/images/01-01.png -------------------------------------------------------------------------------- /01 Getting Started/js-basics.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jmschp/mosh-ultimate-javascript-mastery-series-part-1/HEAD/01 Getting Started/js-basics.zip -------------------------------------------------------------------------------- /01 Getting Started/images/01-01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jmschp/mosh-ultimate-javascript-mastery-series-part-1/HEAD/01 Getting Started/images/01-01.png -------------------------------------------------------------------------------- /01 Getting Started/images/01-02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jmschp/mosh-ultimate-javascript-mastery-series-part-1/HEAD/01 Getting Started/images/01-02.png -------------------------------------------------------------------------------- /01 Getting Started/06- JavaScript in Node.md: -------------------------------------------------------------------------------- 1 | # 06- JavaScript in Node 2 | 3 | Open a terminal and navigate to the folder with the `.js` file 4 | 5 | In the command line run `node index.js` 6 | -------------------------------------------------------------------------------- /06 Arrays/17- Exercise 1- Array from Range.js: -------------------------------------------------------------------------------- 1 | // 17- Exercise 1- Array from Range 2 | 3 | 4 | function arrayFromRange(min, max) { 5 | const numbersArray = new Array(); 6 | for(let i = min; i <= max; i++) { 7 | numbersArray .push(i); 8 | } 9 | return numbersArray; 10 | } 11 | 12 | const numbers = arrayFromRange(-10, -0) 13 | 14 | console.log(numbers); -------------------------------------------------------------------------------- /05 Objects/15- Exercise 1- Address Object.js: -------------------------------------------------------------------------------- 1 | // 15- Exercise 1- Address Object 2 | 3 | const address = { 4 | street: 'Rua Afonso Braz 505', 5 | city: 'São Paulo', 6 | zipCode: '04511-011' 7 | }; 8 | 9 | function showAddress(address) { 10 | for (let key in address) { 11 | console.log(key, address[key]) 12 | } 13 | }; 14 | 15 | showAddress(address); 16 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | The Ultimate JavaScript Mastery Series - Part 1 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /04 Control Flow/10- Exercise 1- Max of Two Numbers.js: -------------------------------------------------------------------------------- 1 | // 10- Exercise 1- Max of Two Numbers 2 | 3 | // Write a function that takes two numbers and returns the maximum of the two. 4 | 5 | function max1(number1, number2) { 6 | return (number1 > number2) ? number1 : number2; 7 | } 8 | 9 | console.log(max1(4, 9)) 10 | 11 | // We could also use if else statements, but this is the cleaner implementation. -------------------------------------------------------------------------------- /02 Basics/02- Constants.js: -------------------------------------------------------------------------------- 1 | // 02 Constants 2 | 3 | 4 | 5 | // In situations where we don't want the value of our variable to change we use constant 6 | 7 | let interestRateVariable = 0.3; 8 | interestRateVariable = 0.5; 9 | 10 | const interestRateConstant = 0.5; 11 | // interestRateConstant = 0.3; if we try to change the value of a constant this will raise na error 12 | console.log(interestRateConstant); 13 | -------------------------------------------------------------------------------- /03 Operators/12- Exercise - Swapping Variables.js: -------------------------------------------------------------------------------- 1 | // 12- Exercise - Swapping Variables 2 | 3 | /* 4 | Swap the value of two variables 5 | We initiate two variable "a" and "b", each with its value. 6 | The we mus swap their value. 7 | */ 8 | 9 | let a = 'red'; 10 | let b = 'blue'; 11 | 12 | console.log(a); 13 | console.log(b); 14 | 15 | let c = a; 16 | a = b 17 | b = c 18 | 19 | console.log(a); 20 | console.log(b); -------------------------------------------------------------------------------- /05 Objects/18- Exercise 4- Blog Post Object.js: -------------------------------------------------------------------------------- 1 | // 18- Exercise 4- Blog Post Object 2 | 3 | const blogPost = { 4 | title: 'How to become a dev', 5 | body: 'blablablabla', 6 | author: 'Miguel', 7 | views: 300, 8 | comments: [ 9 | {author: 'John', body: 'blavbaddad'}, 10 | {author: 'Angie', body: 'blavbaddad'}, 11 | {author: 'Luis', body: 'blavbaddad'} 12 | ], 13 | isLive: true 14 | }; 15 | -------------------------------------------------------------------------------- /03 Operators/01- JavaScript Operators.md: -------------------------------------------------------------------------------- 1 | # 01- JavaScript Operators 2 | 3 | In JavaScript we different kinds of Operators. We use this operator with our variables to create expressions and with these expressions we can implement logic and Algorithms 4 | 5 | ![JavaScript Operators](./images/01-01.png "JavaScript Operators") 6 | 7 | Kinds of operators: 8 | 9 | - Arithmetic 10 | - Assignment 11 | - Comparison 12 | - Logical 13 | - Bitwise 14 | -------------------------------------------------------------------------------- /06 Arrays/19- Exercise 3- Except.js: -------------------------------------------------------------------------------- 1 | // 19- Exercise 3- Except 2 | 3 | 4 | function except(array, excluded) { 5 | const output = []; 6 | array.forEach(element => { 7 | if (!excluded.includes(element)) { 8 | output.push(element); 9 | } 10 | }); 11 | return output; 12 | } 13 | 14 | const numbers = [1, 1, 2, 3, 4, 1, 1]; 15 | 16 | const newArray = except(numbers, [1, 3, 4]); 17 | console.log(newArray); 18 | -------------------------------------------------------------------------------- /04 Control Flow/11- Exercise 2- Landscape or Portrait.js: -------------------------------------------------------------------------------- 1 | // 11- Exercise 2- Landscape or Portrait 2 | 3 | // Create a function that returns true if a images is in landscape format and false if is in portrait format. 4 | 5 | 6 | function isLandscape(width, height) { 7 | return width > height // ? true : false; we don't need this last parte because the evaluation of the condition is already returning true or false. 8 | } 9 | 10 | console.log(isLandscape(800, 600)) -------------------------------------------------------------------------------- /05 Objects/19- Exercise 5- Constructor Functions.js: -------------------------------------------------------------------------------- 1 | // 19- Exercise 5- Constructor Functions 2 | 3 | 4 | function Post(title, body, author, isLive=false) { 5 | this.title = title; 6 | this.body = body; 7 | this.author = author; 8 | }; 9 | 10 | 11 | 12 | function Post(title, body, author) { 13 | this.title = title; 14 | this.body = body; 15 | this.author = author; 16 | this.views = 0; 17 | this.comments = []; 18 | this.isLive = false; 19 | }; -------------------------------------------------------------------------------- /03 Operators/10- Operators Precedence.js: -------------------------------------------------------------------------------- 1 | // 10- Operators Precedence 2 | 3 | /* 4 | Operators have precedence 5 | Just like in math the expression between the parentheses "()" are evaluated first. 6 | */ 7 | 8 | let x = 2 + 4 * 3 // Here the * operator has higher precedence so 4 * 3 is calculates first and then add 2 so the result is 14 9 | console.log(x) 10 | 11 | let y = (2 + 3) * 4 // Here because we use parentheses in (2 + 4) this is calculates first and then we add 3 so the result is 20 12 | console.log(y) -------------------------------------------------------------------------------- /07 Functions/13- Exercise 2- Area of Circle.js: -------------------------------------------------------------------------------- 1 | // 13- Exercise 2- Area of Circle.js 2 | 3 | const circle = { 4 | radius: 1, 5 | set circleRadius(rad) { 6 | this.radius = rad; 7 | }, 8 | get circleArea() { 9 | return Math.PI * this.radius ** 2; 10 | } 11 | } 12 | circle.circleRadius= 10; 13 | console.log(circle.circleArea); 14 | 15 | // Mosh solution 16 | 17 | const circleMosh = { 18 | radius: 1, 19 | get area() { 20 | return Math.PI * this.radius * this.radius; 21 | }, 22 | }; 23 | -------------------------------------------------------------------------------- /03 Operators/03- Assignment Operators.js: -------------------------------------------------------------------------------- 1 | // 03- Assignment Operators 2 | 3 | /* 4 | Theses are the assignment operator: 5 | = 6 | += 7 | -= 8 | *= 9 | /= 10 | %= 11 | */ 12 | 13 | let x = 10; // Assigning 10 to x 14 | 15 | console.log(x += 5); // This is the same as x = x + 5 16 | console.log(x -= 5); // This is the same as x = x - 5 17 | console.log(x *= 5); // This is the same as x = x * 5 18 | console.log(x /= 5); // This is the same as x = x / 5 19 | console.log(x %= 5); // This is the same as x = x % 5 -------------------------------------------------------------------------------- /05 Objects/20- Exercise 6- Price Range Object.js: -------------------------------------------------------------------------------- 1 | // 20- Exercise 6- Price Range Object 2 | 3 | 4 | const priceRange = [ 5 | {minPrice: 0, maxPrice: 99}, 6 | {minPrice: 100, maxPrice: 150}, 7 | {minPrice: 151, maxPrice: 200} 8 | ] 9 | 10 | 11 | // Mosh solution 12 | let priceRange = [ 13 | { label:'$', tooltip: 'Inexpensive', minPricePerPerson: 0, maxPricePerPerson: 10 }, 14 | { label:'$', tooltip: 'Moderate', minPricePerPerson: 11, maxPricePerPerson: 20 }, 15 | { label:'$', tooltip: 'Expensive', minPricePerPerson: 21, maxPricePerPerson: 50 }, 16 | ]; 17 | -------------------------------------------------------------------------------- /06 Arrays/22- Exercise 6- Get Max.js: -------------------------------------------------------------------------------- 1 | // 22 - Exercise 6 - Get Max 2 | 3 | const numbers = [1, 5, 2, 3, 4]; 4 | 5 | const max = getMaxMosh(numbers); 6 | console.log(max); 7 | 8 | function getMax(array) { 9 | return array.reduce((accumulator, currentValue) => { 10 | const max = (accumulator > currentValue) ? accumulator : currentValue 11 | return max 12 | }, undefined); 13 | } 14 | 15 | // Mosh solution 16 | 17 | function getMaxMosh(array) { 18 | if (array.length ===0) return undefined; 19 | return array.reduce((a, b) => (a > b) ? a : b); 20 | } -------------------------------------------------------------------------------- /04 Control Flow/19- Exercise 10- Stars.js: -------------------------------------------------------------------------------- 1 | // 19- Exercise 10- Stars 2 | 3 | 4 | function showStars(rows) { 5 | let pattern = ''; 6 | for (let i = 1; i <= rows; i++) { 7 | pattern += '*'; 8 | console.log(pattern); 9 | } 10 | } 11 | 12 | 13 | //Mosh solution: 14 | function showStars(rows) { 15 | for (let row = 1; row <= rows; row++) { 16 | let pattern = ''; 17 | for (let i = 0; i < row; i++) { 18 | pattern += '*'; 19 | } 20 | console.log(pattern) 21 | } 22 | } 23 | 24 | showStars(5) -------------------------------------------------------------------------------- /06 Arrays/09- The Spread Operator.js: -------------------------------------------------------------------------------- 1 | // 09- The Spread Operator 2 | 3 | 4 | /* 5 | With the Spread Operator we can also combine and copy arrays. 6 | This is a cleaner approach. 7 | */ 8 | 9 | const first = [1, 2, 3]; 10 | const second = [4, 5, 6]; 11 | 12 | // Combining arrays 13 | const combined = [...first, ...second]; 14 | console.log(combined); 15 | 16 | const combined2 = [...first, 'a', 'b', ...second, 'c']; 17 | console.log(combined2); 18 | 19 | // Copy array 20 | 21 | const copied = [...first]; 22 | console.log(copied); 23 | 24 | const copied2 = [...combined]; 25 | console.log(copied2) -------------------------------------------------------------------------------- /07 Functions/12- Exercise 1- Sum of Arguments.js: -------------------------------------------------------------------------------- 1 | // 12- Exercise 1- Sum of Arguments 2 | 3 | function sum(...numbers) { 4 | if (Array.isArray(numbers[0])) { 5 | return numbers[0].reduce((acc, curr) => acc + curr); 6 | } 7 | return numbers.reduce((acc, curr) => acc + curr); 8 | } 9 | 10 | console.log(sum(1, 2, 3, 4, 5)); 11 | console.log(sum([1, 2, 3, 4, 5])); 12 | 13 | // Mosh solution 14 | 15 | function sum(...items) { 16 | if (items.length ===1 && Array.isArray(items[0])) { 17 | items = [...items] 18 | } 19 | return numbers.reduce((acc, curr) => acc + curr); 20 | } -------------------------------------------------------------------------------- /02 Basics/08- Types of Functions.js: -------------------------------------------------------------------------------- 1 | // 08 Types of Functions 2 | 3 | 4 | /* 5 | We have to types of functions: 6 | Performs a task 7 | Calculates value 8 | */ 9 | 10 | // Performs a task 11 | function greetPerson(firstName, lastName) { 12 | console.log("Hello " + firstName + " " + lastName); 13 | } 14 | 15 | 16 | // Calculates value 17 | function square(number) { 18 | return number * number; 19 | } 20 | 21 | // This function is calculates a value and returning it. So we return the value to how ever is calling the function. 22 | 23 | let number = square(2) 24 | console.log(number) -------------------------------------------------------------------------------- /07 Functions/14- Exercise 3- Error Handling.js: -------------------------------------------------------------------------------- 1 | // 14- Exercise 3- Error Handling 2 | 3 | function countOccurrences(array, searchElement) { 4 | if (!Array.isArray(array)) { 5 | throw new Error("First argument must be an array"); 6 | } 7 | return array.reduce((accumulator, current) => { 8 | const occurrence = current === searchElement ? 1 : 0; 9 | return accumulator + occurrence; 10 | }, 0); 11 | } 12 | 13 | const numbers = [1, 2, 3, 4, 1, 5]; 14 | 15 | try { 16 | const count = countOccurrences(null, 1); 17 | console.log(count); 18 | } catch (error) { 19 | console.error(error.message); 20 | } 21 | -------------------------------------------------------------------------------- /05 Objects/04- Dynamic Nature of Objects.js: -------------------------------------------------------------------------------- 1 | // 04- Dynamic Nature of Objects 2 | 3 | /* 4 | In JavaScript object are dynamic, once they are created we can add new properties or methods to it. 5 | */ 6 | 7 | const circle = { 8 | radius: 1, 9 | } 10 | 11 | circle.color = 'yellow'; // In here we add a new property to the object, in this case color 12 | circle.draw = function() { // Here we add a new method two the object. 13 | console.log('Draw') 14 | }; 15 | 16 | console.log(circle); 17 | 18 | delete circle.color; // With the "delete" statement we can delete properties or methods. 19 | 20 | console.log(circle); -------------------------------------------------------------------------------- /04 Control Flow/16- Exercise 7- String Properties.js: -------------------------------------------------------------------------------- 1 | // 16- Exercise 7- String Properties 2 | 3 | /* 4 | Create function "showProperties()"". 5 | Pass an object to that function, and it should and is should display all the properties of the object that are of type string. 6 | */ 7 | 8 | function showProperties(object) { 9 | for (let property in object) { 10 | if (typeof object[property] === 'string') 11 | console.log(property, object[property]); 12 | } 13 | } 14 | 15 | const movie = { 16 | title: "a", 17 | releaseYear: 2018, 18 | rating: 4.5, 19 | director: "b" 20 | } 21 | 22 | showProperties(movie) -------------------------------------------------------------------------------- /04 Control Flow/12- Exercise 3- FizzBuzz.js: -------------------------------------------------------------------------------- 1 | // 12- Exercise 3- FizzBuzz 2 | 3 | 4 | /* 5 | Create the FizzBuzz function 6 | Divisible by 3 => Fizz 7 | Divisible by 5 => Buzz 8 | Divisible by both 3 and 5 => FizzBuzz 9 | Not divisible by 3 or 5 => input 10 | Not a number => 'Not a number' 11 | */ 12 | 13 | function fizzBuzz(input) { 14 | if (typeof input !== 'number') return NaN; 15 | else if ((input % 3 === 0) && (input % 5 === 0)) return 'FizzBuzz'; 16 | else if (input % 3 === 0) return 'Fizz'; 17 | else if (input % 5 === 0) return 'Buzz'; 18 | else return input; 19 | } 20 | 21 | let result = fizzBuzz('a') 22 | console.log(result) -------------------------------------------------------------------------------- /06 Arrays/18- Exercise 2- Includes.js: -------------------------------------------------------------------------------- 1 | // 18- Exercise 2- Includes 2 | 3 | function includes(array, searchElement) { 4 | let output = false; 5 | array.forEach(element => { 6 | if (element === searchElement) { 7 | output = true; 8 | } 9 | }); 10 | return output; 11 | } 12 | 13 | const numbers = [1, 2, 3, 4, 5, 6]; 14 | 15 | console.log(includes(numbers, -3)); 16 | 17 | // Mosh solution 18 | 19 | function includesMosh(array, searchElement) { 20 | for (let element of array) 21 | if (element === searchElement) 22 | return true; 23 | return false; 24 | } 25 | 26 | console.log(includesMosh(numbers, 3)); -------------------------------------------------------------------------------- /03 Operators/04- Comparison Operators.js: -------------------------------------------------------------------------------- 1 | // 04- Comparison Operators 2 | 3 | /* 4 | An expression with a comparison operator will return a boolean value 5 | These are the comparison operators 6 | == equal to 7 | === equal value and equal type 8 | != not equal 9 | !== not equal value or not equal type 10 | > greater than 11 | < less than 12 | >= greater than or equal to 13 | <= less than or equal to 14 | */ 15 | 16 | let x = 5; 17 | 18 | console.log(x == '5'); 19 | console.log(x === 5); 20 | console.log(x != '5'); 21 | console.log(x !== 5); 22 | console.log(x > 5); 23 | console.log(x < 5); 24 | console.log(x >= 5); 25 | console.log(x <= 5); -------------------------------------------------------------------------------- /04 Control Flow/06- Infinite Loops.js: -------------------------------------------------------------------------------- 1 | // 06- Infinite Loops 2 | 3 | /* 4 | A infinite loop executes infinity or forever. 5 | If we create such a loop we may crash the browser or the computer. 6 | */ 7 | 8 | let i = 0; 9 | while (i < 5){ 10 | console.log(i); 11 | // i++ 12 | } 13 | // If we forget to increment i we loop runs forever. 14 | 15 | 16 | for (i = 1; i > 0; i++) { 17 | console.log(i) 18 | } 19 | // This is an example of an infinity for loop, the condition i > 0 is always true, so the loop will never end. 20 | 21 | for (i = 1; i > 0;) { 22 | console.log(i) 23 | } 24 | // This is an example of an infinity for loop, because we are not incrementing i. -------------------------------------------------------------------------------- /05 Objects/16- Exercise 2- Factory and Constructor Functions.js: -------------------------------------------------------------------------------- 1 | // 16- Exercise 2- Factory and Constructor Functions 2 | 3 | // Factory function 4 | function cretaAddress(street, city, zipCode) { 5 | return { 6 | street, 7 | city, 8 | zipCode 9 | }; 10 | }; 11 | 12 | // Constructor function 13 | function Address(street, city, zipCode) { 14 | this.street = street; 15 | this.city = city; 16 | this.zipCode = zipCode; 17 | }; 18 | 19 | 20 | let address1 = cretaAddress('Rua Afonso Braz 505', 'São Paulo', '04511-011'); 21 | console.log(address1); 22 | 23 | let address2 = new Address('Rua Augusta 2099', 'São Paulo', '01413-000'); 24 | console.log(address2) -------------------------------------------------------------------------------- /01 Getting Started/03- Setting Up the Development Environment.md: -------------------------------------------------------------------------------- 1 | # 03- Setting Up the Development Environment 2 | 3 | ## Code editor 4 | 5 | Using Visual Studio Code to write JavaScript. 6 | 7 | ## Node.js 8 | 9 | Download and install Node, We do not need Node to execute JavaScript, because can use the browser to execute JavaScript. But is is good to have node installed, because we use that to install third party libraries. 10 | 11 | ## Files 12 | 13 | Then we create a HTML file "index.html" that we are going to use as a host for the JavaScript code. 14 | 15 | ## VS Code Extension 16 | 17 | Then install a VS Code plugin Live Server, it a very light webserver that we are going to use to serve our application. 18 | -------------------------------------------------------------------------------- /06 Arrays/14- Filtering an Array.js: -------------------------------------------------------------------------------- 1 | // 14- Filtering an Array 2 | 3 | /* 4 | To filter na array we can use the ".filter()" method. 5 | This method evaluates each element of the array with a given condition, and returns the elements that pass that condition to a new array. 6 | */ 7 | 8 | const numbers = [1, 2, -1, 3, -4, -2, 4, 5, 6, 0]; 9 | 10 | let filteredNumbers = numbers.filter(function(number) { 11 | return number > 0; // It will return the elements that pass this condition to a new array. 12 | }); 13 | 14 | console.log(filteredNumbers); 15 | 16 | filteredNumbers = numbers.filter(number => number > 0); // It the same code as above but using arrow function for a cleaner code. 17 | 18 | console.log(filteredNumbers); -------------------------------------------------------------------------------- /04 Control Flow/17- Exercise 8- Sum of Multiples of 3 and 5.js: -------------------------------------------------------------------------------- 1 | // 17- Exercise 8- Sum of Multiples of 3 and 5 2 | 3 | /* 4 | Create a function that will sum all the multiples of 3 and 5 from 0 the limit argument passed. 5 | */ 6 | 7 | function sum(limit) { 8 | let result = 0; 9 | for (i = 0; i <= limit; i++) { 10 | if (i * 3 <= 10) result += (i * 3) 11 | if (i * 5 <= 10) result += (i * 5) 12 | } 13 | return result 14 | } 15 | 16 | 17 | 18 | // Mosh solution 19 | function sum(limit) { 20 | let sum = 0; 21 | 22 | for (let i = 0; i <= limit; i++) { 23 | if (i % 3 === 0 || i % 5 === 0) 24 | sum += i 25 | } 26 | 27 | return sum 28 | } 29 | 30 | 31 | console.log(sum(10)) -------------------------------------------------------------------------------- /04 Control Flow/15- Exercise 6- Count Truthy.js: -------------------------------------------------------------------------------- 1 | // 15- Exercise 6- Count Truthy 2 | 3 | /* 4 | Create function "countTruthy()" 5 | That will count truthy values in an array. 6 | */ 7 | 8 | function countTruthy(array) { 9 | let counter = 0 10 | for (item of array) { 11 | if (item !== false && item !== undefined && item !== null && item !== 0 && item !== '' && item !== NaN) 12 | counter++; 13 | } 14 | return counter 15 | } 16 | 17 | const myArray = [1, 2, 0, 3, undefined, null, 5, 7, 'a', 'fsf'] 18 | 19 | const result = countTruthy(myArray) 20 | console.log(result) 21 | 22 | 23 | // Mosh solution 24 | function countTruthy(array) { 25 | let count = 0 26 | for (let value of array) { 27 | if (value) 28 | count++; 29 | } 30 | return count 31 | } -------------------------------------------------------------------------------- /07 Functions/02- Hoisting.js: -------------------------------------------------------------------------------- 1 | // 02 - Hoisting 2 | 3 | /* 4 | Hoisting is JavaScript's default behavior of moving declarations to the top. 5 | The key difference between Function Declaration and Function Expression is that: 6 | Function declarations can be called before being declared 7 | Function expression can not, it's the same as using a variable. 8 | 9 | The reason for this is when our JavaScript engine runs this code, it moves all function declarations to the top. 10 | Its called Hoisting. The process of moving Function Declarations to the top of the file, and it is made automatically by the Javascript engine. 11 | */ 12 | 13 | walk(); 14 | 15 | // Function declaration 16 | function walk() { 17 | console.log("walk"); 18 | } 19 | // Anonymous Function Expression 20 | let run = function () { 21 | console.log("run"); 22 | }; 23 | -------------------------------------------------------------------------------- /04 Control Flow/14- Exercise 5- Even and Odd Numbers.js: -------------------------------------------------------------------------------- 1 | // 14- Exercise 5- Even and Odd Numbers 2 | 3 | 4 | /* 5 | Create function "showNumbers()" 6 | Accepts a number as parameter, it will return all the numbers up to that number telling if it is odd or even 7 | Example: 8 | If we pass to that function 3 as argument, it should return the following. 9 | 0 "EVEN" 10 | 1 "ODD" 11 | 2 "EVEN" 12 | 3 "ODD" 13 | */ 14 | 15 | function showNumbers(limit) { 16 | for (i = 0; i < limit + 1; i++) { 17 | if (i % 2 === 0) console.log(i , "EVEN") 18 | else console.log(i , "ODD") 19 | } 20 | } 21 | 22 | 23 | // Mosh solution for a cleaner code 24 | function showNumbers(limit) { 25 | for (i = 0; i <= limit; i++) { 26 | const message = (i % 2 === 0) ? "EVEN" : "ODD" 27 | console.log(i, message) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /05 Objects/10- Garbage Collection.js: -------------------------------------------------------------------------------- 1 | // 10- Garbage Collection 2 | 3 | /* 4 | In low level languages like C or C++ when we create an object we have to allocate memory to it. 5 | And when we don't need to that ir anymore we have to deallocate the memory. 6 | In JavaScript we don't have this concept, when we create an object, memory is automatically allocated to it. 7 | And when we don~t need to use it anymore it is deallocate automatically. 8 | The JavaScript Engine has a Garbage Collector. 9 | The job of this Garbage Collector is to find the variables and constant that are no longer used, and then deallocate the memory that was allocated to then. 10 | Memory allocation and deallocation happens automatically behind the scenes, and we do not have control over it. 11 | */ 12 | 13 | const x = {a: 1, b: 2}; 14 | console.log(x); 15 | // Memory is allocated to constant "x" and automatically deallocated when not needed anymore. 16 | -------------------------------------------------------------------------------- /06 Arrays/01- Introduction.js: -------------------------------------------------------------------------------- 1 | // 01- Introduction 2 | 3 | /* 4 | Description 5 | Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. 6 | Neither the length of a JavaScript array nor the types of its elements are fixed. 7 | 8 | Most common operations we can perform in arrays: 9 | Adding elements 10 | Finding elements 11 | Removing elements 12 | Splitting arrays 13 | Combining arrays 14 | 15 | Constructor 16 | Array() 17 | Creates a new Array object. 18 | */ 19 | 20 | // Initializing an array with the Constructor 21 | let myArray1 = new Array(); 22 | console.log(myArray1); 23 | 24 | // Creating an array literal 25 | let myArray2 = []; 26 | console.log(myArray2); 27 | 28 | // Using "const" 29 | const myArray3 = []; 30 | 31 | // In case we use constant to create an array we can not reassign the variable. 32 | // But we can change the content of the array -------------------------------------------------------------------------------- /06 Arrays/11- Joining Arrays.js: -------------------------------------------------------------------------------- 1 | // 11- Joining Arrays 2 | 3 | /* 4 | The "join()" method joins the elements array into a string. 5 | 6 | The join method takes one optional parameter, a string that will be used to join each item from the array. 7 | 8 | Syntax 9 | [].join() 10 | */ 11 | 12 | const numbers = [1, 2, 3]; 13 | const numbersJoined = numbers.join(';'); 14 | console.log(numbersJoined); 15 | console.log(typeof numbersJoined); // The "joined()" method returns a string. 16 | 17 | // The "split()" method goes hand in hand With the "join()" method. 18 | // It converts a string to an array. 19 | 20 | const message = "This is a message"; 21 | const messageArray = message.split(' '); 22 | console.log(messageArray); 23 | 24 | const urlSlugExample = messageArray.join('-'); 25 | console.log(urlSlugExample); 26 | // This technic is particular useful to build url slugs. 27 | // For example when we want to convert a blog post title to the url. -------------------------------------------------------------------------------- /03 Operators/06- Ternary Operator.js: -------------------------------------------------------------------------------- 1 | // 06- Ternary Operator 2 | 3 | /* 4 | The Ternary operator also know as conditional operator, assigns a value to a variable based on a condition. 5 | First we set a variable with a comparison operator, thats our condition. 6 | Them add a "?" followed by the the value if the condition is true, them after the ":" the value if the condition is false. 7 | let variable name = (condition) ? value1 : value2 8 | let voteable = (age < 18) ? "Too young" : "Old enough"; 9 | Example explained: If the variable "age" is a value below 18, the value of the variable "voteable" will be "Too young", otherwise the value of voteable will be "Old enough". 10 | */ 11 | 12 | /* 13 | If a costumer has more than 100 points 14 | They are "gold" costumer, otherwise they are silver consumer 15 | */ 16 | 17 | let costumerPoints = 110; 18 | let typeCostumer = costumerPoints > 100 ? 'gold' : 'silver' 19 | console.log(typeCostumer) -------------------------------------------------------------------------------- /05 Objects/11- Math.js: -------------------------------------------------------------------------------- 1 | // 11- Math 2 | 3 | /* 4 | Math object 5 | Is one of the built-in objects in JavaScript. 6 | https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math 7 | 8 | Reviewing a few properties and methods from the "Math" object. 9 | */ 10 | 11 | // Pi property 12 | const pi = Math.PI 13 | console.log(pi) 14 | 15 | 16 | // Random method 17 | console.log(Math.random()) 18 | // The random method returns a random number between 0 and 1. In case we want to specify the range we can use a function. 19 | function getRandom(min, max) { 20 | return Math.random() * (max - min) + min; 21 | }; 22 | 23 | // Round method 24 | console.log(Math.round(1.954)); 25 | 26 | // Max method 27 | console.log(Math.max(1, 2, 5, 4, 7, 9, 6)); 28 | // Pass to it several numbers and it will return the max. 29 | 30 | // Min method 31 | console.log(Math.min(1, 2, 5, 4, 7, 9, 6)); 32 | // Pass to it several numbers and it will return the min. 33 | -------------------------------------------------------------------------------- /05 Objects/08- Enumerating Properties of an Object.js: -------------------------------------------------------------------------------- 1 | // 08- Enumerating Properties of an Object 2 | 3 | 4 | /* 5 | There are different ways to iterate over the properties of an object. 6 | We saw the for loops 7 | */ 8 | 9 | const circle = { 10 | radius: 1, 11 | draw() { 12 | console.log('Draw'); 13 | } 14 | } 15 | 16 | // Using the for..in loop to get the properties and values of an object 17 | for (let key in circle) { 18 | console.log(key, circle[key]); 19 | } 20 | 21 | for (let key of Object.keys(circle)) { // The "Object.keys()" method will return an array of strings with the object properties. 22 | console.log(key); 23 | } 24 | 25 | for (let entry of Object.entries(circle)) { // The "Object.entries()" method will return an array with the object key value pair. 26 | console.log(entry); 27 | } 28 | 29 | if ('radius' in circle) console.log('Yes') // With the in operator we can check if a given property exists in an object. -------------------------------------------------------------------------------- /07 Functions/03- Arguments.js: -------------------------------------------------------------------------------- 1 | // 03 - Arguments 2 | 3 | /* 4 | JavaScript is dynamic language 5 | He have the same concept in the arguments of a function 6 | */ 7 | 8 | function sum(a, b) { 9 | return a + b; 10 | } 11 | 12 | console.log(sum(1, 2)); // This will return 3 as expected 13 | console.log(sum(1)); // This will return NaN (Not a Number). Because the function is returning 1 + undefined 14 | console.log(sum()); // This will return NaN (Not a Number). Because the function is returning undefined + undefined 15 | console.log(sum(1, 2, 3, 4, 5)); // This will return 3. Only the first two arguments are used, the rest is being ignored. 16 | // The point is we do not get an error. 17 | 18 | // If want to have the flexibility to pass as many arguments as we want. 19 | // Every function in JavaScript as a special object called arguments 20 | 21 | function sum2() { 22 | let total = 0; 23 | for (let num of arguments) { 24 | total += num; 25 | } 26 | return total; 27 | } 28 | 29 | console.log(sum2(1, 2, 3, 4, 5)); -------------------------------------------------------------------------------- /06 Arrays/06- Removing Elements.js: -------------------------------------------------------------------------------- 1 | // 06- Removing Elements 2 | 3 | 4 | const numbers = [1, 2, 3, 4, 5, 6] 5 | 6 | // Remove the last element 7 | // The pop() method removes the last element from an array and returns that element. This method changes the length of the array. 8 | const last = numbers.pop(); 9 | console.log(last); 10 | console.log(numbers); 11 | 12 | // Remove the first element 13 | // The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array. 14 | const first = numbers.shift(); 15 | console.log(first); 16 | console.log(numbers); 17 | 18 | // Remove one or more elements from the middle 19 | // The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. 20 | 21 | 22 | const elementsRemoved = numbers.splice(1, 2); // With the "splice()", it will remove n elements counting from the indicated index. 23 | console.log(elementsRemoved); 24 | console.log(numbers); 25 | -------------------------------------------------------------------------------- /06 Arrays/20- Exercise 4- Moving an Element.js: -------------------------------------------------------------------------------- 1 | // 20 - Exercise 4 - Moving an Element 2 | 3 | const numbers = [1, 2, 3, 4]; 4 | 5 | const output = move(numbers, 0, 4); 6 | console.log(output); 7 | console.log(numbers); 8 | 9 | function move(array, index, offset) { 10 | const output = [...array]; 11 | const itemToMove = output.splice(index, 1)[0]; 12 | const positionToInsert = index + offset; 13 | if (positionToInsert >= 0 && positionToInsert <= numbers.length) { 14 | output.splice(positionToInsert, 0, itemToMove); 15 | return output; 16 | } else { 17 | console.error('Invalid offset'); 18 | } 19 | 20 | } 21 | 22 | 23 | // Mosh solution 24 | 25 | function moveMosh(array, index, offset) { 26 | const position = index + offset; 27 | if (position >= array.length || position < 0) { 28 | console.error('Invalid offset'); 29 | return; 30 | } 31 | const output = [...array]; 32 | const element = output.splice(index, 1)[0]; 33 | output.splice(position, 0, element); 34 | return output; 35 | } 36 | -------------------------------------------------------------------------------- /01 Getting Started/05- Separation of Concerns.md: -------------------------------------------------------------------------------- 1 | # 05- Separation of Concerns 2 | 3 | Although we can write the JavaScript code in the ` 24 | 25 | 26 | ``` 27 | -------------------------------------------------------------------------------- /07 Functions/04- The Rest Operator.js: -------------------------------------------------------------------------------- 1 | // 04- The Rest Operator 2 | 3 | // If we want a function with varying number of parameters we can use the rest operator. It should not be mistaken by the spread operator 4 | 5 | // Syntax 6 | function f(a, b, ...theArgs) { 7 | // ... 8 | } 9 | 10 | /* 11 | Description 12 | A function's last parameter can be prefixed with ... which will cause all remaining (user supplied) arguments to be placed within a "standard" JavaScript array. 13 | 14 | Only the last parameter can be a "rest parameter". 15 | */ 16 | 17 | function sum(...args) { 18 | return args.reduce((a, b) => a + b); // Here we use the reduce method to sum all the values in the array args 19 | } 20 | 21 | console.log(sum(1, 2, 3, 4, 5)); 22 | 23 | // For example we could use this function to calculate the total of a shopping cart. The rest operator has to be the last parameter. 24 | function sumShoppingCart(discount, ...prices) { 25 | let total = prices.reduce((a, b) => a + b); 26 | return total * (1 - discount); 27 | } 28 | 29 | console.log(sumShoppingCart(0.1, 50, 30)); 30 | -------------------------------------------------------------------------------- /05 Objects/03- Constructor Functions.js: -------------------------------------------------------------------------------- 1 | // 03- Constructor Functions 2 | /* 3 | The Constructor Functions job is to construct or create new objects. 4 | For this types of function we use Pascal Notation instead of Camel Notation 5 | 6 | Camel Notation: oneTwoThree 7 | Pascal Notation: OneTwoThree 8 | 9 | In this type of functions instead of returning an object we inicialize an object. 10 | 11 | There is really no difference between factory and constructor function. 12 | The Constructor is familiar to programers of C# or Java. 13 | */ 14 | 15 | function Circle(radius) { 16 | this.radius = radius; 17 | this.draw = function draw() { 18 | console.log('Draw') 19 | }; 20 | }; 21 | 22 | // To create a new object using this function 23 | const circle = new Circle(1) 24 | 25 | /* 26 | When we use the "new operator 3 thing happen": 27 | 1. This operator creates an empty JavaScript object; 28 | 2. Then it will set "this" operator statement to point to the empty object; 29 | 3. Finally the "new" operator will return the object from the function. 30 | */ -------------------------------------------------------------------------------- /02 Basics/03- Primitive Types.js: -------------------------------------------------------------------------------- 1 | // 03 Primitive Types 2 | 3 | /* 4 | Whats kind of values can be assigned to a variable 5 | In JavaScript we have to categories of types 6 | 1 Primitives or Value Types 7 | 2 Reference Types 8 | 9 | Primitives 10 | String ---> 'Hello World' ---> 11 | Numbers ---> 10 ---> 3.14 12 | Boolean ---> true ---> false 13 | Symbol 14 | undefined ---> undefined 15 | null (object) ---> null 16 | 17 | Reference types 18 | Objects 19 | Array 20 | Function 21 | */ 22 | 23 | let typeString = "String"; // String literal. 24 | let typeNumber = 4; // Number literal, in JavaScript we don't have tow kinds of numbers like integer and float. 25 | let typeBoolean = true; // Boolean literal, in this case true. 26 | let typeBoolean = false; // Boolean literal, here false. 27 | let typeUndefined; // Type undefined. 28 | let typeUndefined = undefined; // Type undefined explicit declared. 29 | let typeNull = null; // Type null. We use null when we want to clear the value of the variable. -------------------------------------------------------------------------------- /02 Basics/04- Dynamic Typing.js: -------------------------------------------------------------------------------- 1 | // 04 Dynamic Typing 2 | 3 | 4 | /* 5 | JavaScript is a dynamic language. 6 | 7 | We have two types of programing languages 8 | Static languages (Statically-typed) 9 | In static languages when we declare a variable, the type of that variable is set and can not be changed. 10 | For example "string name = 'Miguel'", this variable is a of type string and can not be changed. 11 | Dynamic languages (Dynamically-typed) 12 | In a dynamic language the type of a variable can change at runtime. 13 | */ 14 | 15 | let typeString = "String"; 16 | let typeNumber = 4; 17 | 18 | console.log(typeof typeString); // string 19 | console.log(typeof typeNumber); // number 20 | 21 | typeString = 15 22 | typeNumber = "I am a string now" 23 | 24 | console.log(typeof typeString); // number 25 | console.log(typeof typeNumber); // string 26 | 27 | // This is what we call a dynamic language, the type of this variables will be determined at runtime, base on the value er assign to them. 28 | 29 | let typeNull = null; 30 | console.log(typeof typeNull); // object -------------------------------------------------------------------------------- /03 Operators/02- Arithmetic Operators.js: -------------------------------------------------------------------------------- 1 | // 02- Arithmetic Operators 2 | 3 | 4 | /* 5 | There are the arithmetic operator in JavaScript 6 | + Addition 7 | - Subtraction 8 | * Multiplication 9 | / Division 10 | % Modulus (division remainder) 11 | ** Exponentiation 12 | ++ Increment 13 | -- Decrement 14 | */ 15 | 16 | let x = 10; 17 | let y = 3; 18 | 19 | console.log(x + y); 20 | console.log(x - y); 21 | console.log(x * y); 22 | console.log(x / y); 23 | console.log(x % y); 24 | console.log(x ** y); // x to the power of y 25 | 26 | 27 | // ++ Incremete operator behaves differently depending on where we put the operator. 28 | console.log(++x); // If we put increment before x, first the value of x first will be incremented by 1, and then we see x it in the console. 29 | console.log(x++); // If we put increment after x, first we see it in the console, and them the value of x will be incremented by 1. 30 | console.log(x); 31 | 32 | // -- Decrement operator behaves just like the Increment, but subtract 1. 33 | console.log(--x); 34 | console.log(x--); 35 | console.log(x); -------------------------------------------------------------------------------- /06 Arrays/03- Finding Elements (Primitives).js: -------------------------------------------------------------------------------- 1 | // 03- Finding Elements (Primitives) 2 | 3 | 4 | const numbers = [1, 2, 3, 4, 1, 6, 2]; 5 | 6 | console.log(numbers.indexOf(1)); 7 | console.log(numbers.indexOf('a')); 8 | /* 9 | The "indexOf()" takes two parameters: 10 | The item we are looking for 11 | The index to start from (optional paramter) 12 | This method will return the index of the first occurrence of that item. 13 | In case the item is not found it will return "-1". 14 | */ 15 | 16 | console.log(numbers.lastIndexOf(1)); 17 | /* 18 | The "lastIndexOf()" takes two parameters: 19 | The item we are looking for 20 | The index to start from (optional paramter) 21 | This method will return the index of the last occurrence of that item. 22 | In case the item is not found it will return "-1". 23 | */ 24 | 25 | 26 | // To verify if a given elements exist in an array 27 | console.log(numbers.indexOf(1) !== -1); // This expression will return true or false. Depending if the element exist in the array. 28 | 29 | // This a new better method to achieve the same thing. 30 | console.log(numbers.includes(1)); 31 | console.log(numbers.includes('a')); -------------------------------------------------------------------------------- /02 Basics/07- Functions.js: -------------------------------------------------------------------------------- 1 | // 07 Functions 2 | 3 | /* 4 | Functions are one of the fundamentals building blocks of JavaScript 5 | A function is basically a set of statements tha performs a task or calculates value. 6 | We declare a function with the keyword function and the the name of the function. 7 | function myFunction { 8 | 9 | } 10 | Between the curly brackets {} is the body of the functions, and it's were we add all the statements we want to our function. 11 | The statements in the function must end with semicolon ";" but the function just ends int } 12 | */ 13 | 14 | 15 | function greet() { 16 | console.log('Hello World'); 17 | } 18 | 19 | greet(); 20 | 21 | // A function can also have one or more parameters. Parameters are like variables but they only exist inside the function. 22 | function greetPerson(firstName, lastName) { 23 | console.log("Hello " + firstName + " " + lastName); 24 | } 25 | 26 | greetPerson('Miguel', 'Pimenta'); // Now we pass the arguments to the function. 27 | greetPerson('Miguel'); // If we don't pass an argument it will return the default value for variable "undefined". 28 | greetPerson(); -------------------------------------------------------------------------------- /05 Objects/17- Exercise 3- Object Equality.js: -------------------------------------------------------------------------------- 1 | // 17- Exercise 3- Object Equality 2 | 3 | 4 | function Address(street, city, zipCode) { 5 | this.street = street; 6 | this.city = city; 7 | this.zipCode = zipCode; 8 | }; 9 | 10 | 11 | let address1 = new Address('Rua Afonso Braz 505', 'São Paulo', '04511-011'); 12 | 13 | let address2 = new Address('Rua Augusta 2099', 'São Paulo', '01413-000'); 14 | 15 | let address3 = new Address('Rua Afonso Braz 505', 'São Paulo', '04511-011'); 16 | 17 | 18 | function areEqual(address1, address2) { 19 | return address1.street === address2.street && 20 | address1.city === address2.city && 21 | address1.zipCode === address2.zipCode; 22 | } 23 | 24 | console.log(areEqual(address1, address3)); 25 | 26 | function areSame(address1, address2) { // Function to check if two objects are pointing to the same object. They are referencing the same object. 27 | if (address1 === address2) 28 | return true 29 | else 30 | return false 31 | } 32 | 33 | console.log(areSame(address1, address2)); 34 | 35 | // Mosh solution 36 | function areSame(address1, address2) { 37 | return address1 === address2; 38 | } -------------------------------------------------------------------------------- /06 Arrays/21- Exercise 5- Count Occurrences.js: -------------------------------------------------------------------------------- 1 | // 21 - Exercise 5 - Count Occurrences 2 | 3 | const numbers = [1, 2, 3, 4, 1, 1]; 4 | 5 | const count = countOccurrences(numbers, 1); 6 | // console.log(count); 7 | 8 | const countReduce = countOccurrencesReduce(numbers, 1); 9 | console.log(countReduce); 10 | 11 | function countOccurrences(array, searchElement) { 12 | let counter = 0; 13 | array.forEach(element => { 14 | if (element === searchElement) counter += 1; 15 | }); 16 | return counter; 17 | } 18 | 19 | function countOccurrencesReduce(array, searchElement) { 20 | let counter = array.reduce((accumulator, currentValue) => { 21 | if (currentValue === searchElement) { 22 | accumulator += 1 23 | return accumulator; 24 | } else { 25 | return accumulator; 26 | } 27 | }, 0); 28 | return counter 29 | } 30 | 31 | // MoshSolution 32 | 33 | function countOccurrencesMosh(array, searchElement) { 34 | return array.reduce((accumulator, current) => { 35 | const occurrence = (current === searchElement) ? 1 : 0 36 | return accumulator + occurrence; 37 | }, 0); 38 | } -------------------------------------------------------------------------------- /05 Objects/13- Template Literals.js: -------------------------------------------------------------------------------- 1 | // 13- Template Literals 2 | 3 | /* 4 | Template literals are enclosed by the backtick (` `) (grave accent) character instead of double or single quotes. 5 | Template literals can contain placeholders. These are indicated by the dollar sign and curly braces (${expression}). 6 | The expressions in the placeholders and the text between the backticks (` `) get passed to a function. 7 | The default function just concatenates the parts into a single string. If there is an expression preceding the template literal (tag here), this is called a tagged template. In that case, the tag expression (usually a function) gets called with the template literal, which you can then manipulate before outputting. 8 | To escape a backtick in a template literal, put a backslash (\) before the backtick. 9 | Syntax 10 | `string text` 11 | 12 | `string text line 1 13 | string text line 2` 14 | 15 | `string text ${expression} string text` 16 | 17 | tag`string text ${expression} string text` 18 | */ 19 | 20 | let name = 'Miguel' 21 | 22 | const message = 23 | ` Hello ${name}, 24 | 25 | This is a message sent using template literals.`; 26 | 27 | console.log(message); 28 | -------------------------------------------------------------------------------- /05 Objects/09- Cloning an Object.js: -------------------------------------------------------------------------------- 1 | // 09- Cloning an Object 2 | 3 | /* 4 | In case we want to duplicate anm objects 5 | */ 6 | 7 | const circle = { 8 | radius: 1, 9 | draw() { 10 | console.log('Draw'); 11 | } 12 | }; 13 | 14 | const anotherCircle1 = {}; 15 | 16 | for (let key in circle) { 17 | anotherCircle1[key] = circle[key]; 18 | } 19 | // We could use the for..in loop do duplicate an object like in the example above. 20 | // But there are better ways to do this in modern JavaScript. 21 | 22 | // Using the "Object.assign()" method. 23 | const anotherCircle2 = Object.assign({}, circle); 24 | /* 25 | As a target we can pass an empty object, and then one or more source objects. 26 | This method copies the object to the new object and the returns it. 27 | This is the same as teh for..in loop above. 28 | */ 29 | 30 | const anotherCircle3 = Object.assign( 31 | {color: "red"}, 32 | circle 33 | ); 34 | // This is the same but in this case we are using an object with one property already in it. 35 | 36 | 37 | // Using the Spread Operator. Is a more simple way to clone an object. 38 | const anotherCircle4 = {...circle}; 39 | -------------------------------------------------------------------------------- /04 Control Flow/08- For...of.js: -------------------------------------------------------------------------------- 1 | // 08- For...of 2 | 3 | 4 | /* 5 | Definition and Usage 6 | The for/of statement loops through the values of an iterable object. 7 | 8 | JavaScript supports different kinds of loops: 9 | for - loops through a block of code a number of times 10 | for/in - loops through the properties of an object 11 | for/of - loops through the values of an iterable object 12 | while - loops through a block of code while a specified condition is true 13 | do/while - loops through a block of code once, and then repeats the loop while a specified condition is true 14 | 15 | Syntax: 16 | for (variable of iterable) { 17 | code block to be executed 18 | } 19 | 20 | variable: 21 | Required. For every iteration the value of the next property is assigned to the variable. Variable can be declared with const, let, or var. 22 | 23 | iterable: 24 | Required. An object that has iterable properties 25 | */ 26 | 27 | let cars = ['BMW', 'Volvo', 'Mini']; 28 | for (let car of cars) { 29 | console.log('The car is ' + car); 30 | } 31 | 32 | 33 | let colors = ['red', 'blue', 'green', 'yellow'] 34 | for (let color in colors) { 35 | console.log('The color is ' + color) 36 | } -------------------------------------------------------------------------------- /06 Arrays/16- Reducing an Array.js: -------------------------------------------------------------------------------- 1 | // 16- Reducing an Array 2 | 3 | /* 4 | With the ".reduce()" method we can reduce all the methods in the array to a single value. 5 | This value can be a string a number, a object or anything. 6 | 7 | This method takes a callback function with two values. 8 | Accumulator 9 | Current Value 10 | Optionally we can pass a second argument to the ".reduce()", that is the value to inicialize the accumulator. 11 | If we don't set the initial value for the accumulator, it will assume the first value of the array. 12 | */ 13 | 14 | const numbers = [1, 2, 3, 4, 5, 6]; 15 | // we could use a for...of loop to sum all the numbers, but the ".reduce()" method provides a cleaner implementation. 16 | 17 | let sum = numbers.reduce((accumulator, currentValue) => { 18 | return accumulator + currentValue; 19 | }, 0); 20 | 21 | console.log(sum); 22 | 23 | /* 24 | In this example we are using reduce to sum all the values in the array. 25 | In each time the current value is added to the accumulator 26 | a = 0 --- c = 1 ---> a = 1 27 | a = 1 --- c = 2 ---> a = 3 28 | a = 3 --- c = 3 ---> a = 6 29 | a = 6 --- c = 4 ---> a = 10 30 | a = 10 --- c = 5 ---> a = 15 31 | a = 15 --- c = 6 ---> a = 21 32 | 33 | Result 21 34 | */ -------------------------------------------------------------------------------- /03 Operators/05- Equality Operators.js: -------------------------------------------------------------------------------- 1 | // 05- Equality Operators 2 | 3 | /* 4 | As we seen in the last lectures we have different equality operators 5 | == equal to 6 | === equal value and equal type 7 | != not equal 8 | !== not equal value or not equal type 9 | */ 10 | 11 | // Strict Equality operator (checks for Type + Value) 12 | // Ina strict equality operator both values have to be of the same type and mus have the same value 13 | console.log(1 === 1) // This returns true because we are comparing the same type to the same value 14 | console.log('1' === 1) // This returns false because we are comparing different types, a string to number. 15 | 16 | 17 | // Lose Equality operator (checks for Value) 18 | console.log(1 == 1) // Here we get true 19 | console.log('1' == 1) // Here we also get true. Because this operator will look at the first part and see a string, then it will convert the second part to a string, and if they became the same value will return true. 20 | console.log(true == 1) // Here we get true as well. Because when we convert 1 to boolean it will be true 21 | console.log(false === 1) // Here we ge false. 22 | console.log(false == 0) // Here we also get true because 0 is a false value. 23 | -------------------------------------------------------------------------------- /05 Objects/06- Functions are Objects.js: -------------------------------------------------------------------------------- 1 | // 06- Functions are Objects 2 | 3 | /* 4 | In JavaScript functions are objects 5 | */ 6 | 7 | function Circle(radius) { 8 | this.radius = radius; 9 | this.draw = function draw() { 10 | console.log('Draw'); 11 | } 12 | } 13 | 14 | console.log(Circle.name); // This property returns the name of the function. 15 | 16 | console.log(Circle.length); // This property returns the number of arguments. 17 | 18 | console.log(Circle.constructor); // This returns the 'Function()' constructor that was used when we create a literal function. JavaScript uses that constructor to crete this object. 19 | // Like this: 20 | const Circle1 = new Function('radius', ` 21 | this.radius = radius; 22 | this.draw = function draw() { 23 | console.log('Draw') 24 | } 25 | `); 26 | 27 | Circle.call({}, 1) // With the "call()" method we can call a function, as the first argument we pass an empty object, and then the following arguments explicitly 28 | Circle.apply({}, [1, 2]) // With the "apply()" method, it works the same way as the call but we pass the arguments as an array. 29 | 30 | // Using the call or apply method is the same as the following code: 31 | const circle = new Circle(1) 32 | console.log(circle); 33 | -------------------------------------------------------------------------------- /07 Functions/09- Let vs Var.js: -------------------------------------------------------------------------------- 1 | // 09- Let vs Var 2 | 3 | /* 4 | let allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike the var keyword, 5 | which declares a variable globally, or locally to an entire function regardless of block scope. 6 | 7 | Just like const the let does not create properties of the window object when declared globally (in the top-most scope). 8 | */ 9 | 10 | function startLet() { 11 | for (let i = 0; i < 5; i++) { 12 | console.log(i); // The variable i is only accessible in the for loop block. 13 | } 14 | } 15 | 16 | function startVar() { 17 | for (var i = 0; i < 5; i++) { 18 | console.log(i); 19 | } 20 | console.log(i); // With the var keyword i is accessible outside or the for loop block. 21 | } 22 | 23 | // var ---> Creates functions scope variables 24 | // let & const ---> Create block scope variables 25 | 26 | var color = 'red'; // When we use var in global scope this variable is attached to the window object in browser. 27 | let age = 30; // Thi does not happens with the let or const keyword. 28 | 29 | // There is only one instance of the window object. We should avoid adding stuff to the window object. 30 | // When we define a function, they are technically a global scope function and they are added to the window object. 31 | 32 | -------------------------------------------------------------------------------- /02 Basics/06- Arrays.js: -------------------------------------------------------------------------------- 1 | // 06 Arrays 2 | 3 | /* 4 | When we are dealing with a list of objects we use an array. 5 | Like for example a list of products in a shopping cart in ana application. 6 | To create an array we use [] brackets. 7 | let myArray = [] 8 | This is whats is called an Array literal. 9 | In this case an empty array. 10 | An array is a data structure that we use to represent a list of items. 11 | */ 12 | 13 | let selectedColors = ['red', 'green']; 14 | console.log(selectedColors); 15 | 16 | /* 17 | Each element in the array as an index, stating in 0 18 | 0: red 19 | 1: green 20 | */ 21 | 22 | console.log(selectedColors[0]); // With this syntax we can access a index. 23 | 24 | /* 25 | JavaScript is Dynamic Language, the same principle applies to the array. 26 | The length of the array can change, and it can hold different type at the same time. 27 | */ 28 | 29 | selectedColors[2] = 'yellow' // With this syntax we are creating a new object i the array at index 2. If we jump a position it will create a <1 empty item> in that position. 30 | console.log(selectedColors) 31 | 32 | selectedColors[3] = 4 33 | console.log(selectedColors) 34 | 35 | console.log(typeof selectedColors) // An array is of type object. 36 | console.log(selectedColors.length) // An array as several properties pre defined. The length property returns the number of items in an array. -------------------------------------------------------------------------------- /02 Basics/05- Objects.js: -------------------------------------------------------------------------------- 1 | // 05 Objects 2 | 3 | /* 4 | Reference types 5 | Objects 6 | Array 7 | Function 8 | 9 | An object in JavaScript or other programing languages is like an object in real life, something that has properties 10 | Like a person that as name, age, height. 11 | When we are dealing with multiple related variable, we can put this variable inside an object. 12 | 13 | 14 | To declare an object we create a variable, or a constant if we don't want the properties to change, and set it to {} 15 | let object = {} 16 | This creates an object literal. 17 | Between the {} we can add one or more key/value pairs. 18 | */ 19 | let person = { 20 | name: 'Miguel', 21 | age: 37, 22 | height: 1.80 23 | }; 24 | 25 | console.log(person); 26 | 27 | // We have to ways to work with this properties 28 | 29 | // With the Dot Notation, we can read o write to a property 30 | person.name = 'Mosh' 31 | console.log(person.name) 32 | 33 | // With Bracket Notation 34 | person['name'] // We pass a string that determines the name of the target property. 35 | console.log(person['name']) 36 | 37 | let selection = "age" 38 | person[selection] // with the Bracket Notation we can use a variable which holds a string with the property name we want to access. 39 | console.log(person[selection]) 40 | 41 | 42 | person[selection] = 40 43 | console.log(person[selection]) -------------------------------------------------------------------------------- /07 Functions/01- Function Declarations vs Expressions.js: -------------------------------------------------------------------------------- 1 | // 01- Function Declarations vs Expressions 2 | 3 | /* 4 | Function declarations 5 | A function definition (also called a function declaration, or function statement) consists of the function keyword, followed by: 6 | 7 | The name of the function. 8 | A list of parameters to the function, enclosed in parentheses and separated by commas. 9 | The JavaScript statements that define the function, enclosed in curly brackets, {...}. 10 | For example, the following code defines a simple function named walk: 11 | */ 12 | 13 | // Function declaration 14 | function walk() { 15 | console.log("walk"); 16 | } 17 | 18 | /* 19 | Function expressions 20 | While the function declaration above is syntactically a statement, functions can also be created by a function expression. 21 | 22 | Such a function can be anonymous; it does not have to have a name. For example, the function walk could have been defined as: 23 | */ 24 | 25 | // Anonymous Function Expression 26 | let run = function () { 27 | console.log("run"); 28 | }; 29 | 30 | // Different from the Function Declaration a Function Expression should have a ; in the end 31 | 32 | // Named Function Expression 33 | const jump = function jump() { 34 | console.log("jump"); 35 | }; 36 | 37 | walk(); 38 | run(); 39 | jump(); 40 | 41 | // We can referent a function expression 42 | const move = run; 43 | 44 | move(); 45 | -------------------------------------------------------------------------------- /05 Objects/01- Basics.js: -------------------------------------------------------------------------------- 1 | // 01- Basics 2 | 3 | /* 4 | In javascript objects are collections of key value pairs. 5 | If we have properties that are highly related we want to encapsulate then inside of an object 6 | 7 | For example, if we are building an app to draw different shapes: 8 | In the case a circle 9 | */ 10 | 11 | let radius = 1; 12 | let x = 10; 13 | let y = 20; 14 | 15 | /* 16 | Instead of defining a bunch of variables like the one above, we should put this variables inside of an object. And then we can use this object anywhere in our program. 17 | In an object the values can be of any type in JavaScript. 18 | The purpose of an object is to group related variables, and quite often we also have functions that operate in these variables. 19 | */ 20 | 21 | const circle = { 22 | radius: 1, 23 | location: { 24 | x: 10, 25 | y: 20 26 | }, 27 | isVisible: true, 28 | draw: function() { 29 | console.log('Draw') 30 | }, 31 | move: function() { 32 | console.log('Move') 33 | } 34 | }; 35 | 36 | circle.draw(); 37 | 38 | /* 39 | This is object oriented style of programming (Object Oriented Programing - OOP). 40 | This is basically a style of programming that were a program is a collections of objects that talk to each other to perform some functionality. 41 | 42 | In programing terms if a functions is part of an object we call that function a method. 43 | */ -------------------------------------------------------------------------------- /05 Objects/14- Date.js: -------------------------------------------------------------------------------- 1 | // 14- Date 2 | 3 | /* 4 | JavaScript Date objects represent a single moment in time in a platform-independent format. 5 | Date objects contain a Number that represents milliseconds since 1 January 1970 UTC. 6 | 7 | Constructor 8 | Date() 9 | Creates a new Date object. 10 | 11 | Creates a JavaScript Date instance that represents a single moment in time in a platform-independent format. 12 | Date objects contain a Number that represents milliseconds since 1 January 1970 UTC. 13 | 14 | Syntax 15 | new Date() 16 | new Date(value) 17 | new Date(dateString) 18 | new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]) 19 | */ 20 | 21 | const dateNow = new Date(); // Using the date without any parameters returns the current date. 22 | console.log(dateNow); 23 | 24 | const date1 = new Date('September 15 2020') 25 | console.log(date1); 26 | 27 | let date2 = new Date(2020, 0, 11, 9, 0); // Month is 0 based indexed 28 | console.log(date2) 29 | 30 | // Date Object have several "get" and "set" methods. 31 | 32 | console.log(dateNow.getDate()); // Get the day of the month. 33 | 34 | console.log(dateNow.setFullYear(2029)); // to set to a different date. 35 | 36 | console.log(dateNow.toDateString()); // Converts date object to string. 37 | 38 | console.log(dateNow.toTimeString()); // Return the time component of the date object. 39 | 40 | console.log(dateNow.toISOString()); // Converts to a standard ISO format commonly used in web applications. -------------------------------------------------------------------------------- /06 Arrays/23- Exercise 7- Movies.js: -------------------------------------------------------------------------------- 1 | // 23 - Exercise 7 - Movies 2 | 3 | const movies = [ 4 | { title: 'a', year: 2018, rating: 4.5 }, 5 | { title: 'b', year: 2018, rating: 4.7 }, 6 | { title: 'c', year: 2018, rating: 3 }, 7 | { title: 'd', year: 2017, rating: 4.5 }, 8 | ] 9 | 10 | // All the movies in 2018 with rating > 4 11 | // Sort them by their rating 12 | // Descending order 13 | // Pick their title 14 | 15 | movies.sort((a, b) => { 16 | const ratingA = a.rating 17 | const ratingB = b.rating 18 | if (ratingA > ratingB) return -1; 19 | if (ratingA < ratingB) return 1; 20 | if (ratingA === ratingB) { 21 | if (a.title.toLowerCase() < b.title.toLowerCase()) return -1; 22 | if (a.title.toLowerCase() > b.title.toLowerCase()) return 1; 23 | if (a.title.toLowerCase() === b.title.toLowerCase()) return 0; 24 | } 25 | }); 26 | 27 | const filteredMovies = movies.filter(movie => movie.rating > 4 && movie.year === 2018); 28 | console.log(filteredMovies) 29 | 30 | filteredMovies.forEach(movie => console.log(movie.title)); 31 | 32 | // Mosh solution 33 | 34 | const moviesMosh = [ 35 | { title: 'a', year: 2018, rating: 4.5 }, 36 | { title: 'b', year: 2018, rating: 4.7 }, 37 | { title: 'c', year: 2018, rating: 3 }, 38 | { title: 'd', year: 2017, rating: 4.5 }, 39 | ] 40 | 41 | const titles = moviesMosh 42 | .filter(m => m.year === 2018 && m.rating >= 4) 43 | .sort((a, b) => a.rating - b.rating) 44 | .reverse() 45 | .map(m => m.title); 46 | 47 | console.log(titles); -------------------------------------------------------------------------------- /06 Arrays/10- Iterating an Array.js: -------------------------------------------------------------------------------- 1 | // 10- Iterating an Array 2 | 3 | 4 | 5 | const numbers = [1, 2, 3, 4, 5, 6] 6 | 7 | /* 8 | for...of loop 9 | The for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables. 10 | It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object. 11 | */ 12 | 13 | for (let number of numbers) 14 | console.log(number); 15 | 16 | 17 | /* 18 | forEach() 19 | The forEach() method executes a provided function once for each array element. 20 | 21 | Syntax 22 | arr.forEach(callback(currentValue [, index [, array]])[, thisArg]) 23 | 24 | Parameters 25 | callback: Function to execute on each element. It accepts between one and three arguments: 26 | 27 | currentValue: The current element being processed in the array. 28 | 29 | index (Optional): The index of currentValue in the array. 30 | 31 | array (Optional): The array forEach() was called upon. 32 | 33 | thisArg (Optional): Value to use as this when executing callback. 34 | 35 | Return value 36 | undefined 37 | */ 38 | 39 | numbers.forEach(function(number) { 40 | console.log(number); 41 | }); 42 | 43 | // The same, but using an Arrow function. 44 | numbers.forEach(number => console.log(number)); 45 | 46 | // Applying the "index" parameter in to get the index of each element. 47 | numbers.forEach((numbers, index) => console.log(index, numbers)); -------------------------------------------------------------------------------- /07 Functions/05- Default Parameters.js: -------------------------------------------------------------------------------- 1 | // 05- Default Parameters 2 | 3 | /* 4 | Syntax 5 | function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) { 6 | statements 7 | } 8 | 9 | Description 10 | In JavaScript, function parameters default to undefined. However, it's often useful to set a different default value. This is where default parameters can help. 11 | 12 | In the past, the general strategy for setting defaults was to test parameter values in the function body and assign a value if they are undefined. 13 | 14 | In the following example, if no value is provided for b when multiply is called, b's value would be undefined when evaluating a * b and multiply would return NaN. 15 | */ 16 | 17 | function interests(principal, rate, years) { 18 | return ((principal * rate) / 100) * years; 19 | } 20 | 21 | console.log(interests(10000, 3.5, 5)); 22 | 23 | 24 | // If we want to have default value for interest rate and years 25 | function interests1(principal, rate = 3.5, years = 5) { 26 | rate = rate || 3.5 // We could user the or operator 27 | year = year || 5 28 | return ((principal * rate) / 100) * years; 29 | } 30 | 31 | console.log(interests1(10000)); 32 | 33 | // From ES6 there is a new way to set the defaults values 34 | function interestsDefault(principal, rate = 3.5, years = 5) { 35 | return ((principal * rate) / 100) * years; 36 | } 37 | 38 | console.log(interestsDefault(10000, 3.5, 5)); 39 | 40 | // Once we give a paramter a default value, all the following parameters should also have a default value. 41 | 42 | -------------------------------------------------------------------------------- /01 Getting Started/02- What is JavaScript.md: -------------------------------------------------------------------------------- 1 | # 02- What is JavaScript 2 | 3 | ## What is JavaScript? 4 | 5 | Is one of them most popular and wildly used programming languages. You can work as a Front-end developer, back-end developer, or full-stack developer. 6 | 7 | ## Whats can you do with it? 8 | 9 | In the early days JavaScript was only used in the browsers to build interactive webpages. Back then some developers refereed to JavaScript as a "toy language" 10 | But is evolved so much, due to companies and community support, that this days we can build: 11 | 12 | - Full Web / Mobile apps 13 | - Real-time Networking apps 14 | - Command-line tools 15 | - Games 16 | 17 | ## Where does Javascript run? 18 | 19 | JavaScript as original design to run only in browsers. In 2009 a engineer called Ryan Doll took the open source JS code from Google Chrome V8 JvaScript engine and embedded it inside a C++ program. He called that program Node. So Node is a C++ program that includes Google Chrome V8 JvaScript engine. With this we can run JavaScript outside the browser. Browser and Node provide a rutim environment to run JavaScript. 20 | 21 | ![Javascript](./images/01-01.png "Javascript") 22 | 23 | ## Whats is ECMAScript? 24 | 25 | ECMAScript is a specification, and JavaScript is a programing language that confirms to that specification. The first version of ECMAScript was released in 1997, than starting from 2015 they have been working on anual releases of new specification. So in 2015 they released ES2015/ES6. 26 | 27 | ![ECMAScript](./images/01-02.png "ECMAScript") 28 | -------------------------------------------------------------------------------- /04 Control Flow/20- Exercise- Prime Numbers.js: -------------------------------------------------------------------------------- 1 | // 20- Exercise- Prime Numbers 2 | 3 | /* 4 | In maths we have to type of numbers 5 | Prime number are numbers whose factors are only 1 and itself 6 | Composite number as many factors 7 | 8 | 11 ---> 1, 11 ---> 11 is Prime because only has two factors. 9 | 12 ---> 1, 2, 3, 6, 12 ---> 12 is composite because is has more than two factors. 10 | */ 11 | 12 | function showPrime(limit) { 13 | for (let i = 1; i <= limit; i++) { 14 | let counter = 0; 15 | for (let x = 1; x <= limit; x++) { 16 | if (i % x === 0) counter++; 17 | } 18 | if (counter === 2) console.log(i); 19 | } 20 | } 21 | 22 | showPrime(20) 23 | 24 | 25 | // Mosh solution 26 | function showPrime(limit) { 27 | for (let number = 2; number <= limit; number++) { 28 | let isPrime = true; 29 | for (let factor = 2; factor < number; factor++) { 30 | if (number % factor === 0) { 31 | isPrime = false; 32 | break; 33 | } 34 | } 35 | if (isPrime) console.log(number); 36 | } 37 | } 38 | 39 | 40 | // Solution applying the Single Responsibility Principle 41 | 42 | function isPrime(number) { 43 | for (let factor = 2; factor < number; factor++) 44 | if (number % factor === 0) return false; 45 | return true 46 | } 47 | 48 | 49 | function showPrime(limit) { 50 | for (let number = 2; number <= limit; number++) 51 | if (isPrime(number)) console.log(number); 52 | } -------------------------------------------------------------------------------- /05 Objects/05- Constructor Property.js: -------------------------------------------------------------------------------- 1 | // 05- Constructor Property 2 | 3 | /* 4 | Every object in JavaScript has a property called "constructor" that references the function that was used to create that objects 5 | */ 6 | 7 | // Factory Function 8 | function createCircle (radius, x, y) { 9 | return { 10 | radius, // in JavaScript if our key and value are the same "radius: radius", we can make our code sorter and simply remove the value. 11 | location: { 12 | x, 13 | y 14 | }, 15 | draw() { // For functions we don't need the full function syntax to define the function. 16 | console.log('Draw') 17 | }, 18 | move() { 19 | console.log('Move') 20 | }, 21 | }; 22 | } 23 | 24 | const circleFactory = createCircle(1, 2, 3); 25 | console.log(circleFactory.constructor); 26 | 27 | /* 28 | [Function: Object] In this case it returns a built-in constructor function "Object()". 29 | When we create an object using the object literal syntax, internally JavaScript uses the "Object()" 30 | let x = {}; JavaScript will do this: 31 | let x = new Object() 32 | */ 33 | 34 | 35 | // Constructor Function 36 | function Circle(radius) { 37 | this.radius = radius; 38 | this.draw = function draw() { 39 | console.log('Draw') 40 | } 41 | } 42 | 43 | const circleConstructor = new Circle(1); 44 | console.log(circleConstructor.constructor); // [Function: Circle] This returns our circle function that we use to create this object. 45 | -------------------------------------------------------------------------------- /02 Basics/01- Variables.js: -------------------------------------------------------------------------------- 1 | // 01 Variables 2 | 3 | /* 4 | In programing we use a variable to store data temporarily in a computer memory. 5 | So we store and give that variable location a name. 6 | With this name we can read the data at a given location in the future. 7 | */ 8 | 9 | // var variableName; 10 | 11 | // Since ES6 we use the "let" keyword to create a variable. There are issue with the "var" key word, we will learn later. 12 | 13 | let variableName; 14 | console.log(variableName) 15 | // prints "undefined" in the console 16 | // By default variable that we define in JavaScript there value is undefined. 17 | 18 | /* 19 | We can also initialize a variable give it a value 20 | */ 21 | 22 | let name = 'Miguel' 23 | console.log(name) 24 | 25 | /* 26 | We have a few rule to name a variable: 27 | 1 Cannot be a keyword like "if". 28 | 2 Should be meaningful, so anyone can understand the code, use descriptive names. 29 | 3 They can not start wit a number 30 | 4 They can not contain a space or a hyphen (-) 31 | 5 Use camelCase, the first letter is lowercase and the first letter of every word after is uppercase. 32 | 6 They are case sensitive 33 | */ 34 | 35 | // To set multiple variables i the same line 36 | let firstName, lastName; 37 | let firstName = 'Miguel', lastName; 38 | let firstName, lastName = "Pimenta"; 39 | let firstName = 'Miguel', lastName = 'Pimenta'; 40 | 41 | // But the modern best practice is to declare each variable in a single line 42 | let firstName = 'Miguel'; 43 | let lastName = 'Pimenta'; -------------------------------------------------------------------------------- /03 Operators/07- Logical Operators.js: -------------------------------------------------------------------------------- 1 | // 07- Logical Operators 2 | 3 | /* 4 | Logical operators are used to determine the logic between variables or values. To make decisions on multiple conditions. 5 | These are the logical operators 6 | && (and operator) With the and operator both conditions or operator have to be true. 7 | || (or operator) With the or operator only one of the conditions has to be true. 8 | ! (not operator) The not operator converts true to false and vice-versa. 9 | x = 6 and y = 3 10 | (x < 10 && y > 1) is true 11 | (x === 5 || y === 5) is false 12 | !(x === y) is true 13 | */ 14 | 15 | // Lets say we want to determine if some one is eligible for a loan, based on is income and credit score. 16 | 17 | let hiIncome = false 18 | let goodCreditScore = true 19 | 20 | let eligibleForLoan = hiIncome && goodCredit // With and operator "&&" applicant has to have high income and good credit score to be eligible for loan. 21 | console.log(eligibleForLoan) 22 | 23 | eligibleForLoan = hiIncome || goodCredit // With or operator "||" applicant has to have high income or good credit score to be eligible for loan. If one of them is true elidible for loan will be true. 24 | console.log(eligibleForLoan) 25 | 26 | let applicationRefused = !eligibleForLoan 27 | console.log(applicationRefused) 28 | // With not operator "!" it will convert true to false and false to true. 29 | //So if the applicant is not eligible for loan, meaning "eligibleForLoan = false", is application will be refused meaning "applicationRefused = !eligibleForLoan" will return true. -------------------------------------------------------------------------------- /06 Arrays/15- Mapping an Array.js: -------------------------------------------------------------------------------- 1 | // 15- Mapping an Array 2 | 3 | 4 | /* 5 | With the ".map()" method we can map each item in the arry to something else. 6 | This method takes a callback function as an argument, and returns a new array. 7 | It does not modify the original array. 8 | 9 | This method is useful, for example, to convert elements in an array to html markup. 10 | */ 11 | 12 | const numbers = [1, -2, 2, -1, 3, 4]; 13 | 14 | let mappedToHtml = numbers.map(function(value) { 15 | return '
  • ' + value + '
  • '; // We convert each element to html. 16 | }); 17 | 18 | console.log(mappedToHtml); 19 | 20 | const html = ''; // with the '.join()' method we convert the array to a string. 21 | // I am using the "\n" escape sequence so the html looks well formatted. 22 | 23 | console.log(html); 24 | 25 | // Chaining different methods is a useful feature. 26 | 27 | const filteredToMapped = numbers 28 | .filter(number => number > 0) 29 | .map(number => '
  • ' + number + '
  • '); 30 | /* 31 | In this example chaining the ".filter()" method and then the ".map()" method. 32 | First we filter values greater than 0 and them we map each element to a list html tag. 33 | In this implementation we the arrow function for a cleaner code. 34 | */ 35 | 36 | console.log(filteredToMapped); 37 | 38 | // Another useful way to use the ".map()" method is to convert the elements to an object. 39 | 40 | const mappedToObj = numbers.map(number => ({key: number})); // We set "key" as the key and each element in the array as the value. 41 | console.log(mappedToObj); -------------------------------------------------------------------------------- /01 Getting Started/04- JavaScript in Browsers.md: -------------------------------------------------------------------------------- 1 | # 04- JavaScript in Browsers 2 | 3 | ## Script Html tag 4 | 5 | To write JavaScript code in the html file we need a scrip element `` . 6 | 7 | There two place were we can add a script element, in the `` section or in the `` section. 8 | 9 | The best practice is to put the script element in the body section after all the HTML code. Why that best practice: 10 | 11 | 1. Because the browser parse the html file from top to bottom. If we put the script code in the head section, our browser may get busy parsing and executing that JavaScript code, and wont be able to render the html in the page 12 | 2. Because almost always the JavaScript code we put in the script element needs to talk to the html element. So by adding the code in the bottom of the `` section we make sure that all the html is renders first. 13 | 14 | There are exception but this are the basic rules. 15 | 16 | So in the bottom of the body section we add a script element 17 | 18 | In that element we can write JavaScript code. 19 | 20 | To add comments to JavaScript we use double forward slashes `//` 21 | 22 | ```html 23 | 24 | 25 | 26 | 27 | 28 | 29 | The Ultimate JavaScript Mastery Series - Part 1 30 | 31 | 32 | 36 | 37 | 38 | ``` 39 | -------------------------------------------------------------------------------- /06 Arrays/12- Sorting Arrays.js: -------------------------------------------------------------------------------- 1 | // 12- Sorting Arrays 2 | 3 | /* 4 | The "sort()" orders the elements in an array. 5 | It modifies the original array. 6 | */ 7 | 8 | 9 | 10 | const numbers = [2, 4, 3, 5, 1, 6]; 11 | numbers.sort(); 12 | console.log(numbers); 13 | 14 | 15 | const myArray = [2, 'a', 4, 3, 'c', 5, 1, 'd', 6, 'b']; 16 | myArray.sort(); 17 | console.log(myArray); 18 | 19 | /* 20 | If an array contains objects as its elements we need to pass a function as an argument to the "sort()" method. 21 | This functions should take two parameters and must follow the following logic: 22 | a < b ---> -1 23 | a > b ---> 1 24 | a === b ---> 0 25 | 26 | function(a, b) { 27 | if (a < b) return -1; 28 | if (a > b) return 1; 29 | if (a === b) return 0; 30 | } 31 | */ 32 | 33 | const courses = [ 34 | {id: 5, name: 'Python'}, 35 | {id: 2, name: 'JavaScript'}, 36 | {id: 3, name: 'Node.js'}, 37 | {id: 4, name: 'C++'}, 38 | {id: 1, name: 'Python'} 39 | ] 40 | 41 | courses.sort(function compare(a, b) { 42 | const nameA = a.name.toLowerCase(); // To compare string we must convert then to lower case or upper case. In computers letters represent correspond o a number, see ascii table. 43 | const nameB = b.name.toLowerCase(); 44 | 45 | if (nameA < nameB) return -1; 46 | if (nameA > nameB) return 1; 47 | if (nameA === nameB) { // With this block of code when the name property as the same value, the items will be sorted by the id property. 48 | if (a.id < b.id) return -1; 49 | if (a.id > b.id) return 1; 50 | if (a.id === b.id) return 0; 51 | } 52 | }); 53 | 54 | console.log(courses); -------------------------------------------------------------------------------- /04 Control Flow/13- Exercise 4- Demerit Points.js: -------------------------------------------------------------------------------- 1 | // 13- Exercise 4- Demerit Points 2 | 3 | 4 | /* 5 | Implement functions "checkSpeed()", it take one parameter, the speed of teh car. 6 | Speed Limit <= 70 ---> display ok message 7 | For every 5 km/h above the speed limit, they are going to get 1 point 8 | If speed above 180 km/h ---> Points >= 12 ---> License suspended 9 | */ 10 | 11 | 12 | // My solution 13 | function checkSpeed(speed) { 14 | let points; 15 | if (speed < 75) return "Ok"; 16 | else if (speed >= 75 && speed < 180) { 17 | points = (speed - 70) / 5; 18 | return points; 19 | } 20 | return "License suspended"; 21 | } 22 | 23 | 24 | let result = checkSpeed(130) 25 | console.log(result) 26 | 27 | 28 | // Mosh solution 29 | function checkSpeed(speed) { 30 | const speedLimit = 70; 31 | const kmPerPoint = 5 32 | if (speed < speedLimit + kmPerPoint) 33 | console.log("Ok"); 34 | else { 35 | const points = Math.floor((speed - speedLimit) / kmPerPoint); 36 | if (points >= 12) 37 | console.log("License suspended"); 38 | else 39 | console.log('Points', points); 40 | } 41 | } 42 | 43 | // For a better cleaner looking code 44 | function checkSpeed(speed) { 45 | const speedLimit = 70; 46 | const kmPerPoint = 5 47 | if (speed < speedLimit + kmPerPoint) { 48 | console.log("Ok"); 49 | return; 50 | } 51 | const points = Math.floor((speed - speedLimit) / kmPerPoint); 52 | if (points >= 12) 53 | console.log("License suspended"); 54 | else 55 | console.log('Points', points); 56 | } -------------------------------------------------------------------------------- /07 Functions/08- Local vs Global Scope.js: -------------------------------------------------------------------------------- 1 | // 08- Local vs Global Scope 2 | 3 | /* 4 | Scope determines the accessibility (visibility) of variables. 5 | 6 | JavaScript Scope 7 | In JavaScript there are two types of scope: 8 | Local scope 9 | Global scope 10 | 11 | JavaScript has code block scope: Each code block creates a new scope. 12 | 13 | Scope determines the accessibility (visibility) of these variables. 14 | 15 | Variables defined inside a code block are not accessible (visible) from outside the code block. 16 | */ 17 | 18 | const color = "red"; // This variable has global scope. We can acesses it anywhere 19 | 20 | function start() { 21 | const message = "hi"; // This variable is only accessible inside of the function. The scope of this constant is limited to the block in which it is define. 22 | const color = "blue"; // If we define a new variable "color" with local scope, it will override the variable with global scope. Local scope take precedence over global scope. 23 | console.log(color); 24 | if (true) { 25 | const another = "bye"; // This const it is only visible in the if block 26 | } 27 | // console.log(another); // If we try to log the "another" outside of the if block, we will have a Reference Error. 28 | 29 | for (let i = 0; i < 5; i++) { 30 | console.log(i); // The variable i is only accessible in the for loop code block. 31 | } 32 | } 33 | 34 | function stop() { 35 | const message = "bye"; // Although we have here another variable named "message", this is perfectly fine. This variable is in the local scope of the "stop()" function. 36 | } 37 | 38 | // In general we should avoid defining global variables, its considered a bad practice. 39 | // This applies to the let and const key words. -------------------------------------------------------------------------------- /04 Control Flow/07- For...in.js: -------------------------------------------------------------------------------- 1 | // 07- For...in 2 | 3 | /* 4 | Definition and Usage 5 | The for/in statement loops through the properties of an object. 6 | The block of code inside the loop will be executed once for each property. 7 | 8 | JavaScript supports different kinds of loops: 9 | for - loops through a block of code a number of times 10 | for/in - loops through the properties of an object 11 | for/of - loops through the values of an iterable object 12 | while - loops through a block of code while a specified condition is true 13 | do/while - loops through a block of code once, and then repeats the loop while a specified condition is true 14 | 15 | Note: Do not use the for/in statement to loop through arrays where index order is important. Use the for statement instead. 16 | 17 | Syntax: 18 | 19 | for (variable in object) { 20 | code block to be executed 21 | } 22 | 23 | variable: 24 | Required. A variable that iterates over the properties of an object 25 | In each iteration the variable will be assign a property. 26 | 27 | object: 28 | Required. The specified object that will be iterated 29 | */ 30 | 31 | let person = { 32 | firstName: 'John', 33 | lastName: 'Doe', 34 | age: 25 35 | }; 36 | 37 | for (let key in person) { 38 | console.log(key); 39 | console.log('The key is '+ key + ' and the value is ' + person[key]) 40 | } 41 | 42 | // We can also use the for...in loop in array but it is best to use the for...of loop. We are going to use the for...in loop for demo. 43 | 44 | let colors = ['red', 'blue', 'green', 'yellow'] 45 | 46 | for (let index in colors) { 47 | console.log(index); 48 | console.log('The color in index ' + index + ' is ' + colors[index]) 49 | } -------------------------------------------------------------------------------- /06 Arrays/07- Emptying an Array.js: -------------------------------------------------------------------------------- 1 | // 07- Emptying an Array 2 | 3 | 4 | /* 5 | We can use different approaches to empty an array. 6 | */ 7 | 8 | // Solution 1 9 | let numbers1 = [1, 2, 3, 4, 5, 6]; 10 | let another1 = numbers1; 11 | 12 | numbers1 = []; 13 | // if we use a constant "const" variable, this will not work because we can not reassign a value to a "const". 14 | console.log(numbers1); 15 | // In case we have other references to this object, like in this example another is referencing numbers, even if we reassign the numbers variable, the original array will still be in memory. 16 | console.log(another1); 17 | // If there are no references to the object eventually it will be removed from memory by the garbage collector. 18 | 19 | 20 | // Solution 2 21 | let numbers2 = [10, 20, 30, 40, 50, 60]; 22 | let another2 = numbers2; 23 | 24 | numbers2.length = 0; 25 | // Here we set the length property to 0. This will truncate the array removing all values. 26 | // With this method it does not matter if we have references to the object. 27 | // Its the original array that is being empty. 28 | console.log(numbers2); 29 | console.log(another2); 30 | 31 | 32 | // Solution 3 33 | let numbers3 = [100, 200, 300, 400, 500, 600]; 34 | let another3 = numbers3; 35 | 36 | numbers3.splice(0, numbers3.length); 37 | // With the "splice()" method, starting from index 0 and using as second argument the length of the array. 38 | 39 | 40 | // Solution 4 41 | let numbers4 = [1000, 2000, 3000, 4000, 5000, 6000]; 42 | let another4 = numbers4; 43 | 44 | while (numbers4.length > 0) { 45 | numbers4.pop(); 46 | } 47 | // Using the "pop()" method in a loop. In case we are dealing with a large array we may encounter performance issues. 48 | 49 | 50 | // Depending on the approach the best solution are 1 and 2. -------------------------------------------------------------------------------- /04 Control Flow/02- Switch...case.js: -------------------------------------------------------------------------------- 1 | // 02- Switch...case 2 | 3 | 4 | /* 5 | Definition and Usage 6 | The switch statement executes a block of code depending on different cases. 7 | The switch statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions. 8 | Use switch to select one of many blocks of code to be executed. This is the perfect solution for long, nested if/else statements. 9 | The switch statement evaluates an expression. The value of the expression is then compared with the values of each case in the structure. 10 | If there is a match, the associated block of code is executed. 11 | The switch statement is often used together with a break or a default keyword (or both). These are both optional: 12 | The break keyword breaks out of the switch block. This will stop the execution of more execution of code and/or case testing inside the block. 13 | If break is omitted, the next code block in the switch statement is executed. 14 | The default keyword specifies some code to run if there is no case match. There can only be one default keyword in a switch. 15 | Although this is optional, it is recommended that you use it, as it takes care of unexpected cases. 16 | 17 | switch(expression) { 18 | case n: 19 | code block 20 | break; 21 | case n: 22 | code block 23 | break; 24 | default: 25 | default code block 26 | } 27 | */ 28 | 29 | let role = 'guest'; 30 | 31 | switch (role) { 32 | case 'guest': 33 | console.log('Guest user'); 34 | break; 35 | case 'moderator': 36 | console.log('moderator user'); 37 | break; 38 | default: 39 | console.log('Unknown user'); 40 | } -------------------------------------------------------------------------------- /05 Objects/07- Value vs Reference Types.js: -------------------------------------------------------------------------------- 1 | // 07- Value vs Reference Types 2 | 3 | /* 4 | As we seen before in JavaScript we have two category of type 5 | 6 | Primitives Types (or Value Types) 7 | String 8 | Numbers 9 | Boolean 10 | Symbol 11 | undefined 12 | null (object) 13 | 14 | Reference Types 15 | Objects 16 | Array 17 | Function 18 | 19 | 20 | */ 21 | 22 | let x = 10; 23 | let y = x; 24 | 25 | x = 20; 26 | 27 | console.log(y); // It returns 10. 28 | //Primitives are independent, the value is stored inside of the variable. 29 | 30 | let xObj = {value: 10}; 31 | let yObj = x; 32 | 33 | x.value = 20; 34 | 35 | console.log(yObj); // It return 20. 36 | // In using object they are not stored in the variable. They are stored somewhere in the memory, and the address (or the reference) of that place in memory is store in the variable. 37 | 38 | // Primitives are copied by their value. 39 | // Objects are copied by their reference. 40 | 41 | 42 | let number = 10; 43 | 44 | function increase(number) { 45 | number++; 46 | } 47 | 48 | increase(number); 49 | console.log(number); // It returns 10. 50 | // When we call increase and pass the number variable to that functions as an argument. 51 | // The "number" variable is completely independent from the "number" paramter in the "increase()" function. 52 | // The "number" parameter is local to the "increase()" function. 53 | 54 | 55 | 56 | let obj = {value: 10}; 57 | 58 | function increase(obj) { 59 | obj.value++; 60 | } 61 | 62 | increase(obj); 63 | console.log(obj); // It returns { value: 11 }. 64 | 65 | // In this case we are not dealing with two independent copies. 66 | // So any changes made to that object will be visible in the variable. -------------------------------------------------------------------------------- /06 Arrays/05- Arrow Functions.js: -------------------------------------------------------------------------------- 1 | // 05- Arrow Functions 2 | 3 | /* 4 | An arrow function expression is a compact alternative to a traditional function expression, but is limited and can't be used in all situations. 5 | 6 | Differences & Limitations: 7 | Does not have its own bindings to this or super, and should not be used as methods. 8 | Does not have arguments, or new.target keywords. 9 | Not suitable for call, apply and bind methods, which generally rely on establishing a scope. 10 | Can not be used as constructors. 11 | Can not use yield, within its body. 12 | 13 | 14 | Syntax 15 | Basic syntax: 16 | 17 | One param. With simple expression return is not needed: 18 | param => expression 19 | 20 | Multiple params require parentheses. With simple expression return is not needed: 21 | (param1, paramN) => expression 22 | 23 | Multiline statements require body brackets and return: 24 | param => { 25 | let a = 1; 26 | return a + b; 27 | } 28 | 29 | Multiple params require parentheses. Multiline statements require body brackets and return: 30 | (param1, paramN) => { 31 | let a = 1; 32 | return a + b; 33 | } 34 | 35 | Advanced syntax: 36 | 37 | To return an object literal expression requires parentheses around expression: 38 | params => ({foo: "a"}) // returning the object {foo: "a"} 39 | 40 | Rest parameters are supported: 41 | (a, b, ...r) => expression 42 | 43 | Default parameters are supported: 44 | (a=400, b=20, c) => expression 45 | 46 | Destructuring within params supported: 47 | ([a, b] = [10, 20]) => a + b; // result is 30 48 | ({ a, b } = { a: 10, b: 20 }) => a + b; // result is 30 49 | */ 50 | 51 | 52 | const courses = [ 53 | { id: 1, name: 'a'}, 54 | { id: 2, name: 'b'} 55 | ]; 56 | 57 | const course = courses.find(course => course.name === 'a'); 58 | 59 | console.log(course); -------------------------------------------------------------------------------- /06 Arrays/13- Testing the Elements of an Array.js: -------------------------------------------------------------------------------- 1 | // 13- Testing the Elements of an Array 2 | 3 | /* 4 | To test elements in an array we can use the ".every()" method or the ".some()" method. 5 | 6 | The ".every()" method checks if all the elements in the array respect the indicated condition 7 | Returns true if every elements respects the condition. 8 | Returns false if at least one element does not respect the condition. It will pause searching on the first element it does not match the condition. 9 | 10 | The ".some()" method checks if at least one of the elements respects a given condition. 11 | Return true if at least one element respects the condition. 12 | Return false if not even one element respects the condition. 13 | 14 | Both this method take as an argument a callback function 15 | 16 | */ 17 | 18 | const numbers1 = [1, 2, 3, 4, 5, 6]; 19 | 20 | let allPositive = numbers1.every(function(value) { 21 | return value > 0; // If all the elements are greater than 0 it will return true. 22 | }); 23 | 24 | console.log('Numbers 1 all positive: ', allPositive); 25 | 26 | let atLeastOnePositive = numbers1.some(function(value) { 27 | return value > 0; // If at least one element is greater than zero it will return true. 28 | }); 29 | 30 | console.log('Numbers 1 at lest one positive: ', atLeastOnePositive); 31 | 32 | const numbers2 = [1, 2, -3, 0, -2, 3, 4]; 33 | 34 | allPositive = numbers2.every(function(value) { 35 | return value > 0; // If all the elements are greater than 0 it will return true. 36 | }); 37 | 38 | console.log('Numbers 2 all positive: ', allPositive); 39 | 40 | atLeastOnePositive = numbers2.some(function(value) { 41 | return value > 0; // If at least one element is greater than zero it will return true. 42 | }); 43 | 44 | console.log('Numbers 2 at lest one positive: ', atLeastOnePositive); 45 | -------------------------------------------------------------------------------- /04 Control Flow/04- While.js: -------------------------------------------------------------------------------- 1 | // 04- While 2 | 3 | /* 4 | Definition and Usage 5 | The while statement creates a loop that is executed while a specified condition is true. 6 | The loop will continue to run as long as the condition is true. It will only stop when the condition becomes false. 7 | JavaScript supports different kinds of loops: 8 | for - loops through a block of code a number of times 9 | for/in - loops through the properties of an object 10 | for/of - loops through the values of an iterable object 11 | while - loops through a block of code while a specified condition is true 12 | do/while - loops through a block of code once, and then repeats the loop while a specified condition is true 13 | 14 | Tip: Use the break statement to break out of a loop, and the continue statement to skip a value in the loop. 15 | 16 | Syntax 17 | while (condition) { 18 | code block to be executed 19 | } 20 | 21 | condition: 22 | Required. Defines the condition for running the loop (the code block). 23 | If it returns true, the loop will start over again, if it returns false, the loop will end. 24 | 25 | Note: If the condition is always true, the loop will never end. This will crash your browser. 26 | Note: If you are using a variable with the condition, initialize it before the loop, and increment it within the loop. 27 | If you forget to increase the variable, the loop will never end. This will also crash your browser. 28 | */ 29 | 30 | console.log('While loop 1') 31 | let i = 0; 32 | while (i <= 5) { 33 | let text = "The number is " + i; 34 | console.log(text) 35 | i++; 36 | } 37 | 38 | 39 | console.log('While loop 2') 40 | let index = 0; 41 | while (index <= 10) { 42 | if (index % 2 !== 0) { 43 | let text = 'Index is odd ' + index 44 | console.log(text) 45 | } 46 | index++; 47 | } -------------------------------------------------------------------------------- /05 Objects/02- Factory Functions.js: -------------------------------------------------------------------------------- 1 | // 02- Factory Functions 2 | 3 | /* 4 | In the last lesson we use the object literal syntax to create ann object. But in case we need to create more than one of teh same object. 5 | For a better implementation we use Factory and Constructor Functions. 6 | In this lesson we are looking at Factory Functions. 7 | Just like a factory producing products, this factory functions produce objects. 8 | */ 9 | 10 | // Create a new function and copy the object in it 11 | function createCircle () { 12 | const circle = { 13 | radius: 1, 14 | location: { 15 | x: 10, 16 | y: 20 17 | }, 18 | isVisible: true, 19 | draw: function() { 20 | console.log('Draw') 21 | }, 22 | move: function() { 23 | console.log('Move') 24 | } 25 | }; 26 | return circle 27 | } 28 | 29 | // We can improve syntax and make it shorter, and we can pass a parameter to the function. 30 | function createCircle (radius, x, y) { 31 | return { 32 | radius, // in JavaScript if our key and value are the same "radius: radius", we can make our code sorter and simply remove the value. 33 | location: { 34 | x, 35 | y 36 | }, 37 | draw() { // For functions we don't need the full function syntax to define the function. 38 | console.log('Draw') 39 | }, 40 | move() { 41 | console.log('Move') 42 | }, 43 | }; 44 | } 45 | 46 | /* 47 | With this Factory Function we have define our logic only in one place, and the we can call this function, in our program and pass to it different arguments. 48 | In case of a bug in the future there is only one place to modify. 49 | */ 50 | 51 | const circle1 = createCircle(1, 2, 3) 52 | circle1.draw() -------------------------------------------------------------------------------- /07 Functions/06- Getters and Setters.js: -------------------------------------------------------------------------------- 1 | // 06- Getters and Setters 2 | 3 | /* 4 | Getters 5 | The get syntax binds an object property to a function that will be called when that property is looked up. 6 | 7 | Description 8 | Sometimes it is desirable to allow access to a property that returns a dynamically computed value, 9 | or you may want to reflect the status of an internal variable without requiring the use of explicit method calls. 10 | In JavaScript, this can be accomplished with the use of a getter. 11 | 12 | It is not possible to simultaneously have a getter bound to a property and have that property actually hold a value, 13 | although it is possible to use a getter and a setter in conjunction to create a type of pseudo-property. 14 | 15 | 16 | Setters 17 | The set syntax binds an object property to a function to be called when there is an attempt to set that property. 18 | 19 | Description 20 | In JavaScript, a setter can be used to execute a function whenever a specified property is attempted to be changed. 21 | Setters are most often used in conjunction with getters to create a type of pseudo-property. 22 | It is not possible to simultaneously have a setter on a property that holds an actual value. 23 | */ 24 | 25 | const person = { 26 | firstName: 'Miguel', 27 | lastName: 'Pimenta', 28 | get fullName() { 29 | return `${this.firstName} ${this.lastName}` 30 | }, 31 | set fullName(name) { 32 | const nameParts = name.split(' '); 33 | this.firstName = nameParts[0]; 34 | this.lastName = nameParts[1]; 35 | } 36 | } 37 | 38 | console.log(person.fullName); // Here we print Miguel Pimenta using the getter 39 | 40 | person.fullName = 'Viviane Sedola' // Here with the setter we modify the full name to Viviane Sedola 41 | 42 | console.log(person.fullName) // Now with the getter the result is Viviane Sedola 43 | console.log(person) -------------------------------------------------------------------------------- /04 Control Flow/18- Exercise 9- Grade.js: -------------------------------------------------------------------------------- 1 | // 18- Exercise 9- Grade 2 | 3 | /* 4 | Calculate the grade of the student 5 | First calculate the average from an array of grade 6 | if: 7 | 01-59 ---> F 8 | 60-69 ---> D 9 | 70-79 ---> C 10 | 80-89 ---> B 11 | 90-100 ---> A 12 | */ 13 | 14 | function calculateGrade(marks) { 15 | let average = 0; 16 | for (mark of marks) 17 | average += mark / marks.length; 18 | if (average >= 0 && average < 60) return 'F' 19 | else if (average >= 60 && average < 70) return 'D' 20 | else if (average >= 70 && average < 80) return 'C' 21 | else if (average >= 80 && average < 90) return 'B' 22 | else return 'A' 23 | } 24 | 25 | const marks = [80, 80, 50]; 26 | 27 | let result = calculateGrade(marks) 28 | console.log(result) 29 | 30 | // Mosh solution 31 | function calculateGrade(marks) { 32 | let sum = 0; 33 | for (let mark of marks) 34 | sum += mark; 35 | let average = sum / marks.length; 36 | 37 | if (average < 60) return 'F'; 38 | if (average < 70) return 'D'; 39 | if (average < 80) return 'C'; 40 | if (average < 90) return 'B'; 41 | return 'A'; 42 | } 43 | 44 | 45 | // Mosh solution for cleaner code to respect the Single Responsibility Principle 46 | // We should separate our function in smaller functions each one with its on purpose. 47 | // In the case separate de average calculation from the grade. 48 | 49 | function calculateAverage(array) { 50 | let sum = 0; 51 | for (let value of array) 52 | sum += value; 53 | return sum / array.length; 54 | } 55 | 56 | function calculateGrade(marks) { 57 | const average = calculateAverage(marks); 58 | if (average < 60) return 'F'; 59 | if (average < 70) return 'D'; 60 | if (average < 80) return 'C'; 61 | if (average < 90) return 'B'; 62 | return 'A'; 63 | } -------------------------------------------------------------------------------- /03 Operators/11- Quiz.md: -------------------------------------------------------------------------------- 1 | # 11- Quiz 2 | 3 | ## 1- What is the result of “true && false”? 4 | 5 | - a - true 6 | - b - false 7 | - c - null 8 | - d - undefined 9 | 10 | Answer: b 11 | 12 | ## 2- What is the result of “(true && false) || true”? 13 | 14 | - a - true 15 | - b - false 16 | - c - null 17 | - d - undefined 18 | 19 | Answer: a 20 | 21 | ## 3- What is the value of y? 22 | 23 | ```javascript 24 | let x = 10; 25 | let y = x > 10 ? 1 : 0; 26 | ``` 27 | 28 | - a - 10 29 | - b - 1 30 | - c - 0 31 | - d - 11 32 | 33 | Answer: c 34 | 35 | ## 4- What is the value of x? 36 | 37 | ```javascript 38 | let x = (2 + 3) \* (4 + 5); 39 | ``` 40 | 41 | - a - 45 42 | - b - 25 43 | - c - 20 44 | - d - 40 45 | 46 | Answer: a 47 | 48 | ## 5- Which expression returns true? 49 | 50 | a- ‘1’ === 1; 51 | b- 1 == 1 52 | c- 1 === 1 53 | d- b and c 54 | 55 | Answer: d 56 | 57 | ## 6- What is the value of x? 58 | 59 | ```javascript 60 | let x = 1 == true; 61 | ``` 62 | 63 | - a - 1 64 | - b - true 65 | - c - false 66 | - d - undefined 67 | 68 | Answer: b 69 | 70 | ## 7- What is the value of y? 71 | 72 | ```javascript 73 | let x = 10; 74 | let y = x > 5 && x < 15; 75 | ``` 76 | 77 | - a - 10 78 | - b - 5 79 | - c - 15 80 | - d - true 81 | 82 | Answer: d 83 | 84 | ## 8- What is the value of x? 85 | 86 | ```javascript 87 | let x = 5; 88 | x += 3; 89 | ``` 90 | 91 | - a - 3 92 | - b - 8 93 | - c - 15 94 | - d - 5 95 | 96 | Answer: b 97 | 98 | ## 9- What is the value of y? 99 | 100 | ```javascript 101 | let x = 10; 102 | let y = x++; 103 | ``` 104 | 105 | - a - 10 106 | - b - 11 107 | - c - 12 108 | - d - 13 109 | 110 | Answer: a 111 | 112 | ## 10- What is the value of y? 113 | 114 | ```javascript 115 | let x = 1; 116 | let y = x !== 2; 117 | ``` 118 | 119 | - a - 1 120 | - b - 2 121 | - c - false 122 | - d - true 123 | 124 | Answer: d 125 | -------------------------------------------------------------------------------- /07 Functions/10- The this Keyword.js: -------------------------------------------------------------------------------- 1 | // 10- The this Keyword 2 | 3 | /* 4 | This references the object that is executing the current function. 5 | 6 | If that function is part of na object we call that function a method. 7 | method ---> this references that object itself 8 | 9 | If that function is a regular function, not part of na object. 10 | function ---> this references the global object (which is the window object in browsers and global in node) 11 | */ 12 | 13 | const video = { 14 | title: "a", 15 | play() { 16 | console.log(this); // Here this references the object itself, because play is a method in the video object. 17 | }, 18 | }; 19 | 20 | video.play(); 21 | 22 | /// We can also add a method and have the same result. 23 | video.stop = function () { 24 | console.log(this); 25 | }; 26 | 27 | video.stop(); 28 | 29 | function playVideo() { 30 | console.log(this); 31 | } 32 | 33 | playVideo(); // Here this is referencing the global object (window in browser, global in node) 34 | 35 | function Video(title) { 36 | this.title = title; 37 | console.log(this); 38 | } 39 | 40 | const v = new Video("b"); 41 | // We use the constructor function to create a new video object. It's a new video object different from the one above. 42 | // If we call a function using the new keyword this will reference the object created. 43 | 44 | const video2 = { 45 | title: "a", 46 | tags: ["a", "b", "c"], 47 | play() { 48 | console.log(this); // Here this references the object itself, because play is a method in the video object. 49 | }, 50 | showTags() { 51 | this.tags.forEach(function(tag) { // If we use a function as a callback function for the forEach method, the this keyword references the global object. 52 | console.log(this.title, tag); 53 | }, this); // As a second argument we can pass this keyword. So the this in the callback function references the object itself and not the global object. 54 | }, 55 | }; 56 | 57 | video2.showTags(); 58 | -------------------------------------------------------------------------------- /06 Arrays/04- Finding Elements (Reference Types).js: -------------------------------------------------------------------------------- 1 | // 04- Finding Elements (Reference Types) 2 | 3 | 4 | /* 5 | Finding Reference Type elements, is deferent that finding Primitive type elements. 6 | To do that we can use the "find()" method, 7 | 8 | Syntax 9 | arr.find(callback(element[, index[, array]])[, thisArg]) 10 | 11 | Parameters: 12 | callback: Function to execute on each value in the array, taking 3 arguments: 13 | element: The current element in the array. 14 | index (Optional): The index (position) of the current element in the array. 15 | array (Optional): The array that find was called on. 16 | thisArg (Optional): Object to use as this inside callback. 17 | 18 | Return value 19 | The value of the first element in the array that satisfies the provided testing function. Otherwise, undefined is returned. 20 | 21 | Description 22 | The find method executes the callback function once for each index of the array until the callback returns a truthy value. 23 | If so, find immediately returns the value of that element. Otherwise, find returns undefined. 24 | */ 25 | 26 | const courses = [ 27 | { id: 1, name: 'a'}, 28 | { id: 2, name: 'b'} 29 | ]; 30 | 31 | console.log(courses.includes({ id: 1, name: 'a'})); // This will return false because, even though the object syntax is the same, they are referencing different address in memory. 32 | 33 | // find() 34 | const course1 = courses.find(function(course) { 35 | return course.name === 'a'; 36 | }); 37 | 38 | console.log(course1); // Return the complete object 39 | 40 | 41 | const course2 = courses.find(function(course) { 42 | return course.name === 'd'; 43 | }); 44 | 45 | console.log(course2); // Return undefined, because we don\t have a course with name "d". 46 | 47 | 48 | // findIndex() This method return the index. In case it does not find a match it returns "-1". 49 | const course3 = courses.findIndex(function(course) { 50 | return course.name === 'a'; 51 | }); 52 | 53 | console.log(course3) // Returns 0 -------------------------------------------------------------------------------- /04 Control Flow/05- Do...while.js: -------------------------------------------------------------------------------- 1 | // 05- Do...while 2 | 3 | /* 4 | Definition and Usage 5 | The do/while statement creates a loop that executes a block of code once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. 6 | The do/while statement is used when you want to run a loop at least one time, no matter what. 7 | Thats the difference between the while loop and the do...while loop. 8 | The while loop only executes the code block if teh condition is true. 9 | The do...while loop executes the code block at least once even if the condition is false. 10 | The do...while loop is a variant of the while loop. 11 | This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. 12 | 13 | JavaScript supports different kinds of loops: 14 | for - loops through a block of code a number of times 15 | for/in - loops through the properties of an object 16 | for/of - loops through the values of an iterable object 17 | while - loops through a block of code while a specified condition is true 18 | do/while - loops through a block of code once, and then repeats the loop while a specified condition is true 19 | 20 | Syntax: 21 | 22 | do { 23 | code block to be executed 24 | } while (condition); 25 | 26 | condition: 27 | Required. Defines the condition for running the loop (the code block). If it returns true, the loop will start over again, if it returns false, the loop will end. 28 | Note: If the condition is always true, the loop will never end. This will crash your browser. 29 | Note: If you are using a variable with the condition, initialize it before the loop, and increment it within the loop. 30 | If you forget to increase the variable, the loop will never end. This will also crash your browser. 31 | */ 32 | 33 | let i = 0; 34 | do { 35 | let text = "The number is " + i; 36 | console.log(text) 37 | i++; 38 | } while (i <= 5); -------------------------------------------------------------------------------- /03 Operators/08- Logical Operators with Non-booleans.js: -------------------------------------------------------------------------------- 1 | // 08- Logical Operators with Non-booleans 2 | 3 | /* 4 | We can use the logical operators with non boolean values 5 | && 6 | || 7 | ! 8 | 9 | The result of the logical expression it is not necessarily a boolean value true or false. 10 | That depends on the value of the operands we have. 11 | The logical operations looks at each operant, and if the operand is not a boolean true or false, it will try to interpret it as Truthy or Falsy. 12 | 13 | Falsy values (False) 14 | false 15 | undefined 16 | null 17 | 0 18 | '' (empty string) 19 | NaN (Not a Number) 20 | 21 | If we use any of this values in a logical operation, they will be treated as falsy. Which is kind a like a boolean False, but is not exactly the same. 22 | Any other value that is not Falsy is Truthy. 23 | 24 | */ 25 | 26 | console.log(false || true) // This will return true 27 | console.log(false || 'Miguel') // This will return true because a non empty string is a Truthy value. 28 | console.log(false || -1) // This will return true because any number different of 0 is a Truthy value. 29 | console.log(false || 1 || 2) // This returns 1 because is the first Truthy operand. 30 | 31 | // When using the '||' or operator the evaluation starts in the first operand, and stops in the first Truthy value it finds, if there are any. 32 | // This is called short-circuiting 33 | 34 | // A real world example to use this could be for default values. 35 | // For example if a user picks a color we that color, if we does not pick a color we use the default value. 36 | 37 | let userColor = 'red' 38 | let defaultColor = 'blue' 39 | console.log(userColor || defaultColor) // This basically means that if we have a value for the user color we use that, if we don't we use the default color. 40 | 41 | userColor = undefined 42 | console.log(userColor || defaultColor) // Here the user did not pick a color, the variable user is set to undefined, so we will use the default color. -------------------------------------------------------------------------------- /04 Control Flow/01- If...else.js: -------------------------------------------------------------------------------- 1 | // 01- If...else 2 | 3 | /* 4 | Conditional Statements: 5 | Definition and Usage 6 | The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed. 7 | 8 | The if/else statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions. 9 | 10 | In JavaScript we have the following conditional statements: 11 | Use "if" to specify a block of code to be executed, if a specified condition is true 12 | Use "else" to specify a block of code to be executed, if the same condition is false 13 | Use "else if" to specify a new condition to test, if the first condition is false 14 | Use "switch" to select one of many blocks of code to be executed 15 | 16 | Syntax: 17 | The if statement specifies a block of code to be executed if a condition is true: 18 | if (condition) { 19 | block of code to be executed if the condition is true 20 | } 21 | 22 | The else statement specifies a block of code to be executed if the condition is false: 23 | if (condition) { 24 | block of code to be executed if the condition is true 25 | } else { 26 | block of code to be executed if the condition is false 27 | } 28 | 29 | The else if statement specifies a new condition if the first condition is false: 30 | if (condition1) { 31 | block of code to be executed if condition1 is true 32 | } else if (condition2) { 33 | block of code to be executed if the condition1 is false and condition2 is true 34 | } else { 35 | block of code to be executed if the condition1 is false and condition2 is false 36 | } 37 | 38 | When a condition is true, the following conditions will be ignored. 39 | 40 | Example depending on the hour we want to display a different message. 41 | If hour is between 6:00 and 12:00, we want to display good morning. 42 | If hour is between 12:00 and 18:00, we want to display good afternoon. 43 | Otherwise display good evening. 44 | */ 45 | 46 | let hour = 15 47 | 48 | if (hour >= 6 && hour < 12) 49 | console.log('Good Morning') 50 | else if (hour >= 12 && hour <= 18) 51 | console.log('Good afternoon') 52 | else 53 | console.log('Good evening') -------------------------------------------------------------------------------- /07 Functions/07- Try and Catch.js: -------------------------------------------------------------------------------- 1 | // 07- Try and Catch 2 | 3 | /* 4 | The try...catch statement marks a block of statements to try and specifies a response should an exception be thrown. 5 | 6 | Syntax 7 | try { 8 | try_statements 9 | } 10 | catch (exception_var) { 11 | catch_statements 12 | } 13 | finally { 14 | finally_statements 15 | } 16 | 17 | Description 18 | The try statement consists of a try-block, which contains one or more statements. 19 | {} must always be used, even for single statements. At least one catch-block, or a finally-block, must be present. This gives us three forms for the try statement: 20 | 21 | try...catch 22 | try...finally 23 | try...catch...finally 24 | 25 | A catch-block contains statements that specify what to do if an exception is thrown in the try-block. 26 | If any statement within the try-block (or in a function called from within the try-block) throws an exception, control is immediately shifted to the catch-block. 27 | If no exception is thrown in the try-block, the catch-block is skipped. 28 | 29 | The finally-block will always execute after the try-block and catch-block(s) have finished executing. 30 | It always executes, regardless of whether an exception was thrown or caught. 31 | 32 | You can nest one or more try statements. If an inner try statement does not have a catch-block, the enclosing try statement's catch-block is used instead. 33 | 34 | You can also use the try statement to handle JavaScript exceptions. 35 | */ 36 | 37 | const person = { 38 | firstName: "Miguel", 39 | lastName: "Pimenta", 40 | get fullName() { 41 | return `${this.firstName} ${this.lastName}`; 42 | }, 43 | set fullName(name) { 44 | if (typeof name !== "string") throw new Error("Name is not a string"); // Here we throw an exception if the type of the user entry is not a string. 45 | const nameParts = name.split(" "); 46 | if (nameParts.length !== 2) throw new Error("Enter a first and last name"); 47 | if (nameParts.length) this.firstName = nameParts[0]; 48 | this.lastName = nameParts[1]; 49 | }, 50 | }; 51 | 52 | try { 53 | person.fullName = null; 54 | } catch (error) { 55 | console.error(error); 56 | } // finally { 57 | // console.log('Restart') 58 | // } 59 | 60 | try { 61 | person.fullName = ""; 62 | } catch (error) { 63 | console.error(error); 64 | } // finally { 65 | // console.log('Restart') 66 | // } 67 | -------------------------------------------------------------------------------- /04 Control Flow/09- Break and Continue.js: -------------------------------------------------------------------------------- 1 | // 09- Break and Continue 2 | 3 | /* 4 | Break statement definition and usage: 5 | The break statement exits a switch statement or a loop (for, for ... in, while, do ... while). 6 | When the break statement is used with a switch statement, it breaks out of the switch block. 7 | This will stop the execution of more execution of code and/or case testing inside the block. 8 | When the break statement is used in a loop, it breaks the loop and continues executing the code after the loop (if any). 9 | The break statement can also be used with an optional label reference, to "jump out" of any JavaScript code block (see "More Examples" below). 10 | Note: Without a label reference, the break statement can only be used inside a loop or a switch. 11 | 12 | Syntax: 13 | 14 | break; 15 | 16 | Using the optional label reference: 17 | break label name; 18 | */ 19 | 20 | for (let i = 0; i <= 10; i++) { 21 | if (i === 5) { 22 | break; 23 | } 24 | console.log('For loop - The index is ' + i); 25 | } 26 | 27 | let i = 0 28 | while (i <= 10) { 29 | if (i === 5) break; 30 | console.log('While loop - The index is ' + i) 31 | i++ 32 | } 33 | 34 | /* 35 | Continue statement definition and usage 36 | The continue statement breaks one iteration (in the loop) if a specified condition occurs, and continues with the next iteration in the loop. 37 | The difference between continue and the break statement, is instead of "jumping out" of a loop, the continue statement "jumps over" one iteration in the loop. 38 | However, when the continue statement is executed, it behaves differently for different types of loops: 39 | In a while loop, the condition is tested, and if it is true, the loop is executed again 40 | In a for loop, the increment expression (e.g. i++) is first evaluated, and then the condition is tested to find out if another iteration should be done 41 | 42 | The continue statement can also be used with an optional label reference. 43 | Note: The continue statement (with or without a label reference) can only be used inside a loop. 44 | 45 | Syntax: 46 | continue; 47 | 48 | Using the optional label reference: 49 | continue label name; 50 | */ 51 | 52 | for (let i = 0; i <= 10; i++) { 53 | if (i % 2 === 0) { 54 | continue; 55 | } 56 | console.log('For loop - The index is ' + i); 57 | } 58 | 59 | let x = 0 60 | while (x <= 10) { 61 | if (x % 2 === 0) { 62 | x++ 63 | continue; 64 | } 65 | console.log('While loop - The index is ' + x) 66 | x++ 67 | } -------------------------------------------------------------------------------- /06 Arrays/02- Adding Elements.js: -------------------------------------------------------------------------------- 1 | // 02- Adding Elements 2 | 3 | 4 | const numbers = [3, 4]; 5 | console.log(numbers); 6 | 7 | // Adding elements to the end. 8 | numbers.push(5, 6); // We can pass one or more arguments and they will be placed in the end of the array. 9 | console.log(numbers); 10 | 11 | // Adding elements to beginning. 12 | numbers.unshift(1, 2); // This methods pushes the existing elements to the right and adds new elements in the beginning 13 | console.log(numbers); 14 | 15 | /* 16 | Adding elements in the middle. 17 | The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. 18 | 19 | Syntax 20 | let arrDeletedItems = arr.splice(start[, deleteCount[, item1[, item2[, ...]]]]) 21 | 22 | Parameters 23 | start 24 | The index at which to start changing the array. 25 | If greater than the length of the array, start will be set to the length of the array. In this case, no element will be deleted but the method will behave as an adding function, adding as many element as item[n*] provided. 26 | If negative, it will begin that many elements from the end of the array. (In this case, the origin -1, meaning -n is the index of the nth last element, and is therefore equivalent to the index of array.length - n.) If array.length + start is less than 0, it will begin from index 0. 27 | 28 | deleteCount Optional 29 | An integer indicating the number of elements in the array to remove from start. 30 | If deleteCount is omitted, or if its value is equal to or larger than array.length - start (that is, if it is equal to or greater than the number of elements left in the array, starting at start), then all the elements from start to the end of the array will be deleted. 31 | Note: In IE8, it won't delete all when deleteCount is omitted. 32 | If deleteCount is 0 or negative, no elements are removed. In this case, you should specify at least one new element (see below). 33 | 34 | item1, item2, ... Optional 35 | The elements to add to the array, beginning from start. If you do not specify any elements, splice() will only remove elements from the array. 36 | 37 | Return value 38 | An array containing the deleted elements. 39 | If only one element is removed, an array of one element is returned. 40 | If no elements are removed, an empty array is returned. 41 | */ 42 | 43 | numbers.splice(2, 0, 'a', 'b', 'c'); 44 | // The first parameter (type number) is the starting position (index). 45 | // The second parameter (type number) is a delete count. How many we want to delete. 46 | // The third parameters are the items we want to add. 47 | console.log(numbers); 48 | -------------------------------------------------------------------------------- /06 Arrays/08- Combining and Slicing Arrays.js: -------------------------------------------------------------------------------- 1 | // 08- Combining and Slicing Arrays 2 | 3 | 4 | const first = [1, 2, 3]; 5 | const second = [4, 5, 6]; 6 | 7 | /* 8 | concat() Combining arrays 9 | The concat() method is used to merge two or more arrays. 10 | This method does not change the existing arrays, but instead returns a new array. 11 | Syntax: 12 | const new_array = old_array.concat([value1[, value2[, ...[, valueN]]]]) 13 | 14 | Parameters 15 | valueN (Optional) 16 | Arrays and/or values to concatenate into a new array. If all valueN parameters are omitted, concat returns a shallow copy of the existing array on which it is called. 17 | 18 | Return value 19 | A new Array instance. 20 | */ 21 | 22 | const combined = first.concat(second); 23 | console.log(combined); 24 | 25 | 26 | /* 27 | slice() Slicing arrays 28 | The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. 29 | The original array will not be modified. 30 | 31 | Syntax 32 | arr.slice([start[, end]]) 33 | 34 | Parameters 35 | start Optional 36 | Zero-based index at which to start extraction. 37 | A negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence. 38 | If start is undefined, slice starts from the index 0. 39 | If start is greater than the index range of the sequence, an empty array is returned. 40 | end Optional 41 | Zero-based index before which to end extraction. slice extracts up to but not including end. For example, slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3). 42 | A negative index can be used, indicating an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. 43 | If end is omitted, slice extracts through the end of the sequence (arr.length). 44 | If end is greater than the length of the sequence, slice extracts through to the end of the sequence (arr.length). 45 | 46 | Return value 47 | A new array containing the extracted elements. 48 | */ 49 | 50 | const sliced = combined.slice(2, 4); 51 | console.log(sliced) 52 | 53 | /* 54 | Both this method when dealing with Reference types they copy the object reference into the new array and not the object value. 55 | Both the original and new array refer to the same object. That is, if a referenced object is modified, the changes are visible to both the new and original arrays. 56 | This includes elements of array arguments that are also arrays. 57 | */ -------------------------------------------------------------------------------- /04 Control Flow/03- For.js: -------------------------------------------------------------------------------- 1 | // 03- For 2 | 3 | /* 4 | Definition and Usage 5 | The for statement creates a loop that is executed as long as a condition is true. 6 | The loop will continue to run as long as the condition is true. It will only stop when the condition becomes false. 7 | JavaScript supports different kinds of loops: 8 | for - loops through a block of code a number of times 9 | for/in - loops through the properties of an object 10 | for/of - loops through the values of an iterable object 11 | while - loops through a block of code while a specified condition is true 12 | do/while - loops through a block of code once, and then repeats the loop while a specified condition is true 13 | 14 | Tip: Use the break statement to break out of a loop, and the continue statement to skip a value in the loop. 15 | 16 | Syntax: 17 | 18 | for (statement 1; statement 2; statement 3) { 19 | code block to be executed 20 | } 21 | 22 | statement1: Initial Expression 23 | Optional. Executed before the loop (the code block) starts. 24 | Normally this statement is used to initialize a counter variable. To initiate multiple values, separate each value with a comma. 25 | Note: This parameter can be omitted. However, do not omit the semicolon ";" 26 | 27 | statement2: Condition 28 | Optional. Defines the condition for running the loop (the code block). 29 | Normally this statement is used to evaluate the condition of the counter variable. 30 | If it returns true, the loop will start over again, if it returns false, the loop will end. 31 | Note: This parameter can be omitted. However, do not omit the semicolon ";". Also, if you omit this parameter, you must provide a break inside the loop. Otherwise the loop will never end, which will crash your browser 32 | 33 | statement3: Increment Expression 34 | Optional. Executed each time after the loop (the code block) has been executed. 35 | Normally this statement is used to increment or decrement the counter variable. 36 | Note: This parameter can be omitted (e.g. to increase/decrease values inside the loop) 37 | */ 38 | console.log('for loop 1') 39 | 40 | for (let i = 0; i < 5; i++) { 41 | let text = 'The number is ' + i 42 | console.log(text); 43 | } 44 | 45 | console.log('for loop 2') 46 | 47 | for (let i = 5; i > 0; i--) { 48 | let text = 'The number is ' + i 49 | console.log(text); 50 | } 51 | 52 | 53 | // Example using the continue statement - Loop through a block of code, but skip the value of "3": 54 | 55 | console.log('for loop 3') 56 | 57 | for (let i = 0; i < 5; i++) { 58 | if (i == 3) { 59 | continue; 60 | } 61 | let text = "The number is " + i; 62 | console.log(text) 63 | } -------------------------------------------------------------------------------- /07 Functions/11- Changing this.js: -------------------------------------------------------------------------------- 1 | // 11- Changing this 2 | 3 | const video = { 4 | title: "a", 5 | tags: ["a", "b", "c"], 6 | play() { 7 | console.log(this); // Here this references the object itself, because play is a method in the video object. 8 | }, 9 | showTags() { 10 | this.tags.forEach(function (tag) { 11 | // If we use a function as a callback function for the forEach method, the this keyword references the global object. 12 | console.log(this.title, tag); 13 | }, this); // As a second argument we can pass this keyword. So the this in the callback function references the object itself and not the global object. 14 | }, 15 | }; 16 | 17 | // The self approach to use the this keyword inside a callback function. It is not a good practice. 18 | const videoSelf = { 19 | title: "a", 20 | tags: ["a", "b", "c"], 21 | play() { 22 | console.log(this); // Here this references the object itself, because play is a method in the video object. 23 | }, 24 | showTags() { 25 | const self = this; // A different approach to use the this method in a function 26 | this.tags.forEach(function (tag) { 27 | console.log(self.title, tag); 28 | }); 29 | }, 30 | }; 31 | 32 | // In JavaScript functions are objects and have different methods we can access 33 | function playVideo(a, b) { 34 | console.log(this); 35 | } 36 | playVideo(); // Here the this key word references the global object. 37 | playVideo.call({ name: "Miguel" }, 1, 2); // As the first parameter of this method "thisArg", we can pass an object and "this" will reference that object. 38 | playVideo.apply({ name: "Miguel" }, [1, 2]); //It works as the call method. The only difference is that here we pass an array as the second parameter, for the other parameters of the function. 39 | const fn = playVideo.bind({ name: "Miguel" }); // The bind method returns a new function and sets this to point permanently to the object we pass as an argument to bind. 40 | fn(); 41 | 42 | // The bind approach to use this in the callback function. 43 | const videoBind = { 44 | title: "a", 45 | tags: ["a", "b", "c"], 46 | play() { 47 | console.log(this); // Here this references the object itself, because play is a method in the video object. 48 | }, 49 | showTags() { 50 | this.tags.forEach( 51 | function (tag) { 52 | console.log(this.title, tag); 53 | }.bind(this) 54 | ); 55 | }, 56 | }; 57 | 58 | //The new solution from ES6 is to use arrow function. 59 | const videoArrow = { 60 | title: "a", 61 | tags: ["a", "b", "c"], 62 | play() { 63 | console.log(this); // Here this references the object itself, because play is a method in the video object. 64 | }, 65 | showTags() { 66 | this.tags.forEach(tag => {// Arrow function inherit this from the containing function 67 | console.log(this.title, tag); 68 | }); 69 | }, 70 | }; 71 | -------------------------------------------------------------------------------- /03 Operators/09- Bitwise Operators.js: -------------------------------------------------------------------------------- 1 | // 09- Bitwise Operators 2 | 3 | 4 | /* 5 | Bit operators work on 32 bits numbers. Any numeric operand in the operation is converted into a 32 bit number. The result is converted back to a JavaScript number. 6 | & AND 7 | | OR 8 | ~ NOT 9 | ^ XOR 10 | << Left shift 11 | >> Right shift 12 | 13 | We humans use de decimal system to represent numbers 0..9, but in computers this numbers are stored in the binary format, which is a combination of 0 and 1 14 | 1 = 00000001 15 | 2 = 00000010 16 | 3 = 00000011 17 | In binary each number is a bit. 18 | Bitwise operator as similar to logical operator but they or on each bit of the number. 19 | */ 20 | 21 | console.log(1 | 2) 22 | /* 23 | Using the bitwise "|" operator it will compare each bit (0 and 1) in its equivalent position, and where he finds 1 the result will be 1 otherwise it will be 0. 24 | 1 = 00000001 25 | 2 = 00000010 26 | result = 00000011 ---> 3 represents 3 in decimal number 27 | */ 28 | 29 | console.log(1 & 2) 30 | /* 31 | Using the bitwise "&" operator it will compare each bit (0 and 1), and it will return 1 if both operands have 1 in the same position, otherwise it will return 0. 32 | 1 = 00000001 33 | 2 = 00000010 34 | result = 00000000 ---> 0 represents 0 in decimal number 35 | */ 36 | 37 | /* 38 | For a real world example 39 | Lets say we want to implement an access controle system. 40 | So the user can have this permissions: 41 | Read 42 | Write 43 | Execute 44 | We can use one byte of information (the same as 8 bits) to determine the kind of permission a user has. 45 | For each permission we assign one bit. 46 | Read ---> 00000100 ---> 4 in decimal 47 | Write ---> 00000010 ---> 2 in decimal 48 | Execute ---> 00000001 ---> 1 in decimal 49 | 50 | Read ---> 00000100 ---> 4 in decimal 51 | Read and Write ---> 00000110 ---> 6 in decimal 52 | Read and Write and Execute ---> 00000111 ---> 7 in decimal 53 | We are representing the permissions in binary numbers. For 54 | */ 55 | 56 | const readPermission = 4; // We convert the binary number 00000100 to decimal, which is 4. 57 | const writePermission = 2; // We convert the binary number 00000010 to decimal, which is 2. 58 | const executePermission = 1; // We convert the binary number 0000001 to decimal, which is 1. 59 | 60 | let myPermission = 0; // We declare a variable and initially we do not have any permissions 0 decimal equal to 00000000 binary 61 | 62 | myPermission = myPermission | readPermission; // With the bitwise "|" operator we are assign the read permission to the user 63 | console.log(myPermission) 64 | 65 | myPermission = myPermission | writePermission; // And here we add the write permission. 66 | console.log(myPermission); 67 | 68 | let message = myPermission & executePermission ? 'yes' : 'no'; // We we check if the user has the Execute permission with the "&" operator. 69 | 70 | // With the bitwise "|" we can add permission, and with the bitwise "&" operator we can che to see if the user has permissions. 71 | -------------------------------------------------------------------------------- /05 Objects/12- String.js: -------------------------------------------------------------------------------- 1 | // 12- String 2 | 3 | /* 4 | String Object 5 | https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/String 6 | 7 | */ 8 | 9 | // String Primitive 10 | const message1 = ' hi, this is a message '; 11 | console.log(typeof message1); // Returns "string". 12 | 13 | // String Object 14 | const message2 = new String('hi, this is another message'); 15 | console.log(typeof message2); // Returns "object". 16 | 17 | // Although primitives do not have method and properties, but when we use the dot notations with a string primitive JavaScript engine wraps it with a string objects. 18 | // Thats why we have access to the method and properties of the string object. 19 | 20 | // Length property 21 | console.log(message1.length); 22 | // Returns the number of characters, in this case 21. 23 | 24 | // Bracket notation to access a character by its index. 25 | console.log(message1[4]); // Returns "t". 26 | 27 | // To check if a string includes certain characters. 28 | console.log(message1.includes("this")); // Return a boolean, in this case true. 29 | console.log(message1.includes("hello")); // Returns false. 30 | 31 | // To check how th string starts. 32 | console.log(message1.startsWith('hi')); // Return a boolean, in this case true. 33 | console.log(message1.startsWith('Hi')); // Return false. 34 | 35 | // To check how the string ends. 36 | console.log(message1.endsWith('ge')); // Return a boolean, in this case true. 37 | console.log(message1.endsWith('end')); // Returns false 38 | 39 | // To find the index of a given character. 40 | console.log(message1.indexOf('is')); // Returns the index number. 41 | console.log(message1.indexOf('not')); // Returns -1 if the characters are not in the string. 42 | 43 | // To replace the string 44 | console.log(message1.replace('hi', 'hello')) // It returns a new string and does not modify the original one. 45 | 46 | // Uppercase 47 | console.log(message1.toUpperCase()) // Returns a new string all uppercase. 48 | 49 | // Lowercase 50 | console.log(message1.toLowerCase()) // Returns a new string all characters lowercase. 51 | 52 | // Trim white spaces. 53 | console.log(message1.trim()) // Removes white spaces in the beginning and end of the string. And returns as new message without altering the original. 54 | console.log(message1.trimLeft()) 55 | console.log(message1.trimRight()) 56 | 57 | // Split method to convert string to array. 58 | console.log(message1.split(' ')) // As an argument we specify the character to split the string. 59 | 60 | /* 61 | Escape notation 62 | Special characters can be encoded using escape notation: 63 | 64 | Code Output 65 | \XXX ---> ISO-8859-1 character / Unicode code point between U+0000 and U+00FF 66 | (where XXX is 1–3 octal digits; range of 0–377) 67 | 68 | \' ---> single quote 69 | \" ---> double quote 70 | \\ ---> backslash 71 | \n ---> new line 72 | \r ---> carriage return 73 | \v ---> vertical tab 74 | \t ---> tab 75 | \b ---> backspace 76 | \f ---> form feed 77 | 78 | \uXXXX ---> UTF-16 code unit / Unicode code point between U+0000 and U+FFFF 79 | (where XXXX is 4 hex digits; range of 0x0000–0xFFFF) 80 | 81 | \u{X} ... 82 | \u{XXXXXX} ---> UTF-32 code unit / Unicode code point between U+0000 and U+10FFFF 83 | (where X…XXXXXX is 1–6 hex digits; range of 0x0–0x10FFFF) 84 | 85 | \xXX ---> ISO-8859-1 character / Unicode code point between U+0000 and U+00FF 86 | (where XX is 2 hex digits; range of 0x00–0xFF) 87 | 88 | */ 89 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [Code With Mosh - The Ultimate JavaScript Mastery Series - Part 1](https://codewithmosh.com/p/javascript-basics-for-beginners) 2 | 3 | ![The Ultimate JavaScript Mastery Series - Part 1](https://process.fs.teachablecdn.com/ADNupMnWyR7kCWRvm76Laz/resize=width:705/https://www.filepicker.io/api/file/4JkBtVU9QUwcwFCWi3AV "The Ultimate JavaScript Mastery Series - Part 1") 4 | 5 | ### Introduction 6 | 7 | This repository was made while studying with [Mosh Hamedani](https://programmingwithmosh.com/ "Programming with Mosh"), in [Code with Mosh](https://codewithmosh.com/ "Code with Mosh"). And it contains all my notes from the course. It can be used as an extensive JavaScript cheatsheet. 8 | 9 | ## Course content 10 | 11 | 1. Getting Started 12 | 2. Basics 13 | 3. Operators 14 | 4. Control Flow 15 | 5. Objects 16 | 6. Arrays 17 | 7. Functions 18 | 19 | ## Getting Started (17m) 20 | 21 | 1. Welcome (0:28) 22 | 2. What is JavaScript (4:40) 23 | 3. Setting Up the Development Environment (3:09) 24 | 4. JavaScript in Browsers (3:47) 25 | 5. Separation of Concerns (2:04) 26 | 6. JavaScript in Node (1:50) 27 | 7. Source Code 28 | 29 | ## Basics (40m) 30 | 31 | 1. Variables (5:36) 32 | 2. Constants (1:44) 33 | 3. Primitive Type (3:10) 34 | 4. Dynamic Typing (3:17) 35 | 5. Objects (5:14) 36 | 6. Arrays (4:18) 37 | 7. Functions (4:39) 38 | 8. Types of Functions (3:16) 39 | 40 | ## Operators (35m) 41 | 42 | 1. JavaScript Operators (0:40) 43 | 2. Arithmetic Operators (3:39) 44 | 3. Assignment Operators (1:44) 45 | 4. Comparison Operators (2:01) 46 | 5. Equality Operators (3:11) 47 | 6. Ternary Operator (2:09) 48 | 7. Logical Operators (5:30) 49 | 8. Logical Operators with Non-booleans (5:53) 50 | 9. Bitwise Operators (8:28) 51 | 10. Operators Precedence (1:14) 52 | 11. Quiz 53 | 12. Exercise - Swapping Variables (2:26) 54 | 55 | ## Control Flow (1h25m) 56 | 57 | 1. If...else (5:23) 58 | 2. Switch...case (4:41) 59 | 3. For (5:50) 60 | 4. While (2:11) 61 | 5. Do...while (3:29) 62 | 6. Infinite Loops (2:42) 63 | 7. For...in (4:25) 64 | 8. For...of (1:15) 65 | 9. Break and Continue (2:34) 66 | 10. Exercise 1- Max of Two Numbers (3:59) 67 | 11. Exercise 2- Landscape or Portrait (2:25) 68 | 12. Exercise 3- FizzBuzz (6:39) 69 | 13. Exercise 4- Demerit Points (9:05) 70 | 14. Exercise 5- Even and Odd Numbers (2:02) 71 | 15. Exercise 6- Count Truthy (4:33) 72 | 16. Exercise 7- String Properties (2:58) 73 | 17. Exercise 8- Sum of Multiples of 3 and 5 (2:40) 74 | 18. Exercise 9- Grade (6:32) 75 | 19. Exercise 10- Stars (2:33) 76 | 20. Exercise- Prime Numbers (8:24) 77 | 78 | ## Objects (1h20m) 79 | 80 | 1. Basics (4:53) 81 | 2. Factory Functions (5:44) 82 | 3. Constructor Functions (5:48) 83 | 4. Dynamic Nature of Objects (2:03) 84 | 5. Constructor Property (2:24) 85 | 6. Functions are Objects (4:47) 86 | 7. Value vs Reference Types (5:49) 87 | 8. Enumerating Properties of an Object (5:09) 88 | 9. Cloning an Object (4:21) 89 | 10. Garbage Collection (1:14) 90 | 11. Math (2:56) 91 | 12. String (6:25) 92 | 13. Template Literals (4:52) 93 | 14. Date (4:00) 94 | 15. Exercise 1- Address Object (1:41) 95 | 16. Exercise 2- Factory and Constructor Functions (3:02) 96 | 17. Exercise 3- Object Equality (3:59) 97 | 18. Exercise 4- Blog Post Object (2:15) 98 | 19. Exercise 5- Constructor Functions (2:52) 99 | 20. Exercise 6- Price Range Object (3:37) 100 | 101 | ## Arrays (1h30m) 102 | 103 | 1. Introduction (0:31) 104 | 2. Adding Elements (3:35) 105 | 3. Finding Elements (Primitives) (3:32) 106 | 4. Finding Elements (Reference Types) (5:46) 107 | 5. Arrow Functions (1:34) 108 | 6. Removing Elements (3:03) 109 | 7. Emptying an Array (4:14) 110 | 8. Combining and Slicing Arrays (3:40) 111 | 9. The Spread Operator (2:25) 112 | 10. Iterating an Array (2:31) 113 | 11. Joining Arrays (3:11) 114 | 12. Sorting Arrays (6:32) 115 | 13. Testing the Elements of an Array (3:44) 116 | 14. Filtering an Array (2:46) 117 | 15. Mapping an Array (7:47) 118 | 16. Reducing an Array (6:43) 119 | 17. Exercise 1- Array from Range (1:50) 120 | 18. Exercise 2- Includes (1:54) 121 | 19. Exercise 3- Except (2:08) 122 | 20. Exercise 4- Moving an Element (6:31) 123 | 21. Exercise 5- Count Occurrences (4:31) 124 | 22. Exercise 6- Get Max (6:14) 125 | 23. Exercise 7- Movies (4:38) 126 | 127 | ## Functions (1h5m) 128 | 129 | 1. Function Declarations vs Expressions (3:18) 130 | 2. Hoisting (1:56) 131 | 3. Arguments (4:15) 132 | 4. The Rest Operator (4:38) 133 | 5. Default Parameters (3:40) 134 | 6. Getters and Setters (5:38) 135 | 7. Try and Catch (5:35) 136 | 8. Local vs Global Scope (4:44) 137 | 9. Let vs Var (5:52) 138 | 10. The this Keyword (7:22) 139 | 11. Changing this (7:00) 140 | 12. Exercise 1- Sum of Arguments (3:42) 141 | 13. Exercise 2- Area of Circle (1:53) 142 | 14. Exercise 3- Error Handling (2:49) 143 | --------------------------------------------------------------------------------