├── 3 JavaScript Operators ├── 3-assignment-operators.js ├── 6-ternary-operator.js ├── 4-comparison-operators.js ├── 5-equality-operators.js ├── 2-arithmetic-operators.js ├── 8-logical-operators-with-non-booleans.js └── 7-logical-operators.js ├── 4 Control Flow ├── 10-exercise-max-of-two-numbers.js ├── 6-infinite-loops.js ├── 8-for-of-loops.js ├── 5-do-while-loops.js ├── 12-exercise-even-and-odd-numbers.js ├── 3-for-loops.js ├── 11-exercise-fizzBuzz.js ├── 7-for-in-loops.js ├── 4-while-loops.js ├── 1-if-else-statement.js ├── 2-switch-case-statement.js └── 9-break-and-continue.js ├── 5 JavaScript Objects ├── 10-garbage-collection.js ├── 5-constructor-property.js ├── 1-object-literals.js ├── 13-template-literals.js ├── 4-objects-are-dynamic.js ├── 9-cloning-an-object.js ├── 11-built-in-math-functions.js ├── 14-the-date-object.js ├── 6-functions-are-objects.js ├── 8-enumerating-properties-of-an-object.js ├── 7-value-vs-reference-types.js ├── 2-factory-functions.js ├── 12-string-methods.js └── 3-constructor-functions.js ├── README.md ├── 6 JavaScript Arrays ├── 1-intro-to-arrays.js ├── 6-removing-elements.js ├── 8-combining-and-slicing-arrays.js ├── 16-reducing-an-array.js ├── 10-iterating-an-array.js ├── 9-spread-operator.js ├── 7-emptying-an-array.js ├── 2-adding-elements.js ├── 5-arrow-functions.js ├── 11-joining-arrays.js ├── 15-mapping-an-array.js ├── 14-filtering-an-array.js ├── 4-finding-reference-types-in-arrays.js ├── 13-testing-elements-of-an-array.js ├── 3-finding-primitive-elements.js └── 12-sorting-arrays.js ├── 2 JavaScript Variables ├── 4-dynamic-typing.js ├── 7-functions.js ├── 1-intro-to-variables.js ├── 2-constants.js ├── 6-arrays.js ├── 8-types-of-functions.js ├── 5-objects.js └── 3-primitive-types.js └── 7 JavaScript Functions ├── 1-function-declarations-vs-expressions.js ├── 2-hoisting.js ├── 3-arguments.js ├── 8-local-vs-global-scope.js ├── 7-try-and-catch.js ├── 9-let-vs-var.js ├── 6-getters-and-setters.js ├── 5-default-parameters.js ├── 4-the-rest-operator.js └── 10-the-this-keyword.js /3 JavaScript Operators/3-assignment-operators.js: -------------------------------------------------------------------------------- 1 | // The assignmet operator is a single equal sign, =, which doesn't check for equality. 2 | let programmingLanguage = 'JavaScript'; -------------------------------------------------------------------------------- /4 Control Flow/10-exercise-max-of-two-numbers.js: -------------------------------------------------------------------------------- 1 | // Implement a function that accepts two numbers and returns the maximum number. 2 | 3 | function max(num1, num2) { 4 | return num1 >= num2 ? num1 : num2; 5 | } -------------------------------------------------------------------------------- /4 Control Flow/6-infinite-loops.js: -------------------------------------------------------------------------------- 1 | // Infinite loops will cause your program to crash. 2 | // You want to ensure within your loops that you are progressively 3 | // getting closer to your condition being false as to termiante the loop. -------------------------------------------------------------------------------- /4 Control Flow/8-for-of-loops.js: -------------------------------------------------------------------------------- 1 | // In the case when we are simply looping over the elements of an array. 2 | // If we aren't utilizing the index variable, then we have a cleaner syntax. 3 | 4 | let numbers = [1, 2, 3, 4, 5, 6, 7]; 5 | 6 | for (const number of numbers) { 7 | console.log(number); 8 | } -------------------------------------------------------------------------------- /5 JavaScript Objects/10-garbage-collection.js: -------------------------------------------------------------------------------- 1 | // In programming languages such as C or C++, 2 | // when you create an object you have to explicitly allocate and deallocate memory. 3 | // But in programming languages such as JavaScript, C#, Java, or Python 4 | // the languages have garbage collection to manage memory for us. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JavaScript for Beginners Notes 2 | 3 | This is a repository containing the course notes for the 3.5 hour video course, JavaScript for Beginners. 4 | 5 | If you would like to support my courses and projects, consider checking out the links below. 6 | 7 | [https://stevencodecraft.com](https://stevencodecraft.com) 8 | 9 | [https://fitfuelplanner.com](https://fitfuelplanner.com) 10 | -------------------------------------------------------------------------------- /4 Control Flow/5-do-while-loops.js: -------------------------------------------------------------------------------- 1 | // Another loop in JavaScript is the do-while loop. 2 | // This differs from the traditional while-loop as 3 | // it will execute the statements within the code block, 4 | // and then evaluate the condition after. 5 | 6 | // This means that a do-while loop is guaranteed to execute at least once. 7 | let i = 0; 8 | do { 9 | console.log(i); 10 | 11 | i++; 12 | } while (i < 10); -------------------------------------------------------------------------------- /4 Control Flow/12-exercise-even-and-odd-numbers.js: -------------------------------------------------------------------------------- 1 | let number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 2 | 3 | function displayEvenNumbers(number) { 4 | for (const num of number) { 5 | if (num % 2 === 0) 6 | console.log(num); 7 | } 8 | } 9 | 10 | function displayOddNumbers(number) { 11 | for (const num of number) { 12 | if (num % 2 !== 0) 13 | console.log(num); 14 | } 15 | } -------------------------------------------------------------------------------- /5 JavaScript Objects/5-constructor-property.js: -------------------------------------------------------------------------------- 1 | // Every object in JavaScript has a constructor function. 2 | const person = { 3 | name: 'Steven' 4 | }; 5 | 6 | console.log( person.constructor ); 7 | 8 | let newObj = {}; 9 | // internally JavaScript sees this as 10 | // let newObj = new Object(); 11 | // so object literal syntax is syntactic sugar 12 | 13 | /* 14 | new String(); 15 | new Boolean(); 16 | new Number(); 17 | */ -------------------------------------------------------------------------------- /6 JavaScript Arrays/1-intro-to-arrays.js: -------------------------------------------------------------------------------- 1 | // Arrays are a commonly used data structure. 2 | // Arrays provide a collection of elements (a list of items). 3 | 4 | // In JavaScript arrays, the index position stores an element that can be of any data type. 5 | // However in real applications, all elements of an array are usually of the same data type. 6 | 7 | // There are many built in methods for arrays, which enable you 8 | // to modify, filter, and retrieve data, using clean and modern syntax. 9 | -------------------------------------------------------------------------------- /2 JavaScript Variables/4-dynamic-typing.js: -------------------------------------------------------------------------------- 1 | // JavaScript is dynamically typed. 2 | // Meaning that you can initialize a variable to a particular data type. 3 | // Then you can reassign it later to a different data type. 4 | // Programming languages which are statically typed, such as Java or C#, 5 | // do not allow you to do this. 6 | 7 | let firstName = 'Steven'; 8 | console.log(typeof firstName); 9 | 10 | firstName = 100; 11 | console.log(typeof firstName); 12 | 13 | firstName = true; 14 | console.log(typeof firstName); 15 | -------------------------------------------------------------------------------- /2 JavaScript Variables/7-functions.js: -------------------------------------------------------------------------------- 1 | // Functions are the building blocks of our applications. 2 | // It allows us to group together statements to perform a task or calculate a value. 3 | 4 | // Function declaration syntax 5 | function sayHi() { 6 | console.log('Hi!'); 7 | } 8 | 9 | // Then we invoke/call the function. 10 | sayHi(); 11 | 12 | // Can also define a parameter variable within the parenthesis. 13 | function sayHiPartTwo(name) { 14 | // Then we use string concatenation to use that variable. 15 | console.log('Hi! ' + name); 16 | } -------------------------------------------------------------------------------- /4 Control Flow/3-for-loops.js: -------------------------------------------------------------------------------- 1 | let numbers = [1, 2, 3, 4, 5, 6, 7]; 2 | 3 | // To output all of the elements in the array. 4 | 5 | let idx = 0; 6 | let lengthOfArray = numbers.length; 7 | 8 | console.log( numbers[idx++] ); 9 | console.log( numbers[idx++] ); 10 | console.log( numbers[idx++] ); 11 | console.log( numbers[idx++] ); 12 | console.log( numbers[idx++] ); 13 | console.log( numbers[idx++] ); 14 | console.log( numbers[idx] ); 15 | 16 | // You can use the for loop to efficiently iterate through an array 17 | for (let idx = 0; idx < numbers.length; idx++) { 18 | console.log(numbers[idx]); 19 | } -------------------------------------------------------------------------------- /4 Control Flow/11-exercise-fizzBuzz.js: -------------------------------------------------------------------------------- 1 | // Implement a function to accept a number. 2 | // Then return "FizzBuzz" if divisible by 3 and 5. 3 | // Or return "Fizz" if only divisible by 3. 4 | // Or return "Buzz" if only divisible by 5. 5 | // Or return the original number if not divisible by 3 or 5 6 | 7 | function fizzBuzz(num) { 8 | if (typeof num !== 'number') return num; 9 | 10 | if (num % 3 === 0 && num % 5 === 0) 11 | return 'FizzBuzz'; 12 | else if (num % 3 === 0) 13 | return 'Fizz'; 14 | else if (num % 5 === 0) 15 | return 'Buzz'; 16 | else 17 | return num; 18 | } -------------------------------------------------------------------------------- /3 JavaScript Operators/6-ternary-operator.js: -------------------------------------------------------------------------------- 1 | // In JavaScript, we have the ternary operator. 2 | // It is a conditional operator that allows us to write cleaner code. 3 | // This can be used when you need to perform a comparison and store values. 4 | 5 | // Note: in this case you could just do 6 | // const canDrive = age >= 16; 7 | // but this is just to demonstrate the syntax of the ternary operator. 8 | 9 | let age = 16; 10 | const canDrive = age >= 16 ? true : false; 11 | console.log('canDrive', canDrive); 12 | 13 | let points = 110; 14 | const customerType = points > 100 ? 'gold' : 'silver'; 15 | console.log('customerType', customerType); -------------------------------------------------------------------------------- /2 JavaScript Variables/1-intro-to-variables.js: -------------------------------------------------------------------------------- 1 | // The var keyword is the previous keyword used to create a variable. 2 | // Declaring and assigning a variable on the same line is known as initialization; 3 | var previousNamingConvention = 'Your First Name'; 4 | 5 | // the let keyword is the modern syntax to create a variable 6 | let firstName = 'Your First Name'; 7 | 8 | // Variable declaration 9 | let variableDeclaration; 10 | 11 | // Variable assignment. The equal sign, =, is known as the assignment operator. 12 | variableDeclaration = 'value'; 13 | 14 | // You output to the console with console.log(); 15 | console.log('variableDeclaration'); 16 | 17 | -------------------------------------------------------------------------------- /4 Control Flow/7-for-in-loops.js: -------------------------------------------------------------------------------- 1 | // We typically use for-loops to iterate over an array. 2 | 3 | // We also have another loop known as the for-in loop 4 | // which is used to iterate over the keys of a JavaScript object. 5 | 6 | // A JavaScript object is a data type that allows you to store key-value pairs. 7 | 8 | const course = { 9 | name: 'JavaScript for Beginners', 10 | duration: 3, 11 | setions: 7 12 | }; 13 | 14 | console.log(course.name); 15 | console.log(course['duration']); 16 | console.log(course.sections); 17 | 18 | // We could also iterate over the keys with the for-in loop. 19 | for (const key in course) { 20 | console.log(course[key]); 21 | } -------------------------------------------------------------------------------- /5 JavaScript Objects/1-object-literals.js: -------------------------------------------------------------------------------- 1 | // Objects are a way to store key-value pairs. 2 | // They allow us to group together stat and behavior that's highly related. 3 | // The benefit is we can make our code cohesive and organized. 4 | 5 | // Encapsulation involves grouping together data and the methods that 6 | // manipulate that data into a single unit. 7 | // While hiding or abstracting away the internal details from outside interference or misuse. 8 | 9 | const dog = { 10 | name: 'Max', 11 | breed: 'Dachshund', 12 | age: 5, 13 | weightInPounds: 12, 14 | eat: function() { 15 | console.log('Chomp!'); 16 | }, 17 | bark() { 18 | console.log('Woof!'); 19 | } 20 | }; -------------------------------------------------------------------------------- /7 JavaScript Functions/1-function-declarations-vs-expressions.js: -------------------------------------------------------------------------------- 1 | // Functions are the cornerstone in JavaScript serving as reusable functions. 2 | // There are different ways to create a function. 3 | // In this lesson we'll explore function-declaration syntax 4 | // and function-expresson syntax. 5 | 6 | // Function declaration syntax 7 | function sayHi() { 8 | console.log('Hi'); 9 | } 10 | 11 | sayHi(); 12 | 13 | // Function expression syntax 14 | // End the curly braces with a semi-colon and utilize an anonymous function. 15 | const sayHello = function() { 16 | console.log('Hello'); 17 | }; 18 | 19 | sayHello(); 20 | 21 | const greeting = function sayBye() { 22 | console.log('Bye'); 23 | } 24 | 25 | greeting(); -------------------------------------------------------------------------------- /6 JavaScript Arrays/6-removing-elements.js: -------------------------------------------------------------------------------- 1 | const numbers = [1, 2, 3, 4, 5]; 2 | 3 | // To remove elements, 4 | // .pop() to remove from the end 5 | // .splice() to remove from the middle 6 | // .shift() to remove from the beginning 7 | 8 | // NOTE: \n within a string stands for newline, 9 | 10 | const lastElement = numbers.pop(); 11 | console.log(`lastElement: ${lastElement}\n`); // lastElement: 5 12 | 13 | const firstElement = numbers.shift(); 14 | console.log(`firstElement: ${firstElement}`); // firstElement: 1 15 | 16 | // 1st arg is the index to start from 17 | // 2nd arg is the number of elements to remove 18 | const middleElement = numbers.splice(1, 1); 19 | console.log(`middleElement: ${middleElement}`); // middleElement: 3 20 | -------------------------------------------------------------------------------- /7 JavaScript Functions/2-hoisting.js: -------------------------------------------------------------------------------- 1 | // The function declaration syntax and function expression syntax 2 | // differ because of the concept of hoisting. 3 | // Hoisting is a process where the JavaScript engine moves all 4 | // function declarations to the top of their enclosing scope. 5 | 6 | // With function declaration syntax, we can call/invoke a function 7 | // before it is defined due to hoisting. 8 | 9 | add(2, 2); 10 | 11 | function add(num1, num2) { 12 | return num1 + num2; 13 | } 14 | 15 | // Hoisting doesn't apply with function expression syntax, 16 | // so you cannot call/invoke a function before it is defined. 17 | 18 | let multiply = function(num1, num2) { 19 | return num1 * num2; 20 | } 21 | 22 | multiply(2, 3); -------------------------------------------------------------------------------- /3 JavaScript Operators/4-comparison-operators.js: -------------------------------------------------------------------------------- 1 | // Comparison operators include... 2 | // >, greater than 3 | // >=, greater than or equal to 4 | // <, less than 5 | // <=, less than or equal to 6 | 7 | // The result of a comparison operator is a boolean value, true or false. 8 | let num1 = 14; 9 | let num2 = 10; 10 | 11 | const isNum1Greater = num1 > num2; 12 | console.log('isNum1Greater', isNum1Greater); 13 | 14 | const isNum1GreaterThanOrEqualTo = num1 >= num2; 15 | console.log('isNum1GreaterThanOrEqualTo', isNum1GreaterThanOrEqualTo); 16 | 17 | const isNum1LessThan = num1 < num2; 18 | console.log('isNum1LessThan', isNum1LessThan); 19 | 20 | const isNum1LessThanOrEqualTo = num1 <= num2; 21 | console.log('isNum1LessThanOrEqualTo', isNum1LessThanOrEqualTo); -------------------------------------------------------------------------------- /3 JavaScript Operators/5-equality-operators.js: -------------------------------------------------------------------------------- 1 | // For checking for equality, we can do so through... 2 | // Loose equality, which uses == 3 | // Strict equality, which uses === 4 | 5 | let a = 2; 6 | let b = '2'; 7 | 8 | // Loose equality evaluates this comparison to be truthy. 9 | // Loose equality doesn't check if the data types are the same. 10 | // JavaScript will perform type coersion with loose equality, converting the data types to be the same before comparing 11 | console.log(a == b); // true 12 | 13 | // Strict equality returns true if the data types are the same and the the values are the same. 14 | console.log(a === b); // false 15 | 16 | console.log(true == '1'); // true 17 | 18 | // Stick to strict equality and use === for equality comparisons. -------------------------------------------------------------------------------- /5 JavaScript Objects/13-template-literals.js: -------------------------------------------------------------------------------- 1 | // In previous lessons when working with strings, 2 | // we have used either single quotes, '', or double quotes, "" 3 | 4 | // We have another way to create a string literal and that is with backticks, `` 5 | // We would call this a template literal. 6 | // The benefit is that it allows us to use string interpolation rather than string concatenation. 7 | 8 | let firstName = 'Steven'; 9 | let lastName = 'Garcia'; 10 | 11 | // string concatenation 12 | let fullName = firstName + ' ' + lastName; 13 | 14 | // string interpolation with a template literal 15 | // ${} acts as a placeholder and within, we can specify an expression 16 | // an expression is any code that would return some value 17 | fullName = `${firstName} ${lastName}`; -------------------------------------------------------------------------------- /4 Control Flow/4-while-loops.js: -------------------------------------------------------------------------------- 1 | let numbers = [1, 2, 3, 4, 5, 6, 7]; 2 | 3 | // We use for loops when we know the exact number of times that we want the loop to execute. 4 | for (let idx = 0; idx < numbers.length; idx++) { 5 | console.log(numbers[idx]); 6 | } 7 | 8 | // There's another way to perform loops, which is the while-loop. 9 | // You would use the while-loop when you know which condition 10 | // must be true, to perform the loop, but not the exact number of times 11 | // you want the loop to be performed. 12 | 13 | let idx = 0; 14 | while (idx < numbers.length) { 15 | console.log(numbers[idx]); 16 | 17 | idx++; 18 | } 19 | 20 | let sum = 0; 21 | while (true) { 22 | console.log('Loop'); 23 | sum++; 24 | 25 | if (sum === 10) 26 | break; 27 | } 28 | -------------------------------------------------------------------------------- /6 JavaScript Arrays/8-combining-and-slicing-arrays.js: -------------------------------------------------------------------------------- 1 | // Let's say we have two arrays and we want to combine it into one array. 2 | const exampleNumbersA = [1, 2, 3]; 3 | const exampleNumbersB = [4, 5, 6]; 4 | 5 | // Can combine these arrays using the concat method. 6 | const combinedArray = exampleNumbersA.concat(exampleNumbersB); 7 | console.log('combinedArray', combinedArray); 8 | 9 | // slice(startIndex, endIndex) where the endIndex is exclusive (not included) 10 | // The slice method will not affect the original array. 11 | const firstSlice = combinedArray.slice(0, 4); 12 | console.log('firstSlice', firstSlice); 13 | 14 | // If you doing this will primitive values, then the elements will be passed by copy. 15 | // However if you're dealing with objects, then the elements will be passed by reference. 16 | 17 | -------------------------------------------------------------------------------- /6 JavaScript Arrays/16-reducing-an-array.js: -------------------------------------------------------------------------------- 1 | // JavaScript has a very powerful array method called reduce. 2 | // It can transform an array into just about anything, 3 | // such as a number, string, object, or another array. 4 | 5 | // This is how you would traditionally calculate the sum of an array of numbers. 6 | const numbers = [1, 10, 5, 14]; 7 | let sum = 0; 8 | 9 | for (const number of numbers) 10 | sum += number; 11 | 12 | console.log(`Total sum: ${sum}`); 13 | 14 | // There's a cleaner way to accomplish this with the sum method. 15 | // 1st argument is a callback function 16 | // this should take in two parameters for the accumulatorValue and the currentValue 17 | // 2nd argument is the initial value for the accumulator 18 | sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); -------------------------------------------------------------------------------- /2 JavaScript Variables/2-constants.js: -------------------------------------------------------------------------------- 1 | // We use the let keyword for variables which hold values that can be changed. 2 | // The const keyword is for values that can not be changed. 3 | 4 | const christmas_2024 = '12.25.2024'; 5 | console.log(christmas_2024); 6 | 7 | // If you tried to reassign the constant, then when you run it, 8 | // JavaScript would throw an error saying 'TypeError: Assignment to constant variable.' 9 | // christmas_2024 = '12.26.2024'; 10 | 11 | // May sometimes see constants named with the snake_case naming convention 12 | // depending on the naming convention of your development team. 13 | 14 | // Also may see variables named with snake_case with the letters capitalized. 15 | const COLOR_GREEN = 'green'; 16 | 17 | // Regardless of the naming convention, it's best to use descriptive names for your variables. -------------------------------------------------------------------------------- /6 JavaScript Arrays/10-iterating-an-array.js: -------------------------------------------------------------------------------- 1 | // To iterate over an array, you could use the for-of loop. 2 | const numbers = [1, 2, 3, 4, 5]; 3 | 4 | for (const number of numbers) 5 | console.log(number); 6 | 7 | // There is another built in method in the array class, known as .forEach() 8 | // so you pass a callback function as the argument for .forEach() 9 | 10 | 11 | numbers.forEach((number) => { 12 | console.log(number); 13 | }); 14 | 15 | // since the arrow function's code block is just one line 16 | // we can put everything on one line to simplify it 17 | // numbers.forEach(number => console.log(number)); 18 | 19 | // The argument for the .forEach() method also accepts an optional second parameter, 20 | // which is the index of the corresponding element. 21 | numbers.forEach((number, index) => console.log(`At index, ${index}: ${number}`)); -------------------------------------------------------------------------------- /6 JavaScript Arrays/9-spread-operator.js: -------------------------------------------------------------------------------- 1 | // There is another way to combine two arrays. 2 | // Which is to utilize the spread operator. 3 | 4 | // So the spread operator can be used 5 | // to copy the properties of an object or the elements of an array. 6 | 7 | const exampleNumbersA = [1, 2, 3]; 8 | const exampleNumbersB = [4, 5, 6]; 9 | 10 | // So rather than doing 11 | // let combined = exampleNumbersA.concat(exampleNumbersB); 12 | // Below is the more commonly used syntax. 13 | 14 | let combined = [...exampleNumbersA, ...exampleNumbersB]; 15 | console.log(combined); 16 | 17 | combined = [...exampleNumbersA, 9, ...exampleNumbersB, 10]; 18 | 19 | // Arrays are objects, meaning that they are passed by reference. 20 | let a = [1, 2]; 21 | let b = a; 22 | 23 | // So we could also use the spread operator in order to make a copy of an array. 24 | b = [...a]; -------------------------------------------------------------------------------- /6 JavaScript Arrays/7-emptying-an-array.js: -------------------------------------------------------------------------------- 1 | let numbers = [1, 2, 3, 4, 5]; 2 | 3 | // If you want to clear all the elements of an array, 4 | // there are different ways that you can do that. 5 | 6 | // If the numbers array was large, then this would be inefficient. 7 | while (numbers.length > 0) 8 | numbers.pop(); 9 | 10 | // could set the length property to 0 11 | 12 | numbers = [1, 2, 3, 4, 5]; 13 | 14 | numbers.length = 0; // we could assign it to 0, clearing/emptying the array 15 | 16 | // could use the .splice() method 17 | 18 | numbers = [1, 2, 3, 4, 5]; 19 | 20 | const deletedNumbers = numbers.splice(0, numbers.length); 21 | console.log(`deletedNumbers: ${deletedNumbers}`); 22 | 23 | // could reassign the array to an empty array, 24 | // the previous array would be garbage collected 25 | 26 | numbers = [1, 2, 3, 4, 5]; 27 | numbers = []; 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /2 JavaScript Variables/6-arrays.js: -------------------------------------------------------------------------------- 1 | // Arrays are used to store lists of data. 2 | // We use square brackets to create an array literal. 3 | let productColors = ['blue', 'green']; 4 | 5 | console.log(productColors); 6 | 7 | // The elements of an array can be accessed by index. 8 | // We begin counting the index from 0. 9 | // So to access the element of 'blue', 10 | // we would use productColors[0] 11 | 12 | // Arrays can contain values of any data type. 13 | // However we typically use arrays where all the elements are the same data type. 14 | 15 | // Arrays are objects. 16 | // Objects consist of key-value pairs. 17 | // In the context of arrays, the keys are an index value. (a numeric value starting from 0) 18 | 19 | // The data type is an object. 20 | console.log(typeof productColors); 21 | 22 | // A useful property that you'll often use: 23 | console.log(productColors.length); -------------------------------------------------------------------------------- /6 JavaScript Arrays/2-adding-elements.js: -------------------------------------------------------------------------------- 1 | // So one of the most common operations when dealing with arrays 2 | // is adding elements. 3 | 4 | // Using the const keyword, we can't reassign this variable to any other value, 5 | // but we can modify the array (the object) that it references. 6 | const numbers = [5, 4, 3, 2, 1]; 7 | 8 | // There are 3 ways to add an element to an array. 9 | // Add to the beginning with .unshift() 10 | // Add to the middle with .splice() 11 | // Add to the end with .push() 12 | 13 | numbers.unshift(14); 14 | numbers.unshift(17, 19); 15 | 16 | // 1st arg is the index position to start from, 17 | // 2nd arg is the number of elements to delete 18 | // then can specify one or more elements to add from that index position specified from the 1st arg 19 | numbers.splice(1, 0, 18); 20 | numbers.splice(1, 0, 25, 24); 21 | 22 | numbers.push(7); 23 | numbers.push(10, 11, 12); 24 | -------------------------------------------------------------------------------- /2 JavaScript Variables/8-types-of-functions.js: -------------------------------------------------------------------------------- 1 | // Functions are a building block in our programs. 2 | // They enable us to group together a block of code, 3 | // which is a set of statements defined within curly braces. 4 | 5 | // We create a function for one of two options. 6 | // The first option is to perform some action. 7 | // The second option is to calculate and return some value. 8 | 9 | // So not all functions require us to explicitly use the return keyword. 10 | // By default if we don't supply an explicit return value, 11 | // then JavaScript will have the function return the value undefined. 12 | 13 | function multiply(num1, num2) { 14 | return num1 * num2; 15 | } 16 | 17 | console.log( multiply(2, 2) ); 18 | 19 | // If we don't specify a return keyword, then JavaScript will return undefined by default. 20 | function add(num1, num2) { 21 | const sum = num1 + num2; 22 | } 23 | 24 | console.log( add(3, 3) ); -------------------------------------------------------------------------------- /5 JavaScript Objects/4-objects-are-dynamic.js: -------------------------------------------------------------------------------- 1 | // Objects in JavaScript are dynamic. 2 | // Meaning that we can add properties or methods at any time. 3 | 4 | // The const keyword used with an object, means that we can't reassign it. 5 | // But we can still change/mutate the properties and methods the object 6 | // that it references. 7 | const person = { 8 | name: 'Steven' 9 | }; 10 | 11 | console.log(person); 12 | 13 | // We can add properties on the fly with dot notation (member notation) 14 | person.favoriteFood = 'tacos'; 15 | 16 | console.log(person); 17 | 18 | // Could also use bracket notation 19 | person['favoriteIceCream'] = 'chocolate'; 20 | 21 | console.log(person); 22 | 23 | // You could delete properties with the delete keyword 24 | delete person.favoriteIceCream; 25 | 26 | console.log(person); 27 | 28 | person.eat = function() { 29 | console.log('start eating'); 30 | } 31 | 32 | person.eat(); 33 | -------------------------------------------------------------------------------- /7 JavaScript Functions/3-arguments.js: -------------------------------------------------------------------------------- 1 | function multiply(num1, num2){ 2 | return num1 * num2; 3 | } 4 | 5 | console.log( multiply(2, 2) ); 6 | 7 | // but if we were to call this function and only supply one argument 8 | 9 | console.log( multiply(2) ); // NaN 10 | 11 | // If we don't supply an argument, then that parameter will be assigned the value of undefined. 12 | 13 | // You could also pass in more arguments than there are parameter variables defined. 14 | // To access those arguments, you could use the built in arguments object. 15 | // Every function in JavaScript has access to a special function named arguments. 16 | // So we just need to iterate over the arguments object. 17 | 18 | function add(num1, num2) { 19 | console.log(arguments); 20 | let product = 1; 21 | for (const num of arguments) 22 | product *= num; 23 | 24 | return product; 25 | } 26 | 27 | console.log( add(1, 2, 3, 4) ); -------------------------------------------------------------------------------- /6 JavaScript Arrays/5-arrow-functions.js: -------------------------------------------------------------------------------- 1 | // Previously we used the function syntax for the callback function for the find() method 2 | 3 | const employees = [ 4 | { 5 | id: 1, 6 | name: 'Jim', 7 | }, 8 | { 9 | id: 2, 10 | name: 'Michael Scott', 11 | }, 12 | { 13 | id: 3, 14 | name: 'Pam', 15 | }, 16 | ]; 17 | 18 | // We pass a callback function which in this case is a predicate function. 19 | // A predicate function is one which returns a boolean value (true or false). 20 | // Here we use the arrow function syntax. 21 | 22 | // So .find() returns the first element that matches 23 | 24 | let employee = employees.find(e => e.name === 'Jim'); 25 | 26 | // When you have an arrow function that has just one statement in the code block, 27 | // then you can put everything on one line. 28 | const add = (num1, num2) => { 29 | return num1 + num2; 30 | } 31 | 32 | // const add = (num1, num2) => num1 + num2; -------------------------------------------------------------------------------- /7 JavaScript Functions/8-local-vs-global-scope.js: -------------------------------------------------------------------------------- 1 | // Global scope, so a variable declared outside any function block or conditional 2 | // has a global scope. 3 | // Meaning that it is accessible from any part of the code after its declaration. 4 | 5 | // This variable is declared in the global scope. 6 | const name = 'Steven'; 7 | console.log(name); 8 | 9 | // Local scope refers to variables declared within blocks, functions, or conditionals. 10 | // So these variables are only accessible within the confines 11 | // of their curly braces. 12 | 13 | { 14 | let lastName = 'Garcia'; 15 | console.log(lastName); 16 | } 17 | 18 | // however we can't access the variable, lastName, outside of the code block 19 | 20 | function greet() { 21 | // So the variable, message, is a local variable 22 | const message = 'Hello World'; 23 | 24 | console.log(message); 25 | } 26 | 27 | greet(); 28 | 29 | // can't access the variable, message, outside of the function block 30 | -------------------------------------------------------------------------------- /3 JavaScript Operators/2-arithmetic-operators.js: -------------------------------------------------------------------------------- 1 | // An expression in JavaScript is something that produces a value. 2 | // An expression goes on the right side of our variable assignment. 3 | 4 | // In JavaScript, we have different arithmetic operators. 5 | // -, +, *, /, % 6 | 7 | // % is the modulo operator and it returns the remainder of division. 8 | 9 | console.log(2 + 2); // 4 10 | 11 | console.log(4 - 2); // 2 12 | 13 | console.log(2 * 2); // 4 14 | 15 | console.log(9 / 3); // 3 16 | 17 | console.log(10 % 2); // the remainder of 0 18 | 19 | console.log(3 ** 2); // 3^2 = 9 (raised to the power of) 20 | 21 | // We also have shorthand (syntactic sugar) to increment or decrement a value 22 | let a = 10; 23 | 24 | a = a + 1; 25 | 26 | a += 1; 27 | 28 | // This will increment the value of a, and then return the previous value. 29 | a++; 30 | 31 | // This will increment the value of a, and then return the updated value. 32 | ++a; 33 | 34 | a -= 1; 35 | 36 | a--; 37 | 38 | --a; -------------------------------------------------------------------------------- /4 Control Flow/1-if-else-statement.js: -------------------------------------------------------------------------------- 1 | // Programming is powerful as it enables us to execute different code based on conditions. 2 | // This is what enables us to provide dynamic and personalized 3 | // applications to end users. 4 | 5 | // The fundamental programming concept that enables this is conditional statements. 6 | // More specifically, if-else statements. 7 | 8 | let priceOfChocolate = 1.99; 9 | let hasAmountInCash = 5; 10 | 11 | const canBuyChocolate = hasAmountInCash >= priceOfChocolate; 12 | 13 | console.log('canBuyChocolate', canBuyChocolate); 14 | console.log(typeof canBuyChocolate); 15 | 16 | if (hasAmountInCash >= priceOfChocolate) { 17 | console.log('Enjoy your purchase'); 18 | } else { 19 | console.log('Sorry you do not have enough'); 20 | } 21 | 22 | let hour = 10; 23 | 24 | if (hour > 6 && hour <= 12) { 25 | console.log('Serving breakfast'); 26 | } else if (hour > 12 && hour <= 14) { 27 | console.log('Serving lunch'); 28 | } else { 29 | console.log('Serving dinner'); 30 | } -------------------------------------------------------------------------------- /5 JavaScript Objects/9-cloning-an-object.js: -------------------------------------------------------------------------------- 1 | let a = { value: 10 }; 2 | let b = a; 3 | 4 | // Since they both reference the same object, if you update one variable, 5 | // it will be reflected in the other variable. 6 | b.value = 20; 7 | 8 | console.log(a); 9 | console.log(b); 10 | 11 | // So if you wanted to have it be the same where 12 | // if you change one property it doesn't affect the other variable. 13 | // Then you would need to create a clone of that object. 14 | 15 | // The first argument is the object you want to copy to. (the target object) 16 | // Then you could pass one or more source objects whose properties and methods 17 | // will be copied to the target object. 18 | // So this creates a copy of the object so changing one won't affect the other. 19 | Object.assign(b, a); 20 | 21 | // We have a more modern syntax to accomplish this, using the spread operator. 22 | // The spread operator is represented with three dots. 23 | // So this creates a copy of the object so changing one won't affect the other. 24 | b = { ...a }; -------------------------------------------------------------------------------- /3 JavaScript Operators/8-logical-operators-with-non-booleans.js: -------------------------------------------------------------------------------- 1 | // Expressions are evaluated from left to right. 2 | // When using logical operators with non-boolean values, 3 | // rather than returning the value of true or false, 4 | // it will return the value of the operand. 5 | 6 | // so in the case of || (or operator) 7 | console.log(false || 'Steven'); // returns 'Steven' 8 | 9 | // So since 'Steven' is evaluated to truthy, it will be the value returned 10 | // the OR operator returns the first truthy value 11 | 12 | // The falsy values in JavaScript are... 13 | // undefined, null, 0, false, '', NaN 14 | // anything else that doesn't fall in this category is considered truthy 15 | 16 | console.log(false || 1 || 2); // returns 1 17 | // The JavaScript OR operator, ||, performs short-circuit evaluation. 18 | // Meaning it stops the expression once it can evaluate to 'truthy' or 'falsy'. 19 | 20 | // Another example 21 | let usersChosenColor = 'blue'; 22 | let defaultColor = 'green'; 23 | 24 | const currentWebsiteColor = usersChosenColor || defaultColor; -------------------------------------------------------------------------------- /6 JavaScript Arrays/11-joining-arrays.js: -------------------------------------------------------------------------------- 1 | // To transform an array into a string, the join() method can be utilized. 2 | const numbers = [1, 2, 3, 4, 5]; 3 | 4 | // Can convert the array into a string, 5 | // where you specify the separate as the argument which will be placed in between the elements. 6 | const joinedNumbers = numbers.join(', '); 7 | console.log(joinedNumbers); 8 | 9 | // Likewise, the .split() method is available for strings, 10 | // this is done to convert a string into an array. 11 | // This will not alter the original string, rather it will return an array. 12 | const courseName = 'JavaScript for Beginners'; 13 | const parts = courseName.split(' '); 14 | console.log(parts); 15 | 16 | // So an example which shows how this could be useful, 17 | // consider the term, URL (Uniform Resource Locator) slug 18 | 19 | // This refers to having a descriptive path in your URL. 20 | // URL slugs are separated by a hyphen 21 | 22 | // Utilize method chaining 23 | const urlSlug = courseName 24 | .toLowerCase() 25 | .split(' ') 26 | .join('-'); -------------------------------------------------------------------------------- /6 JavaScript Arrays/15-mapping-an-array.js: -------------------------------------------------------------------------------- 1 | // The .map() method is a cornerstone of array manipulation. 2 | // It's a powerful way to process and transform array elements. 3 | 4 | // It operates on each element of an array, 5 | // applying a function that you specify, and returns a new array composed of the results. 6 | 7 | // So it allows you to transform data without altering the original array. 8 | 9 | const numbers = [2, 4, 6, 8, 10]; 10 | const squaredNumbers = numbers.map(num => num * num); 11 | console.log('squaredNumbers ', squaredNumbers); 12 | 13 | const characters = ['a', 'b', 'c', 'd']; 14 | const upperCaseCharacters = characters.map(char => char.toUpperCase()); 15 | console.log('upperCaseCharacters', upperCaseCharacters); 16 | 17 | const employees = [ 18 | { id: 1, name: 'Alice', email: 'AliCe@gmail.com' }, 19 | { id: 2, name: 'Steven', email: 'STeVen@gmail.com' }, 20 | { id: 3, name: 'Joe', email: 'Joe@gmail.com' }, 21 | ]; 22 | 23 | const updatedEmployees = employees.map(employee => ({ 24 | ...employee, 25 | email: email.toLowerCase() 26 | })); -------------------------------------------------------------------------------- /6 JavaScript Arrays/14-filtering-an-array.js: -------------------------------------------------------------------------------- 1 | // One of the most versatile built in methods for arrays in JavaScript 2 | // is the filter method. 3 | 4 | // This method is designed to go through an array and extract elements 5 | // that meet a specific condition. 6 | // Returning a new array comprised of only those elements. 7 | 8 | // It's useful for creating subsets of an array that match certain criteria. 9 | 10 | const numbers = [1, 2, 3, 4, 5, 6]; 11 | 12 | // So you pass in a callback predicate function as an argument. 13 | // Once again, predicate functions are functions that return a boolean value. (true or false) 14 | const evenNumbers = numbers.filter(number => number % 2 === 0); 15 | console.log(evenNumbers); 16 | 17 | const employees = [ 18 | { id: 1, name: 'Alice', role: 'Developer' }, 19 | { id: 2, name: 'Bob', role: 'Designer' }, 20 | { id: 3, name: 'Charlie', role: 'Manager' }, 21 | { id: 4, name: 'Danielle', role: 'Developer' }, 22 | ]; 23 | 24 | const developers = employees.filter(employee => employee.role === 'Developer'); 25 | console.log(developers); -------------------------------------------------------------------------------- /7 JavaScript Functions/7-try-and-catch.js: -------------------------------------------------------------------------------- 1 | // The powerful concept of error handling is needed for all JavaScript 2 | // applications that utilize backend APIs. 3 | 4 | // This is done through try-catch blocks. 5 | 6 | 7 | 8 | let course = { 9 | name: 'JavaScript for Beginners', 10 | duration: '3 hours', 11 | get details() { 12 | return `${this.name} is ${this.duration}`; 13 | }, 14 | set details(value) { 15 | if (typeof value !== 'string') { 16 | // Here we are throwing an exception. 17 | throw new Error(`Vallue, ${value} is not a string`); 18 | } 19 | 20 | let parts = value.split(' is '); 21 | 22 | this.name = parts[0]; 23 | this.duration = parts[1]; 24 | } 25 | }; 26 | 27 | // Using try-catch blocks enable us to catch possible exceptions 28 | // so that we can gracefully handle errors without our programs crashing/terminating. 29 | try { 30 | // Within try blocks, would place code that could potentially throw exceptions. 31 | course.details = 42; 32 | } catch (e) { 33 | console.log(`Caught an error: ${e.message}`); 34 | } -------------------------------------------------------------------------------- /7 JavaScript Functions/9-let-vs-var.js: -------------------------------------------------------------------------------- 1 | // The differences between the let and var keyword are a commonly asked interview question. 2 | // In JavaScript versions prior to ES6 (ECMAScript 2015), the var keyword was used to declare variables. 3 | 4 | // The var keyword is function-scoped. Meaning that it is available anywhere within a function. 5 | function display() { 6 | for (var i = 0; i < 5; i++) { 7 | console.log(i); 8 | } 9 | 10 | // we can still access the variable, i, outside of the block it is defined in 11 | console.log(i); 12 | } 13 | 14 | // The let keyword introduces block-scoping to JavaScript. 15 | // This means that a variable declared with let, is only accessible within the block it's defined in. 16 | 17 | function displayNumbers() { 18 | for (let i = 0; i < 5; i++) { 19 | console.log(i); 20 | } 21 | 22 | // we cannot access the variable, i, outside of the block it is defined it 23 | // since we declared it with the let keyword and it is therefore, block-scoped 24 | 25 | // if we tried to access it, then it would result in a ReferenceError 26 | // console.log(i); 27 | } 28 | -------------------------------------------------------------------------------- /6 JavaScript Arrays/4-finding-reference-types-in-arrays.js: -------------------------------------------------------------------------------- 1 | // So the employees object stores 3 objects/reference types. 2 | // When dealing with reference types, we can use the indexOf(), lastIndexOf(), or includes() 3 | // methods built into arrays in order to find an element. 4 | 5 | // As if you compare two different objects, even if they have the same property values, 6 | // they won't be equal and it would be comparing their memory addresses, which differ. 7 | 8 | // Rather we would have to use .find(), .findIndex(), and pass in a predicate callback function 9 | // as the argument. 10 | 11 | const employees = [ 12 | { 13 | id: 1, 14 | name: 'Jim', 15 | }, 16 | { 17 | id: 2, 18 | name: 'Michael Scott', 19 | }, 20 | { 21 | id: 3, 22 | name: 'Pam', 23 | }, 24 | ]; 25 | 26 | // We pass a callback function which in this case is a predicate function. 27 | // A predicate function is one which returns a boolean value (true or false). 28 | 29 | // So .find() returns the first element that matches 30 | 31 | let employee = employees.find(function(e) { 32 | return e.name === 'Jim' 33 | }); 34 | -------------------------------------------------------------------------------- /7 JavaScript Functions/6-getters-and-setters.js: -------------------------------------------------------------------------------- 1 | // Getters and setters within JavaScript, enhance how you interact with object properties. 2 | 3 | let course = { 4 | name: 'JavaScript for Beginners', 5 | duration: '3 hours', 6 | details() { 7 | return `${this.name} is ${this.duration}`; 8 | } 9 | }; 10 | 11 | console.log(`${course.name} is ${course.duration}`); 12 | 13 | console.log( course.details() ); 14 | 15 | // By using getters and setters, these enable us to define custom logic 16 | // for reading and writing properties. 17 | // This enables us to use methods as if they were regular properties 18 | // as a means of encapsulation. 19 | // So they act like virtual properties. 20 | 21 | course = { 22 | name: 'JavaScript for Beginners', 23 | duration: '3 hours', 24 | get details() { 25 | return `${this.name} is ${this.duration}`; 26 | }, 27 | set details(value) { 28 | let parts = value.split(' is '); 29 | 30 | this.name = parts[0]; 31 | this.duration = parts[1]; 32 | } 33 | }; 34 | 35 | console.log( course.details ); 36 | 37 | course.details = 'JavaScript Pro is 10 hours'; 38 | 39 | console.log( course.details ); -------------------------------------------------------------------------------- /4 Control Flow/2-switch-case-statement.js: -------------------------------------------------------------------------------- 1 | // Switch-case statements can also be used for control flow. 2 | // The difference between if-else statements and switch-case statements 3 | // is that switch-case statements are only used for equality comparisons. 4 | 5 | let job = 'Software Developer'; 6 | 7 | if (job === 'Software Developer') { 8 | console.log('Writes code'); 9 | } else if (job === 'Designer') { 10 | console.log('Makes user interface documents'); 11 | } else if (job === 'Cloud Engineer') { 12 | console.log('Manages and deploys cloud resources'); 13 | } else { 14 | console.log('Works directly with customers'); 15 | } 16 | 17 | // Since we doing equality comparisons, this can be hard to read and reptitive. 18 | // So in this case, we could use the switch-case statements. 19 | 20 | switch (job) { 21 | case 'Software Developer': 22 | console.log('Writes code'); 23 | break; 24 | case 'Designer': 25 | console.log('Makes user interface documents'); 26 | break; 27 | case 'Cloud Engineer': 28 | console.log('Manages and deploys cloud resources'); 29 | break; 30 | default: 31 | console.log('Works directly with customers'); 32 | } -------------------------------------------------------------------------------- /5 JavaScript Objects/11-built-in-math-functions.js: -------------------------------------------------------------------------------- 1 | // In JavaScript, we have a built-in class called Math 2 | // This has static helper methods to help us do mathematical calculations. 3 | // It is often utilized in programming interviews. 4 | // Refer to the documentation at developer.mozilla.org since there are many built in methods 5 | 6 | // Some of the most commonly used built-in methods 7 | 8 | console.log( Math.round(3.14) ); // will round the number to 3 9 | 10 | console.log( Math.round(3.6) ); // will round the number to 4 11 | 12 | console.log( Math.floor(4.6) ); // 4 13 | 14 | console.log( Math.ceil(4.2) ); // 5 15 | 16 | console.log( Math.max(1, 2) ); 17 | 18 | console.log( Math.max(1, 2, 3, 4, 5) ); 19 | 20 | console.log( Math.min(1, 2, 3) ); 21 | 22 | console.log( Math.pow(2, 3) ); 23 | 24 | console.log( Math.sqrt(25) ); 25 | 26 | console.log( Math.random() ); // returns a decimal value between 0 and 1 27 | 28 | // to return a value between a range 29 | let min = 1; 30 | let max = 10; 31 | 32 | const randomNum = Math.random() * (max - min) + min; 33 | 34 | // To make it an integer value 35 | const randomIntNum = Math.round( Math.random() * (max - min) + min ); 36 | 37 | console.log(randomNum); -------------------------------------------------------------------------------- /5 JavaScript Objects/14-the-date-object.js: -------------------------------------------------------------------------------- 1 | // In JavaScript we have a built in Date object which stores the date and time. 2 | // It also provides methods for data and time management. 3 | 4 | // We would use the Date object most commonly to store creation and modification times 5 | // for a resource in our database. 6 | 7 | // The Date object can be initialized many different ways. 8 | // refer to the documentation at developer.mozilla.org 9 | 10 | let now = new Date(); 11 | 12 | console.log( now ); 13 | 14 | // passing a number as an argument, 15 | // will represent the number of milliseconds since Jan 1, 1970 16 | let Jan01_1970 = new Date(0); // 0 seconds since Jan 1, 1970 17 | console.log(Jan01_1970); 18 | 19 | let Dec31_1969 = new Date(-24 * 3600 * 1000); 20 | console.log(Dec31_1969); 21 | 22 | const dateOne = new Date('December 25, 2024 16:08'); 23 | 24 | const Jan1_2024 = new Date(2024, 0, 1); // Jan 1, 2024 25 | 26 | console.log( now.getFullYear() ); 27 | 28 | // Represented as a number, 29 | // so 0 = Jan, 1 = Feb, etc. 30 | console.log( now.getMonth() ); 31 | 32 | // difference between UTC (Coordinated Universal Time) and local time zone 33 | console.log( now.getTimezoneOffset() ); 34 | 35 | 36 | -------------------------------------------------------------------------------- /5 JavaScript Objects/6-functions-are-objects.js: -------------------------------------------------------------------------------- 1 | // Functions are objects in JavaScript 2 | 3 | // So this function is an object in memory 4 | function add(num1, num2) { 5 | return num1 + num2; 6 | } 7 | 8 | // So now n references this object in memory, the function named add. 9 | const n = add; 10 | 11 | console.log( n(2, 2) ); 12 | 13 | // So the function named add, has members. 14 | // Meaning that it has properties and methods. 15 | 16 | // This will output the number of parameters that the add function has. 17 | console.log( add.length ); 18 | 19 | // This constructor function is an object in memory 20 | function Programmer(name) { 21 | this.name = name; 22 | this.writeCode = function() { 23 | console.log('Code in JavaScript'); 24 | } 25 | } 26 | 27 | console.log( Programmer.length ); // 1 parameter 28 | console.log( Programmer.constructor ); // references the constructor function 29 | 30 | // To futher demonstrate how functions are objects in JavaScript 31 | const ProgrammerFunc = new Function('name', ` 32 | this.name = name; 33 | this.writeCode = function() { 34 | console.log('Code in JavaScript'); 35 | } 36 | `); 37 | 38 | const newProgrammer = new ProgrammerFunc('Steven'); 39 | newProgrammer.writeCode(); 40 | 41 | -------------------------------------------------------------------------------- /2 JavaScript Variables/5-objects.js: -------------------------------------------------------------------------------- 1 | // Objects are reference types. (They are not a primitive value) 2 | // Objects represent nouns. (person, place, or thing) 3 | // They contain state or behavior, allowing you to group together related values. 4 | 5 | // Object Literals use curly braces. 6 | // Here you would specify key-value pairs. 7 | let course = { 8 | name: 'JavaScript for Beginners', 9 | hours: 3, 10 | }; 11 | 12 | // You can access a property through dot notation. 13 | console.log(course.name); 14 | 15 | // You can also reassign the value. 16 | course.name = 'JavaScript Fundamentals'; 17 | 18 | console.log(course.name); 19 | 20 | // You can also access properties through bracket notation. 21 | // You would typically use dot notation however bracket notation is used 22 | // if you don't know the exact key/property you want to access until runtime. 23 | 24 | console.log(course['name']); 25 | 26 | course['name'] = 'JavaScript 101'; 27 | 28 | console.log(course.name); 29 | 30 | // An example of how you would use bracket notation. 31 | let property = 'hours'; 32 | console.log(course[property]); 33 | 34 | // To demonstrate the different aspects of a JavaScript object. 35 | // The key-value is referred to as a property of the JavaScript object. 36 | let obj = { 37 | key: 'value' 38 | }; -------------------------------------------------------------------------------- /6 JavaScript Arrays/13-testing-elements-of-an-array.js: -------------------------------------------------------------------------------- 1 | // In JavaScript arrays come equipped with several powerful methods 2 | // that allow us to process and evaluate the data within them efficiently. 3 | 4 | // Two such methods are .every() and .some() 5 | // Both of which are used to test elements in an array against a condition. 6 | 7 | // .every() tests whether all elements of an array pass the test of the provided function. 8 | // It returns true if every element in the array satisfies the condition and false otherwise. 9 | 10 | let numbers = [2, 4, 6, 8, 10]; 11 | 12 | // so .every() can accept up to three parameters 13 | // 1st param: the current element of the array 14 | // 2nd param (optional): the index of where the element is stored 15 | // 3rd param (optional): the original array 16 | const areAllEven = numbers.every(number => number % 2 === 0); 17 | console.log(`areAllEven: ${areAllEven}`); 18 | 19 | // .some() checks if at least one element in the array passes the test 20 | // implemented by the provided function. 21 | 22 | numbers = [1, 3, 5, 7, 8, 9]; 23 | 24 | // 1st param: the current element of the array 25 | // 2nd param (optional): the index of where the element is stored 26 | // 3rd param (optional): the original array 27 | const hasOneEvenNumber = numbers.some(number => number % 2 === 0); -------------------------------------------------------------------------------- /5 JavaScript Objects/8-enumerating-properties-of-an-object.js: -------------------------------------------------------------------------------- 1 | // We have the for-of loop for iterating over an array. 2 | // We have the for-in loop to iterate over the keys of an object. 3 | 4 | let numbers = [1, 2, 3, 4, 5]; 5 | 6 | for (const elements of numbers) 7 | console.log(elements); 8 | 9 | const dog = { 10 | name: 'Max', 11 | age: 5, 12 | eyeColor: 'blue' 13 | }; 14 | 15 | for (const key in dog) 16 | console.log(dog[key]); 17 | 18 | // We have another syntax for enumerating over the keys and values of an Object 19 | 20 | // This returns the keys of the object as an array 21 | // Such as: ['name', 'age', 'eyeColor'] 22 | const keys = Object.keys(dog); 23 | 24 | for (const key of Object.keys(dog)) 25 | console.log(key); 26 | 27 | // This returns the values of the object as an array 28 | // Such as: ['Max', 5, 'blue'] 29 | const values = Object.values(dog); 30 | 31 | for (const value of Object.values(dog)) 32 | console.log(value); 33 | 34 | // This returns the key-value pairs of the object as an array. 35 | // So each element will be an array itself, [key, value] 36 | // Such as: [['name', 'Max'], ['age', 5], ['eyeColor', 'blue']]; 37 | const entires = Object.entries(dog); 38 | 39 | for (const entry of Object.entries(dog)) 40 | console.log(`Key: ${entry[0]} => Value: ${entry[1]}`); -------------------------------------------------------------------------------- /7 JavaScript Functions/5-default-parameters.js: -------------------------------------------------------------------------------- 1 | // Default parameters enhance function flexibility. 2 | function writeCode(language) { 3 | console.log(`Write code in ${language}`); 4 | } 5 | 6 | writeCode('JavaScript'); 7 | writeCode('C#'); 8 | 9 | // But what if we were to call writeCode() without any arguments 10 | // The parameter, language, would have the value of undefined by default. 11 | writeCode(); 12 | 13 | // We can assign a default value to parameters, 14 | // ensuring that our function behaves predictably 15 | // even when specific arguments aren't provided. 16 | 17 | function writeProgram(language = 'JavaScript') { 18 | console.log(`Write code in ${language}`); 19 | } 20 | 21 | // If you set a default parameter, then all parameters that follow 22 | // must also be assigned a default value. 23 | function codeDetails(language = 'JavaScript', tool = 'VS Code') { 24 | console.log(`Writing code in ${language} using ${tool}`); 25 | } 26 | 27 | // This enables us to call/invoke our function with flexibility 28 | codeDetails(); 29 | codeDetails('Python'); 30 | codeDetails('C#', 'Visual Studio'); 31 | 32 | function createUser(name, role = 'guest', status = 'active') { 33 | console.log(`User: ${name}, Role: ${role}, Status: ${status}`); 34 | } 35 | 36 | createUser('Steven'); 37 | createUser('Alice', 'admin', 'active'); 38 | -------------------------------------------------------------------------------- /5 JavaScript Objects/7-value-vs-reference-types.js: -------------------------------------------------------------------------------- 1 | // We have eight different data types in JavaScript 2 | // Which include 7 primitive data types, which include 3 | // number, string, boolean, BigInt, undefined, null, and Symbol 4 | 5 | // The eight data type are objects 6 | // Arrays and functions fall into the object category 7 | 8 | // The reason we differentiate the data types is because of how they are allocated in memory. 9 | 10 | // So when working with primitive values, they are passed by copy. 11 | // Meaning that if you were to assign a variable to an existing variable (containing a primitive value) 12 | // Then that new variable would be given a copy of that primitive value. 13 | // Then changing one of the variables won't affect the other variable. 14 | // This is because they are two different variables and are assigned to different memory addresses. 15 | 16 | let a = 10; 17 | let b = a; 18 | 19 | a = 20; 20 | 21 | console.log(a); // 20 22 | console.log(b); // 10 23 | 24 | // Now consider references types 25 | a = { value: 20 }; 26 | b = a; 27 | 28 | a.value = 100; 29 | 30 | console.log(a); // 100 31 | console.log(b); // 100 32 | 33 | // So they have the same value, this is because objects are passed by reference. 34 | // Both of the variables a and b are assigned to the same object in memory (the same memory address) 35 | 36 | // So to summarize 37 | // Primitive values are copied by their value. 38 | // Objects are copied by reference. -------------------------------------------------------------------------------- /5 JavaScript Objects/2-factory-functions.js: -------------------------------------------------------------------------------- 1 | // So if we were to create another object with the same properties 2 | // and methods as the dog object, it would require that we copy and paste. 3 | // Copy and pasting is a sign of code duplication which is somethig that 4 | // we want to avoid in our programs. 5 | 6 | const dog = { 7 | name: 'Max', 8 | breed: 'Dachshund', 9 | age: 5, 10 | weightInPounds: 12, 11 | eat: function() { 12 | console.log('Chomp!'); 13 | }, 14 | bark() { 15 | console.log('Woof!'); 16 | } 17 | }; 18 | 19 | // This makes our code harder to read, more susceptible to bugs, 20 | // and more difficult to modify. 21 | 22 | // One way that we can create another dog object, it to use a factory function. 23 | // This refers to a function, named with the camelCase naming convention, 24 | // which returns an object literal. 25 | 26 | // The details are within the factory function and we pass arguments to the 27 | // factory function's parameter variables. The arguments are used 28 | // to create that custom object. 29 | 30 | function getDog(name, breed, age, weightInPounds) { 31 | return { 32 | name, 33 | breed, 34 | age, 35 | weightInPounds, 36 | eat: function() { 37 | console.log(this.name + ': Chomp!'); 38 | }, 39 | bark() { 40 | console.log(this.name + ': Woof!'); 41 | } 42 | }; 43 | } 44 | 45 | const anotherDog = getDog('Marley', 'Chocolate Lab', 3, 60); -------------------------------------------------------------------------------- /6 JavaScript Arrays/3-finding-primitive-elements.js: -------------------------------------------------------------------------------- 1 | // Arrays can store both primitive data types or reference data types (objects). 2 | // There are three main methods we can use to check if an array contains a primitive value. 3 | 4 | // .indexOf() 5 | // .lastIndexOf() 6 | // .includes() 7 | 8 | const numbers = [5, 4, 3, 2, 1, 3]; 9 | 10 | const indexOfThree = numbers.indexOf(3); 11 | console.log('indexOfThree', indexOfThree); // outputs 2, since the element 3, is at the index of 2 12 | console.log( numbers[indexOfThree] ); 13 | 14 | // searches from right to left 15 | const lastIndexOfThree = numbers.lastIndexOf(3); 16 | console.log('indexOfThree', indexOfThree); // outputs 25 since the element 3's last occurence is at the index of 5 17 | 18 | const indexOfTen = numbers.indexOf(10); 19 | 20 | // So if an element is not found, then the index will be -1 21 | // if you try accessing the array at the position of -1, then it will be undefined 22 | 23 | // So whenever we do .indexOf() or .lastIndexOf() 24 | // we would usually have a conditional statement to ensure the index position is not -1 25 | 26 | if (indexOfTen === -1) { 27 | console.log('10 is not found in the array'); 28 | } 29 | 30 | // If we are not utilizing that index value in order to access or change that element, 31 | // then we can just use the includes method which will return true or false. 32 | if (numbers.includes(10)) { 33 | console.log('10 is found in the array'); 34 | } 35 | 36 | if (!numbers.includes(10)) { 37 | console.log('10 is not found in the array'); 38 | } -------------------------------------------------------------------------------- /7 JavaScript Functions/4-the-rest-operator.js: -------------------------------------------------------------------------------- 1 | // Previously we covered the spread operator which is used for cloning objects in JavaScript. 2 | let course = { 3 | name: 'JavaScript for Beginners', 4 | duration: '3 hours' 5 | }; 6 | 7 | let newCourse = { ...course }; 8 | console.log('newCourse', newCourse); 9 | 10 | // So the spread operator allows us to easily copy properties and methods 11 | // from one object to another. Making a clone of the object. 12 | 13 | // We could also modify the properties for our own custom use. 14 | newCourse = { 15 | ...course, 16 | name: 'JavaScript Pro' 17 | }; 18 | 19 | console.log('newCourse', newCourse); 20 | 21 | // Now a similar syntax can be used in the context of functions. 22 | // So when we use, ..., in functions, we refer to it as the rest operator. 23 | // So unlike the spread operator which expands an array or object, 24 | // the rest operator allows us to gather a varying number of arguments 25 | // into a single array parameter. 26 | 27 | // This is particularly useful when we want a function 28 | // to accept an indefinite number of arguments. 29 | 30 | // The name of the parameter doesn't matter. 31 | function multiply(...args) { 32 | return args.reduce((accumulator, currentValue) => accumulator * currentValue, 1); 33 | } 34 | 35 | console.log( multiply(1, 2, 3, 4) ); // results in the value of 24 36 | 37 | // so the parameter numbers is an array containing a varying number of values 38 | // based on the arguments supplied 39 | function multiplier(multiplierValue, ...numbers) { 40 | return numbers.map(number => number * multiplierValue); 41 | } 42 | 43 | console.log( multiplier(2, 1, 2, 3, 4) ); -------------------------------------------------------------------------------- /5 JavaScript Objects/12-string-methods.js: -------------------------------------------------------------------------------- 1 | // refer to the documentation at mozilla.developer.org 2 | 3 | // We have string literals 4 | const name = 'Steven'; 5 | console.log(typeof name); // 'string' 6 | 7 | // can also make a string using the string object 8 | const anotherName = new String('Joe'); 9 | console.log(typeof anotherName); // 'object' 10 | 11 | // we can access the methods of strings using dot notation or bracket notation 12 | // The JavaScript engine will internally wrap the string literal with the string object. 13 | 14 | // There are built in methods for strings that allow us to operate and manipulate strings. 15 | let sentence = 'A new sentence'; 16 | 17 | const doesIncludeNew = sentence.includes('new'); 18 | console.log('doesIncludeNew', doesIncludeNew); // true 19 | 20 | // can access characters by index value, where the first character of a string is at the index 0 21 | console.log(sentence[3]); // 'e' 22 | 23 | const startsWithA = sentence.startsWith('A'); 24 | console.log('startsWithA', startsWithA); // true 25 | 26 | const endsWithA = sentence.endsWith('A'); 27 | console.log('endsWithA', endsWithA); // false 28 | 29 | let updatedSentence = sentence.replace('new', 'short'); 30 | console.log(updatedSentence); // 'A short sentence' 31 | 32 | let input = ' username@gmail.com '; 33 | console.log( trim(input) ); // 'username@gmail.com', so trim() removes spaces at the beginning and the end 34 | 35 | // split(), will split the sentence into an array 36 | const wordsInSentence = sentence.split(' '); // so split on the empty space 37 | console.log(wordsInSentence); 38 | 39 | let email = 'TesTEmail@gmail.com'; 40 | console.log( email.toLowerCase() ); 41 | console.log( email.toUpperCase() ); -------------------------------------------------------------------------------- /5 JavaScript Objects/3-constructor-functions.js: -------------------------------------------------------------------------------- 1 | // So we know that the object literal syntax creates one object. 2 | // We can easily use factory functions and have it return an object. 3 | // Factory functions provide an efficient and reusable way to create new objects 4 | // which the same state and behavior. (properties and methods) 5 | 6 | // However factory functions are not the common way of achieving this, 7 | // rather we use constructor functions. 8 | 9 | // Constructor functions construct the initial state of an object. 10 | // We name our constructor functions using PascalNotation. 11 | // We would name our constructor function as a noun, rather than a verb. 12 | // Then we utilize the 'this' keyword, as in 'this current object' 13 | // to set the state and behavior. (properties and methods) 14 | 15 | function Dog(name, breed, age, weightInPounds) { 16 | // this is done internally 17 | // this = {}; 18 | 19 | // Add properties to this object 20 | this.name = name; 21 | this.breed = breed; 22 | this.age = age; 23 | 24 | // Add methods to this object 25 | 26 | this.eat = function() { 27 | console.log(this.name + ': Chomp!'); 28 | }, 29 | 30 | this.bark = function() { 31 | console.log(this.name + ': Woof!'); 32 | } 33 | 34 | // this is done internally 35 | // return this; 36 | } 37 | 38 | // To call the constructor function, we use a special keyword, new. 39 | // So we would say that we, instantiated a new Dog object in memory. 40 | // The new keyword, creates an empty JavaScript object. 41 | // It then sets the new keyword to reference this object in memory. 42 | // Then it returns the this keyword. 43 | 44 | // The goal of a constructor function is to instantiate/initialize an object 45 | // with an initial state. (set by the arguments passed to the parameter variables) 46 | 47 | const anotherDog = new Dog('Marley', 'Chocolate Lab', 3, 60); -------------------------------------------------------------------------------- /6 JavaScript Arrays/12-sorting-arrays.js: -------------------------------------------------------------------------------- 1 | // In programming, sorting is a common operation. 2 | // JavaScript arrays come with a built-in sort method, 3 | // that allows you to easily sort array elements. 4 | 5 | // By default when you call sort on an array containing strings 6 | // or numbers, it sorts the elements in ascending order. 7 | 8 | let characters = ['c', 'd', 'b', 'a']; 9 | characters.sort(); 10 | console.log(characters); 11 | 12 | // Another useful method in the array data structure is .reverse() 13 | // This can be used to reverse the order of the elements. 14 | characters.reverse(); 15 | console.log(characters); 16 | 17 | // When you have an array of objects, you need to provide a callback function to the sort method. 18 | // This function defines the sorting logic based on the properties of the object in the array. 19 | let employees = [ 20 | { id: 1, name: 'Jen' }, 21 | { id: 2, name: 'Steven' }, 22 | { id: 3, name: 'Andrew' }, 23 | { id: 4, name: 'Terry' }, 24 | ]; 25 | 26 | // So since we are sorting reference types, we need to pass a callback function for the .sort() method. 27 | // This callback function will accept two parameters which will represent two elements in this case. 28 | // For the callback function, consider the two parameters, obj1 and obj2. 29 | 30 | // If the result is a negative number, then obj1 would come before obj2 in the final sorted array. 31 | // If the result is 0 then obj1 is equal to obj2 and no need to swap any elements. 32 | // If the result is a positve number, then obj1 would come after obj2 in the final sorted array. 33 | 34 | employees.sort((a, b) => { 35 | // Characters are represented internally as numbers in computers based on their ASCII values. 36 | // So capital letters are considered less than lowercase letters. 37 | // Therefore, we want to make the strings all the same case. (case insensitive) 38 | 39 | const lowercaseA = a.name.toLowerCase(); 40 | const lowercaseB = b.name.toLowerCase(); 41 | 42 | if (lowercaseA < lowercaseB) return -1; 43 | if (lowercaseA > lowercaseB) return 1; 44 | return 0; 45 | }); 46 | 47 | console.log(employees); -------------------------------------------------------------------------------- /7 JavaScript Functions/10-the-this-keyword.js: -------------------------------------------------------------------------------- 1 | // The 'this' keyword is crucial because it refers to the object 2 | // that is currently executing the function or method. 3 | 4 | // The value of 'this' depends on the context in which a function 5 | // is called, not where it's declared. 6 | 7 | const course = { 8 | name: 'JavaScript for Beginners', 9 | start() { 10 | console.log(this.name); 11 | } 12 | } 13 | 14 | course.start(); 15 | 16 | // In a function, (meaning not a method defined for an object) 17 | // the this keyword will reference the global object. 18 | // In browsers it's the window object and in Node.js it's the global object. 19 | 20 | function startVideo() { 21 | // This outputs the global object in Node.js 22 | // This would output the window object in web browsers 23 | console.log(this); 24 | } 25 | 26 | // Arrow functions don't have their own 'this' context. 27 | // Instead they inherit this from their parent scope at the time they are defined. 28 | 29 | const newCourse = { 30 | name: 'ES6 syntax', 31 | start: () => { 32 | console.log(this.name); 33 | } 34 | }; 35 | 36 | course.start(); // the output is undefined 37 | 38 | // This is because when using arrow functions, 39 | // the 'this' keyword inherits from its parents scope. 40 | // So in this case, it would be the global object (in Node.js) 41 | 42 | // Since the global object doesn't have a name property, 43 | // then this value will be undefined. 44 | 45 | // You can explicitly set the value of 'this' using bind. 46 | // So bind returns a new function with it bound to a specific object, 47 | // but doesn't immediately invoke it. 48 | 49 | function introduce(language) { 50 | console.log(this.name + ' teaches ' + language); 51 | } 52 | 53 | const instructor = { name: 'Steven' }; 54 | const introduction = introduce.bind(instructor); 55 | 56 | introduction('JavaScript'); // the output is 'Steven teaches JavaScript' 57 | 58 | // So the 'this' keyword in JavaScript plays a critical role in 59 | // determining the context of function execution. 60 | // Its value is determined by the execution context 61 | // or explicitly bound using bind. -------------------------------------------------------------------------------- /3 JavaScript Operators/7-logical-operators.js: -------------------------------------------------------------------------------- 1 | // We use logical operators to make decisions based on multiple conditions. 2 | // There are 4 logical operators which include: 3 | // || (or operator) 4 | // && (and operator) 5 | // ! (not operator) 6 | // ?? (null coalesing) 7 | 8 | // These can be applied to values of any type, not just boolean values. 9 | // Expressions are evaluated from left to right. 10 | 11 | // Consider the four possible logical combinations that can be made when working with two operands. 12 | // So as long as one is true, then it will return true. 13 | console.log(true || true); // true 14 | console.log(true || false); // true 15 | console.log(false || true); // true 16 | console.log(false || false); // false 17 | 18 | // An example of the ||, or operator 19 | let hasReservation = true; 20 | let acceptingWalkIns = false; 21 | const hasAccessToTable = hasReservation || acceptingWalkIns; 22 | 23 | console.log('hasAccessToTable', hasAccessToTable); 24 | 25 | // &&, the AND operator 26 | // This returns true if all the operands being evaluated are truthy. 27 | // Consider the four possible logical combinations that can be made when working with two operands. 28 | console.log(true && true); // true 29 | console.log(true && false); // false 30 | console.log(false && true); // false 31 | console.log(false && false); // false 32 | 33 | let age = 16; 34 | let hasCar = true; 35 | const canDrive = age >= 16 && hasCar; 36 | 37 | console.log('canDrive', canDrive); 38 | 39 | // Another example 40 | let a = true, b = true, c = true, d = true; 41 | 42 | console.log(a && b || c && d); 43 | 44 | // Same as... 45 | console.log((a && b) || (c && d)); 46 | 47 | // !, the NOT operator 48 | // This will return the inverse of the operand. 49 | console.log(!true); // false 50 | 51 | // Another example 52 | let isClosedOnSunday = true; 53 | 54 | const isRestaurantOpen = !isClosedOnSunday; 55 | 56 | console.log(isReservaationOpen); 57 | 58 | // ??, nullish coalescing operator 59 | // So if a value is null or undefined, then we can supply a default value. 60 | 61 | let doesValueExist = null; 62 | const result = doesValueExist ?? false; 63 | 64 | // So the ?? operator is syntactic sugar for... 65 | const resultOfExpression = (a !== null && a !== undefined) ? a : false; -------------------------------------------------------------------------------- /2 JavaScript Variables/3-primitive-types.js: -------------------------------------------------------------------------------- 1 | // In JavaScript, data can belong to two different categories. 2 | // Primitive value types or Reference types. 3 | 4 | // Primitive types refer to simple, fundamental data. 5 | 6 | // The 8 data types in JavaScript are 7 | // string, number, BigInt, boolean, undefined, null, Symbol, and object. 8 | 9 | // There are 3 ways to create a string literal. 10 | 11 | // Initialize a string with single quotes 12 | let favoriteFruit = 'strawberries'; 13 | 14 | // Initialize a string with double quotes 15 | let favoriteIceCream = "chocolate"; 16 | 17 | // Initialize a string with backticks, ``. 18 | // This creates a template literal which can be used for string interpolation. 19 | let favoriteProgrammingLanguage = `JavaScript`; 20 | 21 | // Assign to a number 22 | let numberOfDonuts = 12; 23 | 24 | // In JavaScript, the number data type, encompasses both integers and decimal values. 25 | let pi = 3.14; 26 | 27 | // BigInt, ends with the character n, and this is for very large numeric values 28 | let veryLargeNumber = 54389759347634976346n; 29 | 30 | // The boolean data type holds the value of true or false. 31 | let lovesCoding = true; 32 | 33 | // undefined is the default value of a variable if we do not assign it. 34 | let favoriteColor; 35 | 36 | // Outputting it will display undefined 37 | console.log(favoriteColor); 38 | 39 | // The null data type, means value unknown or empty. 40 | favoriteFruit = null; 41 | 42 | // The Symbol data type, is used to create unique identifiers for objects 43 | 44 | // The object data type, is known as a reference data type. 45 | // So primitive values can only contain a single thing, such as a number or a string. 46 | // But objects can have more complex structures and hold key-value pairs. 47 | let course = { 48 | name: 'JavaScript for Beginners', 49 | hours: 3 50 | }; 51 | 52 | // Also have the typeof operator, which will return the type of the operand 53 | // The operand will be either a variable or a literal value. 54 | 55 | console.log(typeof 3); // this will output, 'number' 56 | 57 | console.log(typeof favoriteFruit); // this will output, 'string' 58 | 59 | console.log(typeof 109234532525n); // this wil output, 'bigint' 60 | 61 | console.log(typeof 'taco'); // this will output, 'string' 62 | 63 | console.log(typeof null); // this will output, 'object' 64 | 65 | // null, is not actually an object. 66 | // This is from the early days of JavaScript, 67 | // and it returns the value of 'object' for backwards compatibility -------------------------------------------------------------------------------- /4 Control Flow/9-break-and-continue.js: -------------------------------------------------------------------------------- 1 | // In loops, there may be specific conditions where you will want to terminate the loop. 2 | // This is where you would use the break statement. 3 | 4 | // There may also be times when you want to skip to the next iteration of the loop, 5 | // which is where you would use the continue statement. 6 | 7 | // Starting with the break keyword 8 | 9 | // break statement in the for loop 10 | for (let i = 0; i < 10; i++) { 11 | if (i === 5) 12 | break; 13 | 14 | console.log(i); 15 | } 16 | 17 | // break statement in the while loop 18 | let i = 0; 19 | while (i < 10) { 20 | if (i === 5) 21 | break; 22 | 23 | console.log(i); 24 | 25 | i++; 26 | } 27 | 28 | // break statement in the do-while loop 29 | let doWhileIdx = 0; 30 | do { 31 | if (doWhileIdx === 5) 32 | break; 33 | 34 | console.log(doWhileIdx); 35 | 36 | doWhileIdx++; 37 | } while (doWhileIdx < 10); 38 | 39 | // break statement in the for-in loop 40 | let object = { a: 1, b: 2, c: 3 }; 41 | for (const key in object) { 42 | if (key === 'b') break; 43 | 44 | console.log(object[key]); 45 | } 46 | 47 | // break statement in the for-of loop 48 | const array = [1, 2, 3, 4, 5]; 49 | for (let element of array) { 50 | if (element === 3) break; 51 | 52 | console.log(array[element]); 53 | } 54 | 55 | // Now let us consider the continue keyword 56 | 57 | // continue statement in the for loop 58 | for (let i = 0; i < 10; i++) { 59 | if (i % 2 === 0) 60 | continue; 61 | 62 | console.log(i); 63 | } 64 | 65 | // continue statement in the while loop 66 | let whileLoopIdx = 0; 67 | while (whileLoopIdx < 10) { 68 | if (whileLoopIdx % 2 === 0) 69 | continue; 70 | 71 | console.log(whileLoopIdx); 72 | 73 | whileLoopIdx++; 74 | } 75 | 76 | // continue statement in the do-while loop 77 | doWhileIdx = 0; 78 | do { 79 | if (doWhileIdx % 2 === 0) 80 | continue; 81 | 82 | console.log(doWhileIdx); 83 | 84 | doWhileIdx++; 85 | } while (doWhileIdx < 10); 86 | 87 | // continue statement in the for-in loop 88 | object = { a: 1, b: 2, c: 3, d: 4 }; 89 | 90 | for (const key in object) { 91 | if (object[key] % 2 === 0) continue; 92 | 93 | console.log(object[key]); 94 | } 95 | 96 | // continue statement in the for-of loop 97 | for (let element of array) { 98 | if (element % 2 === 0) continue; 99 | 100 | console.log(array[element]); 101 | } --------------------------------------------------------------------------------