learn JavaScript this course is designed to take beginners through the basics of JavaScript with clear explanations and quiz sections while we already have a lot of JavaScript courses on our Channel Stephen is an excellent teacher so we wanted to bring this course to our community welcome to JavaScript for beginners in this course you're going to dive into the essentials of the most widely used programming language in the world design with beginners in mind this course is segmented into seven comprehensive sections after finishing this course you have the skills needed to tackle Advanced courses and move closer to a career in Tech section one We Begin by exploring what JavaScript is and why it's a great first programming language to learn I'll then guide you through setting up your development environment and take the first steps into writing software in section two you'll learn about JavaScript variables the fundamental building blocks of storing and structuring data section three introduces you to the symbols and operators essential for performing calculations modifying data and executing logical operations dive into the power of programming as we cover control flow to learn how to direct your programs using loops and conditional statements making your code more dynamic and interactive objects are crucial in objectoriented programming for creating modern applications this section demystifies JavaScript objects and their role in developing applications learn about arrays a pivotal data structure in JavaScript will explore commonly used methods to manipulate and utilize arrays effectively we'll wrap up with functions enabling you to write clean reusable code that can simplify complex tasks start your coding Journey with JavaScript for beginners on Steven ccraft what is Javascript JavaScript stands as the most popular programming language in the world isessential for frontend web development it Powers the interactivity on websites but it's c abilities extend far beyond JavaScript can also craft backend Services desktop apps and even mobile applications let's break down a modern website it's built using HTML CSS and JavaScript HTML lays the foundation structuring the web page CSS steps in to style and design the structure adding colors layouts and fonts then JavaScript brings it all to life it makes websites interactive in real time like when you like a post or scroll through a feed all without reloading the page a common misconception is that JavaScript and Java are related in reality they're very different languages and serve distinct purposes Java often Powers large Enterprise backends while JavaScript is the go-to for front-end Development Across all companies this makes JavaScript and essential skill for web developers the core programming principles you learn here aren't just limited to JavaScript they're transferable to other languages too despite javascript's unique aspects it's an excellent starting point for beginners it's Dynamic powerful yet easier to grasp compared to other more verose languages like C or Java by mastering JavaScript you're not only learning an in demand programming language but also grasping the foundational coding Concepts applicable across software development [Music] to start programming JavaScript there are two essential tools you need to install node.js and visual studio code so what is no. JS this is a powerful runtime environment that lets you run JavaScript outside the confines of a web browser it's what enables you to build and run JavaScript applications on your computer including serers side projects while you could just run JavaScript in your browser for this course we will be using node.js to execute our programs the second tool is Visual Studio code otherwise known as vs code developed by Microsoft this is an integrated development environment or IDE for short and this is where you'll spend most your your time writing testing debugging and running your code it's a versatile desktop application used by developers worldwide and we'll be using it throughout this course both nodejs and visual studio are free and easy to install installing node.js Begin by opening your browser and heading to nodejs.org once you're on the side click to download node.js LTS stands for long-term support downloading this version is recommended for most users because it's the most stable and well supported version of node.js once downloaded open the installer and follow the onscreen instructions the default settings are suitable for most users so you can proceed with them unless you have specific preferences installing Visual Studio code next we'll install our IDE navigate to code. visual studio.com in your web browser click the download button for your operating system vs code is available for Windows Mac and Linux after downloading run the installer like with node.js the default installation options will work perfectly for our purposes so now once you have installed both node.js and visual studio code click to open up vs code after you click it you will see the welcome page then open up finder or File Explorer for your windows and create a new folder now this will be the folder where we place our code so I'll just name it project now the name of the folder doesn't matter then I can click and drag it into vs code this will open up the project now to add a new file to our project I can click on this icon and I can name it code. JS so the name of this file doesn't matter but the file extension does so now we can write our first line of code and I'll say console.log then in single quotes I'll say hello world and then I'll end it with the semi callon notice as I'm typing this file has not been saved yet and so I see a circle indicating that I have unsaved changes so to save it I can do command s or on Windows it would be contrs so now if I want to actually execute this file I can do file appearance and then panel to open up the integrated terminal in vs code now there's also a shortcut I can do control and back tick so if you don't use the back tick character often it's located on the left hand side of your keyboard above the tab key so I can do control and back tick to toggle this open so I'll be using node to execute this program so I'll type node and then the name of our file which is code. Js so here we see this value hello world is logged to the console so I'll close this now vs code offers a lot of features and a lot of ways to customize it before this course we'll just be covering the basics that you need to get started so on the left hand side is the activity bar where we see a list of icons the topmost icon is the folder icon and we can use it to toggle our project to see the folders and files within it next is the search icon and we can use this to search find and replace text so for example let's say if I do hello enter we see that this text is found in our code. JS file so close that the next one is our source code icon and this is used to keep track of the changes in our project as well as collaborate with other developers using get ver control next is the run and debug icon you would use this when setting break points in your code and debugging it if there are errors next is the extensions icon this gives you access to the extensions Marketplace so this enables you to install additional features to VSS code to improve your productivity and help you customize VSS code to your needs now the icons on the bottom is for your account and to adjust your settings now on the bottom of the screen is the status bar here in Blue on the left side you will see any errors or warnings in your code and on the right side I see the line number that I'm on for my current file and I also see the programming language being used so let's say if I wanted to add another file to my project rather than always having to click on this icon I can use a keyboard shortcut of command and N or control and n on windows open up a new file and on the bottom right we see that this is identified as plain text so now if I want to save this file as a Javascript file I can do command s and I can name it as second program .js and now on the bottom right we see that VSS code can identify that this is a Javascript file the next thing I want to cover is the command pallet you can access the command pallet by going to view and then command pallet now another way to do that is with the keyboard shortcut of command shift and P or it'll be control shift and P on Windows now the command pallet is very important as it is the control center for all commands in vs code from here we can also adjust the color thing that we use so I click on color theme and as I scroll up and down we can see different color themes for my code editor you can also access additional themes by going to the very top and clicking on browse additional color themes allowing you to search through different options now for this course I'll just stick to the standard Visual Studio One now to make the text larger you can do command and plus or control and plus on Windows and also command minus or control minus in order to make the text smaller so this is a quick overview of VSS code teaching you the basics that you need for this course before we get started if you're interested in supporting my courses and projects you can follow me on my new YouTube channel and Instagram at Steven codecraft and if you're looking to enhance your health and fitness routine check out my workout and meal planning app at fitfuel planner.com the app offers over 100 recipes workout plans meal plans and a grocery list feature it's designed to make tracking your calories and macronutrients straightforward and stressfree I appreciate your support and I'll see you in the next section with the vs code open let's start our first program we will start by creating a new file by clicking the icon on the left Explorer and we can name this file whatever we want I'm going to name it variables and I'm use the file extension of JS for a Javas file so in JavaScript our applications need to work with information such as an online shop where the information might be the product sold or info about the user variables are used to store this information in programming we would refer to this information as data in our applications we create read update and delete data we need a way to keep data in memory so that we can perform these operations on it and to do that we use variables a variable is a name storage for data so variable store data temporarily in a computer's memory and under the hood it will be stored in a memory location and we can access that data stored by the variable name then we give it so to declare a variable the old way of doing it was using the VAR keyword I'll show you an example of that we use the VAR keyword now we name the variable I'll use the name first name and then I will assign it to data so I assign it to the word being my first name and I use single quotes in order to tell JavaScript that this is a string a string of characters so programmers we refer to words as strings we could also use double quotes and both work fine in JavaScript Now using the VAR keyword is the old way of doing it now the modern way of doing it is to use the let keyword in order to initialize this value I'll talk about the differences of these conventions later in the course after you're comfortable with the basics so this statement here that I highlighted is known as initialization know that we could also declare this variable and assign it on two different lines I'll show you an example of that and then we do first name and assign to our value so this first statement which I have highlighted is the Declaration I'm declaring a variable then I'm am assigning it on the second line note that on the second line I did not have to use the let keyword again I only have to do it once when I first create it not that the single equal sign is known as the assignment operator and that's the operator I use to connect data to the variable I have declared know that there are some reserved words that I cannot use as my variable name I'll show you an example of that so we use our let keyword to create our variable and I'm going to name it function which is a reserved keyword then I will assign it to a string saying test so here VSS code indicates with these underlines this variable name is not allowed that's another benefit of using vs code because we can catch errors early on in our development so let me delete this so note when I declare this variable right just declaring it again I use camel case notation for my variable name and this helps with readability and it's a common convention in JavaScript so what you do is the first word that you use for your variable you will have that in all lowercase and then any proceeding words you will start the first letter uppercase and the rest of that word in lower case and this allows you to have descriptive variable names that are easy to to read as opposed to if I were to do something like this which is just less readable okay we can also declare multiple variables on the same line so here if I instead of doing the semicolon I use last name and assign it to my last name and end the statement with a semicolon semicolons tell JavaScript that this is the end of the line but this becomes hard to read especially when working with larger programs so we prefer to put every initialization on its own line so a real life analogy let's say we have let message and we sign up to the string hello how does look like visually so to grasp this visually consider this first screenshot so you can think of our variable as a box that's the amount of memory that JavaScript has allocated for us to grasp this concept visually consider this diagram we declare a variable which we imagine as a box for data and this box has a sticker with the word message on it which is the name of our variable then we store the value hello in it we could also change the variable as many times as we like let's say if I do message and I assign it to world ending with the semicolon well visually to grasp this so the previous string which I had as hello will be Gage collected by JavaScript and that new string that we assigned it to will be stored in the memory location so in order to run this program and to log it to the console we can use a built-in function in JavaScript known as console.log I'll do console.log and I'll pass in the name of my variable message ending it with a semicolon now to actually run this program I'll open up the panel you can open up the panel in vs code by doing control and back tick as the keyboard shortcut or I close that you can go view appearance and then panel to open it up so here in order to view what files I have in my project I can do LS and that's list out the files in my folder also known as my directory and here I see variables. JS which is the file I want to execute I'm going to execute this with node so I type in node variables. js and here I see the value of my variable logged out to the console let's take a short quiz to test what you learned this part is essential to ensure that you retain the information what is a variable a variable is a named storage for data how do you declare a variable you declare a variable with the let keyword in JavaScript we use the let keyword for variables which hold a value that can be changed to declare a variable which has a constant value which can't be changed we would use the const keyword an example of this would be const I name it Christmas 2024 and I assign that to the string say 12.25 2024 ending it with a semicolon so when a programmer ass sure that a variable will never change they can declare it with const to guarantee and communicate that fact to everyone here if I log it out console.log Christmas 2024 opening up the panel I can say node variables. js and here I see that output it now with the cons keyword if I were to try to reassign it and un log it out JavaScript would display an error so let's say before outputting it let's say if I did Christmas 2024 and I assign that to 12262 24 when I try running that it will display an error so if I go up and run it so here it is an error saying that I cannot assign to a constant variable so another convention I'm doing constants is to use all uppercase Den notate that this is a constant value here I will use all values where each word is all uppercase and separated by underscore rather than using camel case now the use of this is not required and it depends on the convention of your team one thing I want you to take away from the first two videos of the section is that I have been using descriptive names for my variables this helps me write code that other people can easily understand now I could have named this variable as const n equals green but other programmers do not have context of what I initialize this constant value so always use descriptive names for your variables what is the purpose of a constant the purpose of a constant is to Define data that cannot be changed what is the difference between a constant and a variable a variable defines data that can be changed and reassigned later in the program whereas a constant defines data that cannot be changed in JavaScript the data that we use can belong to either two categories primitive value types and reference types there are eight basic data types in JavaScript primitive types refer to simple fundamental data examples include string number big int Boolean undefined null and symbol the reference data type is the object data type don't worry about memorizing this right now just focus on understanding and it will become second nature over time so let me show an example of each of these so I can initialize strings three different ways I can say let favorite fruit I'll sign it to strawberries using single quotes then I'll create a string and I initialize it with double quotes sign that to chocolate then I can use back ticks which will create a template literal so I can say let favorite programming language assign to JavaScript now these are the three different ways that we can initialize a string data type now we can cover numbers let's say if I do let number of donuts I'm that to 12 now numbers Encompass both integer values and decimal values so if I say let Pi then I can sign that to 3.14 let's say if I do let very large number type out a large number and then end it with the character n not a shown example of a Boolean data type which stores the value of either true or false I can say let loves coding assign that to the value of true now the undefined data type this means that a value is not assigned to a variable so if I just declare a variable let's say if I do let favorite color then by default it will be assigned the value of undefined so if I console lck that I'll see the value of undefined favorite color opening up the panel and then running it up arrow and run here I see its value is undefined now for the data type null we use null and we want to explicitly clear the value of a variable so if I do favorite fruit I can assign that to null we also have symbols which are used to create unique identifiers and objects so if I can do cons and I'll say unique key for example assign that to symbol and then open and closing parentheses now the last data type is a reference data type that is an object so an object is known as a reference type primitive values can only contain a single thing whether it be a number or a string objects can have a more complex structure and they hold key value pairs this enables us to store more than one variable all in one so for example I can say let course assign that to opening and closing curly braces so this defines an object literal and I can define a key so I'll say name set that to JavaScript for beginners comma and then I can Define another key ours with the value of three and I can end it with a semicolon so objects enable me to create more complex structures now we can use the type of operator in JavaScript in order to return the type of the operand and the operand could be either a variable or a value so if I open up the panel if I just type node so when we use the type of operator then it will return the data type as a string so if I do undefine here we see undefined returned as a string now if I do type of zero we see that data type is a number now we'll try for a big int if I do type of 10n we get big int let have I do type of Taco we'll get a string let's do type of assemble now for the last example I'll say type of null so the result of type of for null is an object note that null isn't actually an object the type of output for null being an object is from the early days of JavaScript and it has remained for backwards compatibility so to quickly recap there are eight basic data types in JavaScript of those eight seven of them are primma data types which include number big int string Boolean null undefined and symbol and for nonpr data types we have the object data type which is a more complex data structure what are primitive data types in JavaScript primitive data types refer to fundamental values these values can only contain a single thing whether it be a string number or Boolean what are the seven primitive data types in JavaScript the seven primitive data types are string number Boolean big in undefined null and symbol programming languages that allow you to initialize a variable to a data type and then reassign it to a different data type are known as dynamically typed in other languages such as C or Java you specify the data type that you want to use and cannot reassign it to a different data type JavaScript is dynamically typed so a variable is not bound to only being assigned to one type so to show an example of this fin initialize let first name and assign it to the string of Steven then I can reassign it to a number say if I assign it to the value of 100 then I can reassign it to a Boolean so here we see that we can assign any data type value to our variable since it is dynamic the type of our variable can change at runtime here if I were to console Lo the types and do console.log type of first name I'll add some spacing and I'll copy and paste some here so output it node variables .js so here I see the different data types based on what I assigned it to be now in a professional setting you can see how this could potentially cause bugs and our application if someone were to assign it to a data type that doesn't make sense so we need to be careful of that and in professional settings you would often use a version of JavaScript known as typescript which is a statically typed version of JavaScript with enhanced [Music] features what is dynamic typing in JavaScript Dynamic typing refers to the ability to initialize a variable to one data type for example a string and to assign it to any other data type whether it be a number a Boolean or an object objects are reference types in JavaScript objects are used to represent an object or noun in real life it contains State and behavior enabling us to group together related values and make our code cleaner object literal syntax uses curly braces so if I initialize an object I'll say let course assign to curly braces then I can specify a key I'll name it name with the value of JavaScript for beginners so name is referred to as a key and this string is referred to as a value now I can add more key value pairs by adding a comma and then specify ours and then I'll say three end it with the semicolon now we can console log this object console.log course opening up the panel node variables. js and here this outputs the object so the key value pair when considered together is referred to as a property of the object and all the keys are represented internally as a string so in order to access these properties we can do so through two different notations the most common notation is dot notation so after course I can say dot name and this will output the associated value for this key so if I run it again here I see outputed the associated value we could also reassign a property if I say course. name and assign to JavaScript fundamentals ending it with the semicolon now if I copy this and paste again I see that it has updated that value clear the panel and then run again so here I see the associated value has been changed now we can also access these properties using bracket notation so I comment this out then if I do console.log of course then square brackets and then specify the key as a string so I'll say name and then I'll output it so this is a different syntax to accomplish the same thing I could also use bracket notation to update the value so if I do course name and assign it to JavaScript 101 then I output it again and this displays the updated value so which approach is better do notation is more commonly used however you would use bracket notation in the case when you don't know which Target property you want to access until runtime here if I comment this out so to show an example of this I'll initialize a variable let property and assign it to hours then I'll do console.log the name of the object which is course and using bracket notation I will use this variable as the key and this will output the associated value for the key of ours when I run in the panel it output the associated value what is an object in JavaScript an object is a fundamental data type in JavaScript that allows you to store key value pairs you can use the object literal syntax by using curly braces and Define the key value pairs inside of it are objects a reference type or a primitive type objects are a reference type PR type refer to values that hold a singular value such as a string number or Boolean whereas objects are more complex data type that allow you to store multiple key value [Music] pairs objects allow you to store key value pairs but often we need an order collection where we have a first element second element and so on this data could be a list of products to display on a web page arrays are used to store lists of data we would use square brackets to create an array literal for example we can do let product colors and we use the square bracket notation and here I we just store some strings ending it with the semicolon and so here I'll just console log it product colors opening up the panel and here it see it logs out the array our list of data now if we just want to access one element in our list we can do so through bracket notation and access it by the index so an interesting about arrays is that we begin counting from zero so rather than counting the first element as the first element we say that this is at the zero position and then one and so on so here if I log it out here I see a logged out blue for the first element in our array at the zero index so the type of variables of each element can change at runtime in JavaScript you can have different data types in an array to demonstrate that so before I call log let's say if I do product colors at the index at zero and I assign that to 42 log that out here I see I logged out the number value of 42 however in a rowo project you would keep the data types the same this is just to demonstrate the flexibility of JavaScript note that an array is an object objects have key value pairs in this case the key is an index value so here if I were to log out the type of let's do console. log type of product colors opening up the panel again our terminal let's log it out and we see that the data type is an object a useful property that you often use when working with arrays is the length property product colors. length so just like we know our objects have properties arrays in JavaScript have built-in properties so here I will log it out and we see that there are two elements in our [Music] array what are arrays arrays are a data structure in JavaScript that allow you to store list of data how would you determine the length of an array arrays have a built-in property called length that allows you to find the length of the array how would you access the first element of an array you start counting from the index of zero in order to access the first element you would use square bracket notation to access the element or to change the value of the element function are the building blocks of our applications it allows us to group together statements to perform a task or calculate a value show you an example we will use the function keyword and we can name our function using camel case we use these parentheses to den notate any argument values we can pass in and I can do console. log end with a semicolon note that we don't need a semicolon at the end of this curly brace and then to actually have JavaScript execute that code for us I can do say Hi and then call by passing in the parentheses here open up the panel and execute this code I see that executed the code within the curly braces we can also Define a parameter variable so here if I add in name I can name this whatever I want then to actually output it or to actually utilize that I can do a plus sign and add in the name of the variable so when working with strings and using a plus sign this is known as string concatenation so it would combine these together create a new string so since I've defined this parameter variable here I need to supply an argument when calling it so here I'll just pass in my name save and open up the panel so once again it's view appearance and then panel flare that out and then run it again and here I see it outputed the argument that I passed in to that parameter variable so here we see there is not a space and so let me add that in here I add the space before this closing single quote and let's run it again [Music] what is a function a function in JavaScript is a name piece of code we use the function keyword and then we can name the function whatever we want after we use parentheses and then curly braces within those curly braces we Define statements and we can invoke or call that function in order to execute those statements benefit is allows us to quickly and efficiently execute those statements without having to duplicate our code what is a parameter variable when defining our functions we specify a parameter list within the parentheses when calling our function we can pass in values and that will allow us to customize the execution of our function so we know that functions are a building block on our programs they enable us to group together a block of code which is a set of statements defined within curly braces one thing I want to to clarify is the purpose of functions we create a function for one of two options the first is to perform some action and the second is to calculate and return some value so not all functions require us to explicitly use the return keyword by default if we don't Supply an explicit return value then JavaScript will have the function return the value undefined I'll show you an example of that so if I declare a function I'll name it multiply and I'll specify two parameters num one and num two then the curly braces to Define our code block and then I will return the product of num one * num 2 so now if I were to call or invoke that function I can say console.log to Output it result and then I will call it I'll say multiply passing in 2 * 2 save it open up the panel up arrow and run it and here I see the result of four was outputed now if I did not use this return keyword and if I were instead for example to store it in a variable const product is assigned to this operation then JavaScript will return the value of undefined by default since I did not supply an explicit return keyword so if I run it again here I see the return value multiply was undefined what are the two reasons to create a function you would create a function either for it to perform an action or to calculate a value and return that value let's summarize what we covered in this section if this is your first time learning this I don't expect you to memorize everything from the start with contined practice you will pick it up and it will become second nature be sure to view the GitHub repository associated with this project and review the project files related to the section so variables are used to store temporary data data can be categorized into eight different data types of these eight data types seven of them are considered primitive data types they are called primitive data types because they are singular values or simple values these primitive data types are strings numbers booleans null undefined big int and symbol and the eighth data type are object objects are key value Pairs and they are not a primitive data type because they are a more complex data type and don't just store a singular value there's also a built-in data structure called arrays which stores list of data which is one of the most used structures that you will use as a developer we also covered functions so rather than having to copy and paste code and duplicate it we can simply name a block of code which is just a group of statements great job on completing the section and with that I'll see you in the next section in JavaScript we can operate on our variables by using operators these include arithmetic assignment comparison logical and bitwise operators which serve as fundamental building blocks for our applications we'll be diving into each of these in the section an expression in JavaScript is something that produces a value an expression goes on the right side of our variable assignment so in JavaScript we have different mathematical operators which include subtraction action addition multiplication represented with an ASC sign division represented by a for Slash and the modulo operator so modulo is the remainder of division and it's useful as it helps us determine whether a number is even or odd so let's open up the panel and type node and enter so now that we're in interactive mode we'll go through different examples so if I do 2 + 2 that results in four likewise if I do 4 minus 2 we get the result of that so an example of multiplication an example of division with the for slash symbol we get two now an example of the modu operator let's say if I were to do 10 modul 2 so what this says is 10 / 2 and it will return what the remainder is so return zero so we know that this is an even number likewise if I did an odd number / two then we get the remainder of one we could also raise to the power of let's say if I do 3 raised the Power of Two And that results in 9 now we also have the increment and decrement operators so if I initialize let a is assigned to 10 now if I want to update this value I can say a is equal to a + 1 now JavaScript provides a shorter syntax where we can use syntactic sugar and say A Plus equal 1 which accomplishes the same thing now we can do it even shorter we can do a plus plus and this will increment the value we could also increment by doing Plus+ a now the difference is the following when I have the two plus operators after the variable it will return the current value stored at the variable a and then it will increment it after if I have the two plus operators before the variable then it will increment the value then it will return that updated value the same functionality also applies for decrementing the value I demonstrate that such as a - equal 1 or I can do a - minus or- - A [Music] what arithmetic operators are available in JavaScript arithmetic operators are symbols used in programming languages including JavaScript to perform common mathematical operations on numbers these include addition subtraction multiplication division modulus increment decrement and exponentiation if I declared let num assigned to one how would I increment it there are four ways to increment a number in JavaScript you can do num is assigned to num plus one or you can use the Shand of num plus equals 1 or the syntactic sugar of num Plus+ or you can do the incrementing before the variable name you are familiar with the assignment operator being a single equal sign such as let programming language assign to JavaScript the single equal sign does not actually check for equality in JavaScript it's an important distinction that stands for assignment as in assigning a value to a variable later in this section I will show you how we can check if two variables or two values are equal in [Music] JavaScript what does the single equal sign stand for in JavaScript the single equal sign stands for the assignment operator and we use it to assign a value to a variable when Del with numbers we often use comparison operators these comparison operators include greater than greater than or equal to less than and less than equal to the result of using comparison operators in an expression is a Boolean value so it will result in either true or false I'll show you an example of each of these and it will make more sense so I'm to deare this variable I'll say let num one is assigned to 14 and I'll say let num two is assigned to 10 then I'll declare a constant I'll call it is num one greater and I'll assign that to num one and then greater than num two so what I have highlighted here is the expression and this will result in a bullan value so a true or false value that will be stored in this variable so I'll log it out console.log is num one greater and let's log it out so in the panel I'll say node control flow and I see that is true so it results in a bullan value so let's consider the other scenarios I'll just rename this variable to make it more descriptive I'll say is greater than or equal to and just copy that over over and I'll change this comparison operator to you be greater than or equal to so open it up and we'll just run it again now I'll show the case when and change this compresson operator to be less than so this is asking is num one less than num two so I'll just rename this to be more descriptive I'll say is num one less than so the actual name of these variables is arbitrary but I do want it to be descriptive for anyone reading this program so this Returns the result false now I'll check if one is less than or equal to num two I'll just change the name of the variable as well so is num one less than or equal to what are the comparison operators in JavaScript the comparison operators are greater than greater than or equal to less than and less than equal [Music] to for checking for equality for two variables we can do so in two different ways so we know that using one equal sign is for the assignment operator here if I just initialize some variables say let B is assigned to two as a string so one equal sign is not for checking the equality so to see if two values are equal we can do so through two equal signs so here if I do console. log AAL B so this is known as loose equality when using two equal signs cuz here I'm comparing a number and a string so let's output this to see the result so this results in true the reason why is because this evaluates in JavaScript what is known as truthy so let me show you the other way of doing comparison which is with strict equality so I would do console.log a equal to B so using three equal signs is strict equality for the first time when doing loose equality it converts into a string by converting to the same data type and then comparing the values restrict quality it Compares it as is without doing any conversions so I'll output it so when doing loose equality it evaluates to true and the reason is because these are two different data types we are comparing a number data type and a string data type to show you another example of how JavaScript converts values with loose equality I'll show you one equal to one represented as a string and so even that these values are different data types JavaScript will convert it for us so it will evaluate to True let's comment these previous ones out here comment that out and comment that one out so once I output it here I see it evaluates the true likewise if I were to do true equal to one JavaScript will convert these into Boolean values before performing the comparison with loose equality all right so in order to avoid this confusion stick to strict equality and use three equal [Music] signs what is the assignment operator the assignment operator in JavaScript refers to using a single equal sign in order to assign a value to a variable what is loose equality loose equality in JavaScript refers to the comparison of two values using two equal signs without enforcing type similarity when using Luci equ quality JavaScript performs type coercion if the values being compared are of different data types attempting to convert them to a comparable form before making the comparison this process known as type coercion can lead to unexpected results if you're not aware of how the values are converted these three examples show how JavaScript would perform loose equality what is strict equality strict equality refers to using three equal signs for checking for equality this will return true if the values are equal and of the same data type in JavaScript we have something called a Turner operator so the Turner operator is a conditional operator that allows us to write cleaner code often times you need to perform a comparison and store values let's go into an example say let age is equal to 16 and I want to determine if I can drive so I form a comparison so age greater than equal to 16 well in that case I can use a question mark and then true or false so let's break this down highlighted I have the comparison comparing the value at this variable and this number so this question mark is the turn operator which means that if this results to true then it will return true otherwise return false let me console log it console. log can drive opening up the panel panel is control and back or view appearance panel so up Arrow execute it and we know that it's true so now I will comment this out since we no longer need it for now and I'll fig another example let's say let points points is equal to 110 and the output of to determine what the customer type is so points is greater than 100 then in that case we determine gold in the case when it's true or silver in the case when it's false so output it console.log customer type so what this does this allows us to perform an assignment to the customer type variable that we declared conditionally based on the result of this comparison so once again I'll output it note and we see that the customer is a gold customer type what is the tary operator the Turner operator is a way to conditionally assign a value to a variable you would use a conditional expression followed by a question mark if that conditional expression is evaluated the truthy then you'll use the value that follows just after the question mark otherwise you'll use the value following the colon which is specified at the end what is the value stored in the variable customer type the value stored will be the string containing the word gold we use logical operators to make decisions based on multiple conditions there are four logical operators The Logical operators are the or operator the and operator not and no coalescing these can be applied to values of any type not just bulling starting with the or operator which is represented by two vertical lines so there are four possible logical combinations and I'll show you each a console log true and use the logical or operator represented by two vertical lines in this case I'll just do true so what this expression does the expression I've highlighted true and true as long as one of the operands is true then it will return true so I'll just lock that out n operator .js so we know that the other option is if the first is false and this value is true so in this case we know that as long as one is true then it will return the value as expected right so we know that now if the first is true and this is false same result as expected then we log that out and the last option will be when they are both false pull out the panel and run it one more more time so so long as one of the operand is true and the expression will evaluate as expected if operand is not a Boolean value then it'll be converted to a Boolean value for the evaluation for example the number one is treated as true and the number zero as false so the or operator is evaluated from left to right and for each operand converts it to a Boolean and once it finds an operand that resolves to true it stops and Returns the original value of that op and if all operand have been evaluated to false then it Returns the last operant and the value is return in its original form without the conversion to a boan value now to show you another example we say let has reservation I'll close the panel assign that to true then I'll say let accepting Walkins and assign it to false if it has access to table has reservation or accepting Walkins plog that out opening the panel or run it and see it evaluates the true now let's consider the and operator so and returns true if all the operand are truthy and false otherwise I'll show you all possible combinations true true so you know that's true and I'll just copy it the other four times for the other cases now all other cases will be false so have false and true true and false and false and true run in the panel node operators. js and here we see as expected so this operator valuates from left to right and once again it converts each operand to a Boolean if it is not already a bullan type and once it discovers one of the operand to be false then it stops execution which is known as short circuit evaluation so to show you a more rward example I say let H is equal 16 I can say let has car equals true let's say cons can drive age is greater than equal to 16 and as car and let's log that out here it evaluates to true so that the Precedence of the and operator higher than the or operator so just to give you a visual of that console.log a let's just make it let a equal true and b equal true and c equal true and D equal true then if I were to write this expression and can say A and B or C and D then this value up here is actually the same as this as if you were to write parentheses just to show that using the ersan holds higher precedence and is evaluated first before the or Operator just to demonstrate that next is the Boolean not operator represented by exclamation point so it converts the operan to a Boolean type true or false and it Returns the inverse value so let's just say if I to do console.log of true then whatever this current value is it will return the inverse it will return false in this case here we know it evaluates defaults so let's say if I were to do let is closed on Sunday if find true then I can say cons is restaurant open to this close on Sunday then I can console log it then I can run it and here we see it is Returns the inverse of this value so let's close that so the last operator is the nullish coalescing operator represented by two question marks if a value is nuller undefined then we can supply a default value show you an example of that let's say let a let's just assign it to and we want to determine what the result is so if a is truthy right so in this case it is not so we need to apply a default value so we use the no Co Lessing operator here so this being the default value so if I just log it out result and then I'll execute it in the panel I'll do node operators. js and here we see it evaluates default by giv by being given the default value to make better sense of this I'll show you that this is actually syntactic Sugar if we were to do the longer format it would be a not equal to null and a not equal to undefined and then using the Turner operator which is a question mark So this expression this condition is evaluated and if it's true then return a otherwise return false so what we did before is just the shorthand version of this and it provides syntactic sugar and cleaner code and easier to read for [Music] us what are logical operators logical operators in JavaScript are special symbols or keywords used within Expressions to perform logical operations they primarily involve Boolean values however they can be applied to values of any type not just booleans the result of these operations is to determine the logical relationship between the operant typically resulting in a Boolean value that indicates the truthiness or fals of the combined expression what are the four main logical operators in [Music] JavaScript the form operators are the and operator the or operator the not operator and no coalescing operator what is this operator and how does it [Music] work this operator represented by two vertical lines is the or operator it Compares two operands or two values and as long as one of them results to true then the expression will return true what is this operator and how does it [Music] work this operator represented by two ampersands is the and operator the way it works is it Compares two values or two operands when both operands results to true then it will return truthy what is this operator and how does it [Music] work this operator represented by the exclamation point is known as the not operator also sometimes called the bang operator so this value Returns the inverse of the operand that is used with for example if the exclamation point is used in front of a variable and that variable is assigned to the value true the exclamation point will have it return the inverse it will return false what is this operator and how does it [Music] work this operator represented by two question marks is the no Co Lessing operator but this does is allows you to supply a default value in case the operand used in front of the question mark is [Music] false JavaScript is different from other programming languages one way that it differs is in its use of logical operators and how they can be applied to nonbing operant I'll pull up the panel you can go to view appearance and the panel so if I write enter node and compare false or the string Steven here we see Steven is returned using the or operator it Returns the first True Value so you see that this string is evaluated to true so in JavaScript the result of a logical expression is not necessarily true or false so it looks at the operan and if it's not a Boolean value it will then try to interpret it as truthy or falsy so in JavaScript something that is falsy which is different from the Boolean false encompasses the values of undefined null zero false the empty string and not a number anything not falsey anything which does not fall in the category that I previously mentioned is considered truthy now to show you another example you can consider false or one or two the result of this is one JavaScript evaluates this from left to right since one is considered truthy then JavaScript can perform shortcircuit evaluation and return immediately this means that JavaScript will stop once it can successfully determine the result and it doesn't have to evaluate every operan so to provide a more World W example let me initialize user chosen color is assigned to Blue and we'll say the default color is green now we can determine what is the current website color so I'll say user chosen color or default color I'll console log it current website color because both of these values are strings JavaScript will convert these to Boolean values and consider whether this is truthy node operators. js and here it evaluates to Blue but if I were to delete blue and it be empty string then JavaScript would evaluate that to be falsy and it will turn the default color what does the term falsy mean in JavaScript so this term applies when you're using logical operators with non- Boolean values since logical operators deal with Boolean values which means values that are true or false if you're using a non- bullan value such as a string or a number JavaScript needs to be able to convert that value into a Boolean value into a true or false value what are the falsy values JavaScript has a set of non-bo values which it considers to be falsy meaning that when javascrip converts these non- Boolean values into Boolean values via type coercion it evaluates to false the falsy values consist of null undefined not a number the empty string zero and false these are the values that JavaScript will consider to be false how do logical operators function when applied to non- Boolean values logical operators are evaluated from left to right if you're using the or operator once JavaScript evaluates an operand to be truthy then it will return that value if you are using the and operator then all the operands need to evaluate the truthy in the case when it's true then it will return the last value in the expression consider the expression let name assigned to the string test and con result equal to false or name what is the value stored in the variable result the value stored will be the string with the word test so operator precedence I'll initialize this variable 5 + 5 * 4 and then I'll console log the result console.log and then n your node operator SS here it evaluates to 25 so previously in JavaScript everything has been evaluated going from left to write for each statement but here when using operators it will use the same order of precedent used in math that being parentheses exponents multiplication division and then subtraction so in order to make this more readable usually we would use parentheses just to make it more readable for other programmers who are viewing our code but JavaScript does this under the hood so I will save it this will return the same result for us but here is just a bit more readable now we could also override that precedence by utilizing parenthesis [Music] to summarize the section on operators we covered the arithmetic operators which include addition subtraction multiplication division and modulo we covered the assignment operator which is used for assigning values to variables we covered the comparison operators which use greater than greater than equal to less than and less than equal to we covered the equality operators such as loose equality which uses two equal signs which will have JavaScript perform type coercion and compare the underly values of the operands irrespective of the data type instead we should use strict equality which uses three equal signs to ensure that we are checking that the values are the same and the data type is the same for the operands that we are comparing we cover the Turner operator which provides syntactic sugar for conditionally assigning a value depending on a condition so if the condition is true use the value specified after the question mark if the condition is false use the value specified after the colon we cover the logic operators which include the or operator with two vertical lines the and operator which uses two ampersands and the not operator which uses an exclamation point this concludes this section and I will see you in the next [Music] one so now rename this file to control flow control flow so programming is powerful as it enables us to execute different code based on conditions this is what enables us to provide Dynamic and personalize applications to end users the fundamental programming concept that enables this is conditional statements more specifically ifal statements so previously we have considered let's say if I already do price of chocolate equal to the number that decimal value and let's say let has amount in cash assigned to five well we can use comparison operators and score the result of this Boolean operation you can say can buy chocolate equal to has Mountain cache and if that is greater than or equal to the price of the product then we know we can determine whether this is true or false I'll just lock it out Lo node control flow. Js and we know that that's true now if I to log out instead the type of this variable and this will determine what the data type is so if I execute that again we know what that is a Boolean result so the result of these comparison operators we know it will be a Boolean result so we can utilize these comparisons and these conditions to execute different code so if I were to utilize an IFL statement I can say if which is a built-in keyword in JavaScript and I can utilize this variable in parenthesis this is known as a condition then I'll do curly braces and with these cemb braces I can write statements that will be executed this condition is true so I can say console.log Enjoy your purchase so now execute this program and we see the string enjoy your purchase now let's say if I were to make this person only had 99 cents in cash then if I would execute it then we see that that is not logged to the console as this is not true it would be false in this case so let's go back to setting the value of five now rather than just logging out in the case when it's true can also log in the case when it's false by using an lse statement which is built into JavaScript and we will log in this case console.log sorry you do not have you know so execute both cases once again we get the result so only this code is executed in this case because this value is evaluated to true now let's go to 099 now we'll see which statement is executed and which is logged in the case when can by chocolate is false so here we see this was locked to the console so to show you a different example and remove that we have two types of conditionals in programming the if Al statement which is used most commonly and we also have switch case statements which I'll be covering in the next lesson so let me consider a more evolved example to show you what else you can do with IFL statements let me initialize and say let hour is assign to 10 for example I want to do different conditions to determine what types of food a restaurant is serving based on the time so let's say if the hour is greater than 6 and the hour is less than or equal to 12 then it would serve breakfast console.log serving breakfast let's log this out so it's currently serving breakfast now we also want to consider the case when it would serve lunch so let's say as if the hour is greater than equal to 12 so say it's greater than 12 and the hour is less than or equal to 14 then in that case we will log console.log serving lunch let's open this up and log it out so let me change this value let's say it's 1:00 then we see that it's serving lunch now in the case when it would be serving dinner let's say else now when we have if else if then the last statement would just be else and in this case we don't need to supply a condition meaning that we don't need to do parentheses here and this will be evaluated as the default case console.log serving dinner so let's make this and we'll log it out so now you see the case of how we can utilize ifal statements to custom the output for the user in the case when we just have one statement within the curly braces now when I have this highlighted this can also be referred to as a code block so when we just have one statement within it we can actually clean it up and remove the curly braces just to make it a bit more readable and cleaner what is the ifal statement control flow and programming refers to the order in which statements are executed in JavaScript control flow structures such as the IFL statement dictate how and under what conditions certain blocks code are executed switch case statements can also be used for control flow the difference between iFile statements and switch case statements is that switch case is only used for equality comparisons so I'll show you an example let's initialize a variable and say let job assigned to the string of software developer now I'll show you an example of the control flow using IF and Al if statements so I'll say if job is equal 2 so I'll use three equal signs for strict equality and then the string software developer I'll do curly braces and in that case I will console.log wres code save that open up the panel and I'll run it so I'll say node control flow. JS in here because this condition is true it executes and console logs that string I'll show some other examples so let's say less if job is equal to a designer curly braces I'll say console.log makes user interface documents end it with the semicolon now if I were to assign this variable to be assigned to designer and I run it again here it executes this console log statement I'll show another example Al if your job is equal to we'll say cloud engineer console log manages and employ Cloud resources right so let's say if I assign this value and I run it again console logs that and I had a default with the last out statement console.log I'll say Works directly with customers I'll just say sales run it and executes this last out statement so so since we are using our ifal conditions to do comparisons with the equality operator this can be a bit hard to read and repetitive when you find yourself having a long chain of if and Al if statements when you're using comparisons for all the conditions you can consider using switch case statements so instead of the code above I'll comment it out by highlighting it and doing command for slash or control for slash on Windows I'll use a syntax where I say switch as the keyword and for the condition in the parentheses I will specify the variable then what I do is I will use the keyword case so in the case when it's equal to software developer colon then I'll will console lck this statement and then use a keyword break with the semicolon to end the comparison then I'll say in the case when it's a designer colon then I'll copy this over so I'm effectively implementing the same functionality just using different syntax that's easier to read copy this over with a break statement and then I'll add a default so this is another way to achieve that same functionality now the reason why we use the break statement is that what the switch case statement would do is it will take this variable and it will compare it to every single case and in the case when it is equal to it then it would execute the code in this code block so by specifying the break statement we're telling JavaScript to break out of this switch case statement so no longer perform any more comparisons and move on with the program we'll log it out so in the case when it's equal to I'll say software developer and save it I'll scroll down so you can see the code and then I'll execute it so this is a way to achieve that same functionality once again when using switch case statements this only applies in the case when you are doing equality comparisons what are switch case statements and when would you use it switch case statements provide a clean syntax in the case when you're using a variable and Performing comparison equality you can implement the same functionality using IF and Al if statements but switch casy statements provide a clean alternative for accomplishing the same thing so to describe the syntax you would use the switch keyword then in parenthesis you would use a variable or a value and then within the code blocks you would specify different cases to define the case when that variable or value is equal to that case and then execute code for that particular use case when using switch case statements you also want to remember to supply a default value next we will cover for Loops so I will initialize an array call it let numbers is assigned to using our array literal syntax with square brackets I'll do 1 2 3 4 5 6 and 7even ending it with a semicolon now what I'll do is I'll initialize this number to be the index of zero because we know when we start counting these elements we we start counting from zero so for this index value in this element this is at the zeroth position then the first position second position and so on then to determine what the length of the array is I can say let length of array and it be numbers and arrays have a built-in property called length so that can be stored here so now what I want to do I want to go through and log each element in this array by referencing it by its index so I use bracket notation to access it by index I can do console.log so the name with the array square bracket notation and I'll do the index and I'll log that out so this executes and this displays the element at the zeroth position the first position of the array now let's say if I wanted to Output every single element well I can copy it over so I'll do shift option in the down arrow just to copy it over seven times now each time I want to increment it so rather than having to do do this and then do index Plus+ to increment it I can just do it within it and I know if I do the increment after then this will be displayed and then be updated after so I'll continue this TR for each one except for the last one and I'll log that out so here you see this executes and this displays every element in the array now this was a very repetitive process and we would want to do this in a real program so I'll comment all this out and we can use it to reference it as we build up our first for Loop so for Loops allow us to get the benefit in the power programming cuz it can execute a lot of code in a very short amount of time so we utilize the for keyword which is a special keyword that allows us to create a for Loop and we can do initialization here we'll say let index assign zero and we'll do a semicolon and then we can do while the index is less than the numbers. length and then the index increments and then I'll do curly braces so I'll break this down what we did here is just put the same logic on one line so we initial our variable index to keep track of where we are in the array then we have a condition so is this index value less than the numbers. length and this will evaluate to a Boolean value while it's true then the code within this code block Within These curly braces will be executed if it's false then it will stop execution now we want to continue incrementing through the numbers array so we need to continue to increment the index now if we were not have this then this will result in infinite Loop and this code will continue to be executed and our computer would crash so it's very important to have this last value incrementing it to make sure that we are getting closer to this condition being false so another way to think about this if this is your first time seeing it whenever we have these traditional for Loops we have an initialization part we have a conditional part and then we have an increment or decrement part so now in here I'll just do console log numbers at index so using this variable to reference the element that we want to execute so I'll execute that and we get the same result with much cleaner code so Loops reduce our code duplication and they have fast execution so here it's just executed with an array with seven elements but but let's say if I were to do another for Loop let's comment this out so command for slash or control forward slash let's say if I do four our initial ation part let num is assigned to zero while num is less than a value like 100 and let's say the number increments right initialization condition and then increment or decrement so this value the code will be continue to be executed while this condition is true and once it's false it will stop its execution so I do console.log and let's execute the number so here you see all these values are quickly executed and I don't have to go through and do console logs for every single number what is a for Loop in programming a for Loop is use in order to execute a code block repeatedly so rather than having to manually repeat that code which will lead to code duplication you can define a code block def find within curly braces and using the special syntax of the for Loop you can continue to repeat those lines of code while it condition is true what is the Syntax for a for Loop the Syntax for the traditional for Loop uses the for keyword then you would define an initialization part you define a variable then you would Define a condition so while the condition is true you will execute the code within the code block within the curly braces and then you will have an increment or decrement part where you are updating the variable such that it gets closer to the condition being false because you need to make sure that you break out of the for Loop cuz you don't want to deal with with an infinite Loop which would cause your program and your computer to [Music] crash we often need to repeat actions and Loops are a way to repeat the same code multiple times you've seen the for Loop which provides a traditional Syntax for iterating over an array we use for Loops when we know the exact time when we want the loop to stop executing there is another syntax called a while loop and we can implement the same functionality of for loops with while Loops so first I will show you the for loop again so we'll say we know we have let index is assigned to zero then we have the condition where we say the index is less than numbers. length and then the index increments right so we have the beginning part the initialization we have the condition and then we have the step condition where we're incrementing console. log numbers add Index right since this is new syntax for you I want to be repetitive just to make it easier for you to remember execute that now let's use a while loop to achieve the same functionality so I will say let index is assigned to zero and here I will use the while keyword so in the parentheses I will say index is less than numbers. length and then curly braces so in here I will say console.log numbers at index and then the index increments so I'll comment this out by highlighting it in control for slash or control for slash for Windows so we see that this has the same Parts but it's broken up so here we see the initialization part here then the conditional part and then the step condition so now execute it just to show you that we have the same functionality and executes the same functionality now the difference is that we would use a for Loop when the number of iterations is known before entering the loop whereas we would use a while loop in the case when the number of iterations is not known before entering the loop so to show you one condition that shows this and demonstrates this we can say if we have let sum is equal to zero and we can just say while true so while this condition is true execute the code with in the block I can just say console.log Loop and then some increments then I can do um if the sum is equal to 10 then in that case we can use a break statement and break out of the loop so this is a special keyword we can use within our while loop or for Loop to stop and break out of the execution so I'll run this and here we see we have console logged Loop so in this case we have shown that we want this condition in this Loop to continue to run while this is true and we have this case to ensure that we don't have an infinite Loop so it doesn't run an infinite amount of times and we know when to terminate it and this is something that we cannot do with a for Loop meaning that we cannot just use a condition of while it's true continue [Music] executing what are the similarities and differences between the for Loop and the while loop the for Loop and the W Loop are similar in that they both execute a block of code repeated while a condition is true the difference is is that you would use a for Loop typically for iterating over an array whereas a while loop you would use that in order to execute the same block of code while a condition is true we have another loop we can use in JavaScript known as a do while loop now do while Loops are not commonly used but I want to show it to just so that you are aware of it so previously we have used for loops and while Loops where we specified a condition and then executed code within curly braces and if and only if the condition evaluated to True would that code block be executed so the code in the code block was only executed after the condition with do well Loops we specify the code block first and then the condition after so let me show you an example let's say if we do let I is assigned to zero so we initialize that now we'll use this syntax where we say do which is a built-in keyword in JavaScript then we can do console.log let's say I and then we increment it now we Supply the condition after so while I is less than 10 then we use a semicolon determinate it so so this syntax will execute the code block first right everything I have highlighted within the curly braces and then do the condition check after to determine if the loop should continue executing so with this syntax it's guaranteed that our code block will execute at least once so I'll save this when I'll execute it up arrow and we see it's executed what is the difference between a w Loop and a do W Loop both a while loop and a do Loop are similar in that they repeatedly execute a block of code given a condition being true the difference is that a while loop will check the condition first and if it is true then execute the code with a do while loop it will execute the code first specify within the curly braces and then check the conditional statement so a while loop is not guaranteed to run it will only run if the condition is true whereas a do Loop is guaranteed to run at least once one thing I want you to be aware of in working with loops is the problem of infinite Loops so when working with either a for Loop a while loop or a do while loop we must ensure that our Loops terminate if you were to Simply do for example while true for the condition and just do console.log of loop then this will continue to Loop and execute an infinite amount of times and our program and computer would eventually crash so when working with either for Loops while Loops or do while Loops we have to ensure that we specify a condition in the parentheses that will eventually evaluate to false or we can explicitly use a break statement to explicitly tell JavaScript that we want the loop to stop executing so once again I'll show you the for Loop let num assign to Z num less than equal to 100 num increments and once again we'll log out the num so the two things I want you to consider here is the condition so this Loop will continue to execute while this is true and so the step condition right here we want to ensure that for each iteration we are getting closer to terminating this condition to this condition being false so that's where we do num Plus+ as opposed to numus minus cuz in this case it will lead to an infinite Loop so whenever you're working with loops be careful of the condition that you're using and the step that you are specifying to get closer for to evalua to false what are infinite Loops infinite Loops can occur in a for Loop while loop or do while loop this happens when the condition you define is always true this will lead to the code block being repeatedly executed without being terminated this will lead to your program crashing how can you prevent infinite Loops to prevent infinite Loops in your for Loop while loop or do while loop you need to make sure that there is a step condition that is continually being updated so that for every execution of the code block you are getting closer to the condition being terminated you have seen the for Loop many times which shows us how we can Loop and iterate over an array we also have a syntax that allows us to iterate over the keys of a JavaScript object once again a JavaScript object is a data type that allows us to specify key value pairs so now I can initialize the object con course sign to and object literal I can specify the key of name with the value of JavaScript for beginners comma then I can add duration 3 hours and sections 7 I ended with a semicolon now if I wanted to display each property or key of this object I would need to do the following console.log then I can access it through notation course. name I can also access the value through square bracket notation by do console.log then course square brackets and then as a string pass and duration and the last property console.log course. sections save it then I'll run in the panel node control flow. JS and this displays all the values now this is fine since we only have three properties but let's say this object had 30 properties then this process would be inefficient so we want to reduce our codes duplication and make it clean and easy to read by using a 4in loop so I can comment this out so the four in Loop is used with JavaScript objects to allow us to iterate over the JavaScript object and get access to the keys so if I do four and I can name it cons key in course so I can name this variable whatever I want and then we specify the object that we want to iterate over then I output it console.log of course and then using square bracket notation I will specify the key so then I output it and I get the same result [Music] what is the Forin Loop and when would you use it the foreign Loop is used to iterate through the keys of a JavaScript object you would use it when you want to efficiently iterate through the object and access its value in the case when we are simply looping over the elements of an array it can be bothersome to always have to write the traditional for Loop once again I'll show you full execution of that so I initialize an array with five elements and the traditional for Loop Lane index increments console. log and then we have numbers and we access it by its index with the bracket notation let's execute this clear it go up again to re execute each element of the array so this is a lot of syntax to write and in this case it's not needed because we are simply accessing the elements of the array we would need this in the case if we were using this index variable for some other use case but since we're not I can comment it out highlight it and do command for slash or control for slash if you're on windows so if we simply need to access the element we can use a different syntax called the four of syntax and this is used for when iterating over an array so once again we use the four keyword and I can say let element of numbers so in this case we use of and this iterates over the elements of the array now in this case I use the variable name element you can name this whatever you want and can call it numbers for example but I like naming an element and also I use the let keyword for this being a variable you could also have it be a con since we're not changing it I'll name it as let and then I'll console.log it clear this out and then iterate and get the same [Music] result what is the four of loop the four of loop is a special Tex in JavaScript that allows us to easily iterate over an array for each iteration we get access to the element you would use the four of loop over the traditional for Loop in the case when you don't need to use the index that you currently iterating on break and continue statements so when working with loops there may be specific conditions when we want to stop execution the break statement means to break out of the loops execution and we would use this to terminate the execution of a loop so this can be used for all the different Loops that we have covered so far which include the four Loop the while loop the do while loop the four in Loop and the four of loop let me show you an example of each for the four Loop we can say let I is assign to zero I is less than 10 and I increments now we can say if I we'll say if I is equal to five curly braces then we'll say break so this exits the loop when I is five so otherwise we want to console log it console. log I and let's execute it clear this out I'll go up and let's execute each of the expected values and stops execution once I is equal to 5 so I'll close this out and I'll commment it out command slash control slash now I'll show you the same process with a while loop so I can say let I is assign to zero while I is less than 10 if I is equal to 5 then we'll use break right exit the loop when it's equal to five otherwise console. log and since we're using a while loop we need to make sure that we increment I right we get it to where it stops execution so we don't get an infinite Loop so let's open up the panel again view appearance and panel and I'll clear it with command and K or control and K we'll go up with up arrow and execute it we get the same expected result now I'll continue showing you for the other Loops let's consider a do while loop so let's say let I assigned to zero now we use our do keyword and specify our code block within the curly braces we'll specify our condition so if I is equal to 5 strict equality and once again the break statement otherwise we console log I and we need to make sure that we increment I so we don't get an infinite Loop now we specify our condition after so while I is less than 10 we continue looping so open up our panel again clear it out same expected result right so let's do our for in the for in syntax is used with objects so I can say cons and I'll just call this object and I'll just specify on one line so we'll say the first first key is a and the value is one then we'll say b 2 and c and three and I'll just add a semicolon at the end here now I can do for let key in object now I can name this whatever I want and I could also use a const if I wanted but I'm going to keep it a and I can check if the key is equal to B for example so in working with objects each of these keys in this case it would be a B and C are internally represented as strings so if the key is equal to B then I'll break out otherwise I want to console log it so I'll say console. log the object at that key so let's open up the panel and let's run it so here we see it executes the value of one which is the value associated with the key a so I'll close this out and comment it out our last one is our four of Loop and it's used for ital objects so this includes arrays and strings so I can say so I can to const array is equal to 1 2 3 4 and 5 and I'll say let element of array if element is equal to three restrict equality then I can break out otherwise I will console log it open up the panel and we'll execute it again so we get the values of 1 and two and once the element is equal to three then we stop execution so I will clear everything out let's remove everything now let's talk about the continu statement so the continu statement means that you want to skip the current iteration of the loop and proceed to the next iteration and once again this can be used for all the different Loops that we have considered so far and I'll show you an example for each so the repetition is good because it really drills the syntax into your memory so we'll say 4 I is equal to Z while I is less than 10 and I increments now we'll say if I is modul 2 equal to0 so I'll explain what this means so the module operator which I covered earlier this finds the remainder of division so in this case the remainder of dividing by two if that is equal to zero this checks that if a element or if a value is even then in this case I will specify that I want to continue meaning that I want to skip this current iteration and move to the next one so then I will console log in the other case all right so another way to think of the continue statement you can think of it as if it were skip that's actually not a keyword in JavaScript but that's a way you can think about it to better understand its purpose skip the current iteration and move to the next one so I'll open up the panel and we'll execute it and so in this case we expect only odd numbers to be displayed since we're skipping over all the even numbers so once again only displays the odd numbers because we're using the module operator right which gets the remainder of the division so I'll comment this out now I'll show you the continue statement in the context of a while loop say let I is assigned to zero while I is less than 10 well I'll say I increments and if I modul 2 right so strict equality zero so if that is even then I want to skip to the next iteration otherwise I'll console log it console log I open up the panel and let's display it and it displays only the odd numbers as expected so I'll comment this out now let's consider a do while loop so I'll say let I side zero do curly braces I increment if I modul 2 Z then continue otherwise log it out and we specify our condition well I is less than 10 so I'm showing you the different way of doing it of using the continue statement for all the different Loops that we've covered so far right same result only displaying the odd values now in the context of the four in Loop once again 4N is used with objects I can specify cons object the curly braces the key of A maps to the value of one then B and two let's say C and 3 and d and four and I'll add a semicolon here and I'll iterate over it so we have four let key in object now in this case if the object the key right so now we're checking the value mod 2 Z well in this case we'll want to continue it right so we want to skip over all the even numbers otherwise we'll console.log the object at the key so we'll only display the odd numbers in this case so open up the panel run it again only the odd values in our object we'll comment it out and our last example is four of which is used for iterating over objects like arrays and strings I'll specify con array is equal to 1 2 3 4 and 5 then we'll say let element of r r array now if the element mod 2 is equal to Z right the remainder of the division is equal to Z then we know that it's even and we want to continue meaning that we want to skip over that otherwise we'll log it out log of element so let's open up the panel and we'll run it only the odd numbers in this case so you can use the continue keyword like a skip keyword and it skips over the current iteration and goes to the next iteration of the [Music] loop what is the break keyword used for the break keyword is used when dealing with control flow in for Loops or in switch case statements so when JavaScript encounters the brake statement within one of these structures it will stop the execution for that Associated for Loop or switch case statement what is the continue keyword used for the continue keyword can be used within for Loop Loops or while Loops so when JavaScript Encounters this keyword it will skip the current iteration of that for Loop and Skip on to the next iteration Implement a function that accepts two numbers and Returns the maximum number so we'll create our function with the function keyword and we'll name it Max num now we need to take in two parameter variables so I'll say num one and num two on our curly braces and then we had a return statement now we will compare these numbers so I can say num one and I can say greater than equal to num two in which case we want to return the maximum value which would be num one or num two so I'm utilizing a tary operator here so I'll test it say I'll console.log of Max num and I'll say two and one so we expect two to be locked to the console so execute it and the maximum value is [Music] displayed Implement a function to accept a number as a parameter then return the string fizzbuzz if that number is divisible by three and five or return the string Fizz if it's only divisible by three and not five or return the string buzz if it's only divisible by five now if the number is not divisible by three or five then just return the original number the next exercise is a common problem asked to Junior developers to weed out candidates that don't understand the fundamentals of programming so I will discuss the problem so the problem is known as fizzbuzz so it takes in a number and if a number is divisible by three and five then you want to return the string fizzbuzz now if the number is divisible by three but not divisible by five then you want to return Fizz if the number is divisible by five and not divisible by three then you want to return Buzz otherwise you want to return the original input so now that You' Tred to implement this problem I will go through and implement this solution for you first we want to use the keyword function we'll name it fizzbuzz and it takes in a parameter being a number so I'll call it number have our curly braces so now we want to see if the number is divisible by three and five so we have a conditional statement we have if the number is divisible by three right so we use the modular operator if the remainder of that division is zero and if the number is divisible by five then in that case we want to return fizzbuzz I'll do single quotes fbuds El if the number is divisible by three then in that case we want to return fiz otherwise if the number is divisible by five then we will return buzz in the default case we will simply return the number input so I'll do console.log bis buzz and I'll test all conditions so first we'll do a value that is divisible by 3 and five we can do 15 so we'll log that out so we're expecting FS buuz to be the result we get the expected result so now we'll say if it's 9 then we expect Fizz now in the case when it's 10 then we expect buzz and let's say if it's seven then we expect [Music] seven so for the next exercise I want you to create a function that takes in an array as a parameter and iterates through all the elements of the array displaying all of the even numbers so Implement our function we'll call it function and I'll call it display even numbers and I'll just call it an array as name of the parameter variable so now what I want to do is utilizing a for Loop so since it's an array I can use four and I'll say cons element or call it number number of array then I can check if the number is divisible by two by using the module operator then in that case I'll con I'll log it simply call display even numbers and invoke it passing in an array so I'll say 1 2 3 4 5 6 7 8 9 and 10 so let's output it in the panel go up and here we see only the even values are outputed now I can copy this and if I already say display odd numbers then the only change I would need to do would be to say if this is not equal to zero by using the not equal operator so in this case if I do to display odd numbers then only the odd numbers would be displayed so I can go up and only the odd values are logged to the console control flow refers to the order in which individual statements or function calls are executed in a program it determines the logical progression of a program based on conditions or Loops guiding the program to make decisions or repeat operations so in this section we covered if and Al if statements to conditionally determine which code to write so if a condition is true then execute the code within the specified code block within the curly braces we also have switch case statements to determine which code to execute based on equality we covered the traditional for Loop while Loops do well Loops the potential problem of infinite Loops which we want to avoid we covered four in Loops for iterating over the keys of a JavaScript object we covered the four of loop for iterating over an array we also have the break statement to terminate a loop or switch case statement and the continue statement which skips the current iteration and moves on to the next iteration of a loop great job on completing the section and with practice all the syntax will become come second [Music] nature so you know that objects are a way to store key value pairs they allow us to group together State and behavior that's highly related the benefit is that we can group together highly related variables and even group functions within it so using the object literal syntax I'll say const dog our curly braces creates an object literal now I can add a key so I'll say name with the value Max I'll say breed which is doxin age a five weight and pounds is 12 so far we've only stored key value pairs representing properties but we can also add our own function so let's say eat and we'll say a function so this is an anonymous function here and I'll say console.log tromp so that's one way of adding a function now there's another syntax we can just add the name of the method console.log and so when we have a function within an object we call it and Method so here we are encapsulating State and behavior so encapsulation involves grouping together data and the methods that manipulate the data into a single unit while hiding or abstracting away the internal details from outside interference or misuse what is the purpose of JavaScript objects JavaScript objects store key value pairs their purpose is to store State and behavior state is represented by properties and behavior is represented by functions within the object when when we specify a function within an object we call it a [Music] method so if we were to create another object with the same properties and methods as the dog object we would have to copy and paste so I'll show you an example of that let's say I copy all this and paste it here and let's say I call it another dog and the name let's give it a name of Marley say the breed is a chocolate lab the age let's say is three and say the weight and pounds is 60 so this leads to code duplication which becomes hard to maintain once our application begins to grow so I'm going to comment this out so far we've been using functions to perform some operation and return A Primitive value that value being a number a string or a bulling value but we can also use functions to return an object so here's an example of how we can do that to reduce our code duplication and our need to copy and paste create a new function and I'll call it get dog now I'll specify parameters which allow me to customize the properties for a dog object so I'll call it name breed the age and the weight and pounds so what I'll do here is I'll return an object literal with the same properties as this dog object so I'll give it a name so the key is name and the value is the parameter variable right the argument that we pass in have the breed we have the age the weight and pounds and then the same methods so you can use other syntax actually just to clean it up cons. log and the last method l so we have now created a function where by passing in the arguments to this parameter variables will allow us to get a dog object so if we wanted to create this exact object I can say move back up const I'll call it another dog equals get dog we'll pass in the name Marley the breed chocolate lab AG three and 60 so rather than having to duplicate all this code and copy and paste it we can instead get that same functionality all in one line by using a reusable function one more thing I want to show we see that we do have duplication here in our function because we are using the same key and value which have the same exact name so when you have this in JavaScript we have syntactic sugar which allows us to clean up our code so JavaScript is able to look at this and know that the key and the value have the same name so this only works when these values the key and this parameter ver that Supply to it is the same so let's output it out console.log I call it another dog so outputting that object I would do node objects. js and I can output and see the properties and the method what are Factory functions Factory functions provide an efficient way for us to create a new object now the name of the function will use camel case notation and it can accept parameter variables these parameter variables can help customize the values of the object being returned the benefit is that it reduces code duplication and the need to copy and [Music] paste so we know that the object literal syntax using curly braces creates one object and that we can use Factory functions to easily create multiple objects Factory functions is not the common way of achieving this rather we use Constructor functions the purpose of the Constructor function is to construct the initial state of an object when creating a Constructor function we use p SC notation whereas we would use camel case notation for variables and function names Constructor functions use a special keyword called this which references the object that's calling this code so when you see the keyword this you can think of it as this current object so the naming convention for Constructor functions is to have the name of it be a noun rather than a verb so Show an example of a Constructor function use the function keyword and we name it a noun so I'll name it dog I'll specify the parameter variables so name greed age and weight and pounds so if the differences above we have the factory function which uses a verb and camel case notation and on the bottom we use a noun and Pascal notation so internally when using a Constructor function there's a special keyword called this which is assigned to an object literal the curly braces and this is done internally and implicitly so we don't know how to explicitly write this out I just want to show you a visual example of it and then we would add properties to this this keyword so I'll say this.name is equal to name this. breed is equal to breed this. age is age and this. weight and pounds is weight and pounds so what we were doing we were assigning this current object specifying a key and assigning it to a value with this value is actually the argument being passed then we can specify our methods I'll do this. e and assign it to an anonymous function the function keyword and then I'll just copy this console log and then our last method do this. bar is assign to an anonymous function and I'll just copy this console log and this will implicitly return the this keyword where this keyword represents this current object so this convention of making an uppercase and using Pascal notation tells other programmers that this is a Constructor function and it's a common convention using JavaScript so to use a Constructor function we utilize a special keyword called new I'll scroll down and show an example of that I'll say const another dog as the name of the variable and I'll assign that to new dog then we pass in our arguments I'll specify Marley as the name of the dog it's a lab we'll say 3 years old and 60 lb so we say that we instantiated a new dog object and the variable name another dog references this new object that we just created that we just instantiated so let's talk more about the new keyword the new keyword is syntactic sugar which means it provides a modern and clean syntax and does three things under the hood when we use the new keyword with the Constructor function it creates an empty JavaScript object it then sets to this keyword to point to this empty object in memory and then it returns this keyword and does so implicitly so to recap the main purpose of Constructor functions is to define a function that will initialize an object with an initial State and this initial State can be customized based on the arguments that you pass to the parameter variables so now I'll log out this object I'll say console.log another dog and I'll run this and here we see it outputs our [Music] object what are Constructor functions Constructor functions are used to instantiate objects in JavaScript we would name the function using Pascal notation and use a noun for the name then for setting the key value pairs we will use the this keyword and within it we can set the properties and the methods of an object objects in JavaScript are Dynamic meaning that we can add or remove Properties or methods at any time so for example if we have con person is assigned to the object literal key of name and the value of Steven end it with a semicolon here I'll just console log that run it again so we just see that object literal with the expected property now we can also add properties on the fly so if I do person and let's say if I use dot notation and I can just say any key that I want can say favorite food and assign that to the string tacos then I'll just copy this and I'll log it again and this will comment the first console log out and let's run it again so here we see we have added this property of favorite food on on the fly so you can update objects dynamically we could also update it using bracket notation say person and I'll say favorite ice cream and I'll assign that to CH just to show a different Syntax for you to add a property here I'll log it out coma this one out and here we see added that property now we can also delete properties and I would delete properties using the delete keyword so I'll say delete person do favorite ice cream and if I were to console log it I'll just copy and paste it here then I expect the object to have the properties of the name and the favorite food and we get it as expected so comment this console log now we could also add methods on the fly so I can say person. e as the key and just assign it to Anonymous function and this was just console log say start eating for example then I can invoke it I can just say person. e then the parentheses to invoke and call that method let's run it and we get the expected output of start eating which we defined in this function so notice that when we created this object literal we use the const keyword now in this instance since we assigning it to a complex data type being an object data type that's stores multiple key value pairs using the con keyword means that we cannot assign it to another value but we can still change and mutate the properties and methods within that object literal to short an example that I can say person and assign that to an empty object in object literal and let's run it and here we get an error because we cannot change the assignment to a constant variable after we've already initialized it explain in your own words how are objects Dynamic objects in JavaScript are dynamic because you can change and mutate the properties and methods of the object after it has been [Music] initialized every object in JavaScript has a Constructor The Constructor function is the one used to construct an object and it is called implicitly whenever we create a new object we use the term instantiate whenever we create a new object as in we instantiated a new object so we have our existing object with object literal syntax and person references this object now there is a built-in property for all objects called Constructor which we can access either through dot notation or bracket notation so I'll console log that console.log say person do Constructor output in and here we see it references a Constructor function I'll comment both these out so when we do let new object and assign that to an empty object literal with these curly braces internally JavaScript sees this as if were to do let new object assigned to the new keyword and then object comment this out so these two lines the one above and the one beneath it mean the same thing however this first syntax which use the object literal syntax is syntactic sugar essentially this means it's a shorter way to write the same code so in JavaScript we also have new string as in the string object but instead we use string literals so for example I did my name now we also have new Boolean but we use true and false instead for bulling literals we also have a new number but we just use numbers as a number literal so every object has a Constructor property which refers to the Constructor function used to create that object what is the Constructor property The Constructor property is a property that exists for all objects in JavaScript you can access it with either the dot notation or bracket notation and it references the Constructor function used to instantiate and create that [Music] object in JavaScript unlike other programing languages functions are objects so for this function that I'll Define here I'll name it function add and it'll accept two parameters num one and num two and then I'll just return the sum of these values so this function here is actually an object in JavaScript so it is an object in memory I'll show you an example of that I can actually assign it to another value so I'll say const n just the name of this variable and I'll assign that to the name of this function so now n references this object in memory it references this function I can actually call and invoke this function and I'll show you an example of that I'll do console.log and I'll say n and I'll invoke it and I'll pass in two arguments I'll just say two and two now I'll log it out up arrow and here you see the value four is expected so I'll comment this out so this function that defined add has members meaning that it has properties and methods here I'll console log and I'll say add and this has a prop property length which defines the number of parameters that this function accepts I'll loog that out and I expect two and we get it as expected so I'll comment all this out and I will Define a Constructor function I'll say function and then using Pascal notation so the first letter is capitalize I'll name it programmer and it will accept one parameter I'll just say name so we know to use the this keyword which means this current object so I'll say this. name and I'll assign it and I'll also Define a method within this Constructor function I'll say this. writes code or write code is assigned to an anonymous function and I'll say console.log and I'll say code in JavaScript end it with a semicolon so this Constructor function is an object in memory I can console.log and I'll say programmer. l and we log it out and we see it accepts one parameter I'll just copy one more time and I'll say Constructor log that out so here this references the Constructor function I'll show you a different syntax just to further demonstrate how functions are objects in Javas script I'll comment this out command for slash or control slash if you're on Windows and I'll say const programmer and assign it to New function I'll specify my parameter name it name and then I'll use back ticks as the second argument and I'll Define this.name is assigned to name and this do write code is assigned to the anonymous function I'll just copy this console log here so here I see I'm using the new function syntax to instantiate a function object assigning it to this value so then I can instantiate it say cons new programmer then I'll use the new keyword to call the Constructor function say new programmer and pass in the argument of my name end it with the semi and then I'll say new programmer and call the method write code so let's log that out and we get the output as [Music] expected explain how functions are objects in JavaScript internally functions are represented as objects in JavaScript meaning that they have properties and methods so you know that we have eight different data types in JavaScript which include the primitive data types which are number string Boolean null undefined symbol and big int we also have the complex data type better known as object data types so arrays and functions also fall into the object category the reason we differentiate these data types is because of how they are allocated in memory so let's consider the perimeter data type first if I say let a and I initialize that to 10 let's say let B and I initialize that to be assigned to the variable a now if I reassign the value a let's say if I assign that to the value 20 let's console log both of them and console. log V open up the panel and we'll run it so here we see the output different values so both A and B are assigned to a number which is a primitive data type and when we log them out we see that they are two independent variables meaning that that they refer to different memory addresses when we assign a variable to another variable which holds a primitive value then that primitive value will be passed by copy so essentially this would be the same as doing let B assigned to the value of 10 so if this is your first time being introduced to this concept this may seem overwhelming at first but this will become second nature over time to summarize what I've been saying just remember this primitive values are passed by copy not by reference so I'll clear this so let's say if I initialize let a is assigned to the object literal which has the property value 20 and I'll say let B is assigned to a so B is assigned to this reference variable which is assigned to this object so let me change this value so I'll say a. value and I'll assign that to the value 100 so now let's output both of them so I say console.log I say A and console.log B let's see in the panel so here you see when I log them out they have the same value I updated the value of a but I did not update the value of B and the reason why they outputed the same value is because they are both referencing the same object and memory they're both referencing the same memory address so to summarize Primitives are copied by their value and object are copied by their reference this is an important concept and it will make more sense with practice and this concept also applies to other programming languages what are primitive values and what are they passed by primitive values refer to simple values such as string number booleans and they are passed by copy what are object values and what are they passed by object values refers to key value pairs this also includes arrays and they are passed by reference so we've covered the different for Loops we've covered the four of loop which is used to iterate over an array we have the four in Loop which is used to iterate over the keys of an object and I'll give you a reminder of both of those so first I'll create I'll say let numbers and assign that to an array of 1 2 3 4 and five and to it it over it I'll use four I'll say con elements of numbers now once again I could name this variable whatever I want but I'm naming elements just to demonstrate that it's iterates over the elements of the array then I'll do log of elements let's log that out with node objects. js and this outputs all the elements in the array so I comment this out then I'll create an object say cons dog is assigned to the curly braces name Max I'll say age is five and I'll say I color is blue I'll end it with the semicon then I'll say four cons key in dog so the four in Lube will iterate over the keys of an object so I'll say console.log dog and using square bracket notation I'll use the key to iterate the values let's output it and we get the expected result comment this out so we have another Syntax for enumerating over the keys and the values of an object I'll store the values here I'll say const and I'll name it keys and we can use object. keys and pass in the name of the object this case it's dog so object is a built-in class in JavaScript and it has properties and methods once again methods are just functions defined within an object so this returns all the keys of the object as an array a console Lo console.log keys so this outputs all the keys of the object comment this out now we also have object. values in order to get all these values stored as an array so I can say const values is equal to object. values of Doc let's console.log that and output it now we get all of the values of this object stored as an array we could also get the properties so the key value pairs each stored as an element in the array to show you that I'll say cons and I'll call it entries equal to object. entries and pass in the name of that object let's console log that entries we'll output it so here we see the key value pairs has been stored as an element in the array so essentially this is a nested array so this provides another syntax to accomplish the same thing which is enumerating over an object now to show you how we can use these methods to iterate over the values I'll show you an example let's say four and I will say const key of object. keys fast and dog I'm using four of because we are iterating over an array then I can just copy and paste this to key or output that so once again this iterates over the array and comment that out then I'll say four const value of object. values the name of the object and let output that this outputs all the values and then we'll do our entries so I can say four const entry of object. entries pass in the name of the object console.log of entry and we'll output it so here we see the key value pairs displayed as an array and this particular syntax may come in handy when doing programming interviews during cases when you need to enumerate over an object how can you enumerate over the properties of an object there are different ways to enumerate over the properties of an object one way is you can use the fourin loop iterate over the keys of an object we can also use the built-in object class for example iterating over the keys with object. keys enumerating over the values with object. values and enumerating over the properties with object. [Music] entries so we know that if we have two variables I'll say let a is assigned to the object literal value of 10 I'll say let B is assigned to a now if I were to update one of the variables we know that since they both reference the same object if I change one it will also affect the other variable console.log a and console. log B and since they both reference the same object they will both have a value of 20 so I run in the panel so here they display the same value as they both reference the same object now if we wanted to have it the case where if we change the value of one of these variables it doesn't affect the other then we would need to have it be two independent variables and that could be accomplished by creating a clone of an object so we know that objects are passed by reference so we need to use a built-in method called object. assign so instead of saying let B is assigned to a I'll initialize it to an object literal then before I assign this value I will do object assign first I will pass the target object this is the object that I want to copy to so in this case it would be B and then I provide one or more Source objects in which I want to copy the properties and methods to the Target object in this case it is the variable a so all the properties and methods of a will be copied to B and it will create two independent Vari so B will now have a clone of the object that a references so here I'll save this and I'll run it so here you see they reference two different objects and they have different values changing one does not affect the other now we also have another syntax that allows us to accomplish this known as the spread operator it uses three dots as in an ellipsis and this will create a copy of the object so instead of having to do object. assign when I initialize B I can use three dots dot dot dot and then the object that I want to clone in this case it' be a so this will create two independent objects so they are not referencing the same object in memory open up the panel and we'll get the same result how would you make a clone of an object in JavaScript you can make a clone of an object by using object. assign for the first argument you would pass the target object then you can pass in one or more Source objects you can also use a more modern syntax known as the spread operator in order to copy the properties and methods to a Target object by the use of three dots before the variable that references the object in programming languages like C++ when you create an object you have to allocate memory and deallocate it but in programming languages such as JavaScript C and Java we don't have this concept so you don't have to explicitly deallocate memory the JavaScript engine has a garbage collector meaning that it will self-manage itself and find the variables and objects that are no longer being used in our program and it will intelligently free up that memory as JavaScript developers we don't have to worry about allocating and deallocating memory for our objects in JavaScript we have a built-in class called math this has static helper methods to help us do mathematical calculations and is often utilized in programming interviews it has many methods so don't worry about memorizing it rather refer to developer. mozilla.org search for a math and click the first recommendation then you can read the documentation and view the various methods that it contains here I will show you the most commonly used ones I'll open up the panel and I'll type in node so when working with decimal numbers I can use math. round and pass in 3.14 and this will round the number likewise if I did math that round say 3.6 and it will round up now if I always want to round down I can use math. floor let's say 4.6 if I always want to round up I can do math. ceiling say I do 4.2 now to find the maximum number I can do math. Max and I can pass in one and two I could also add in more arguments to say if I 1 2 3 4 and five so it accepts more than just two arguments likewise I have math. Min just say if I do 1 two and three we could also raise to the power of so I can say math. the base number say if I make it two and let's just say if it's cubed then I can perform that I can do math. square root say 25 so I'll clear this out now one of the most useful built-in methods is the random method we can do math. random so this will return a number between 0 and 1 as a decimal value now if I want to return a random number between a range then I need to perform it differently let's say if I do let Min assign that to one and I say let Max equal to 10 now if I want to return a random number I can say cons random number then I'll assign that to math. random times the max minus the Min plus the minimum so this will return return a number between 1 and 10 and if I wanted to always be an integer value then I would do math. round and wrap it in parentheses so I'll console Lo this value console.log random num and this will generate a random number between that range I just run node node objects. js if I ran it again so don't worry about memorizing these these will come second nature over time I just wanted to introduce you to the built-in methods that you have access to what are some of the methods that the built-in math class has some of the methods that we covered include math. floor math. round math. seal math. Max math. Min square root math. power and math. random how would you generate a random number between 1 and 100 this L of code represents the formula in order to create a random number between a minimum number and a maximum number so when jaas script we have two kinds of strings one way is the string literal through the use of single quotes double quotes or back ticks so for example if I just do CL name and assign it to a name a console log I'll say type of name when I output it I'll see that it is a string data type now I can also make a string using the string object so I can say const I'll call it another name assign that to put the new keyword which calls the Constructor of string I can pass an argument here I'll just say Joe as the name now if I console log the type I'll see that it is an object another name output it and we see this value is an object data type so I'll comment this out so with this variable that is assigned to this string literal we can access the methods of strings using dot notation or bracket notation and the JavaScript engine will internally wrap that string literal with the string object so there are built-in methods that allow us to operate and manipulate strings in this video I'll show you some of the most commonly used ones I'll make a new string I'll say let sentence and I'll s that to a new sentence and I end with period comment this out now I can check does include new for example I can say sentence and one built-in method is includes pass in the string new and so what this does is this checks the string and sees if the string passed to it as an argument is found if it is then it returns true otherwise it returns false here I just log it out does include new here we see that it does include we can access characters by index value where the first character of a string is at the index of zero the second character is at the index of one third character is index 2 and so on so if I do console.log a sentence at the index of three so if we count this we see the first character at the zero position is a then the empty string then n is at the second index and then E is at the third index because we start counting from zero so we're expecting e we show it in the panel and we get the character that we expected this out I can say cons starts with a I'll say sentence so the method is starts with I'll pass in the string of a and this will return true if the sentence begins with this character and false otherwise. log resp a and we see that is true now I'll just copy this paste it here and I'll rename it I'll say ends with a and change the method to be ends with change that here com it out so we expect this to be false I'll run it and we get false as expected now another useful method is the replace method so if I do let updated sentence sentence. replace first argument I can specify the string that I want to replace in the current existing string oper on so let's say new and I want to replace that to be short so this will return a new sentence and it will not mutate this existing sentence let's output it also log update sentence output it so we expecting the new string to be a short sentence and we get that updated string now some other useful methods is the trim method so if you're expecting user input from an input field it is useful to use the trim method in case the user has spaces in the beginning or at the end of their input so let's update this as if we had space in the beginning and space at the end I'll call this trimmed sentence so I can say sentence. trim and this will remove the spaces from both the beginning and the end here just console log it and get that string with the spaces trimmed at the end now some of the methods is trim left which will remove the spaces from the beginning of the string and we have trim right which will remove spaces at the end one useful method that is commonly used in programming interviews is the split method with the split method we can specify a delimiter and what JavaScript would do is that it will create an array split in the sentence so I can say con and I'll say words in sentence then I will say sentence about the split and the delator I'll say this empty string so so this will split the string whenever it encounters an empty space and those elements will be placed in an array here I'll remove these spaces in the beginning and the end so here let's console log console.log words and sentence then I output it so it is split based on the white space so I'll comment this out two other helpful methods are two lowercase and two uppercase so let's say a user enters in their email and they enter it with mixed casing so some letters are capitalized some are lowercase well when we save that email in the database we likely want to make that all lowercase or all uppercase so the next time when the user logs in they are not restricted from logging in based on case sensitivity so I can say say let lower case email assign that to email and I'll say to lower case console log that lowercase email node objects. js and we get that same string but in all lowercase likewise I can say let uppercase email sign that to email. two uppercase output it uppercase Emil now we get in all uppercase there are many more methods available for Strings and it's best to consult developer. mozilla.org to view the documentation for [Music] Strings name some of the methods in the string [Music] class some of the methods in the string class that we covered in this lesson is replace trim trim left trim right includes index of split two lowercase and and two uppercase in previous lessons when working with strings we have used either single quotes or double quotes we have another way to create a string literal and that is with back ticks so the back tick key on your keyboard is usually above the caps lock key on the upper left side the benefit of using back tick characters which we call a template literal is that it allows us to use string interpolation rather than having to use string concatenation so for example if I say let first name and assign that to my name and then I say let last name and assign that to my last name name now if I want to combine them I can say let I'll say full name and I have to do first name and use the plus sign operator add last name and this performs string concatenation creating a new string and storing it in this variable so let's output it console. log full name and when we run it we see the strings have been combined but there is no space between them so let me add that in I'll add an empty space and then another plus sign now if I run it again I see it properly displays with the space in between so rather than having to include this which is a bit hard to read I have another syntax that I could use so I'll comment this out with template literals it provides a cleaner syntax to accomplish the same thing I can say let full name then I'll use back ticks to create that string literal otherwise known as a template literal then I can use a syntax a dollar sign and then curly braces this acts as a placeholder and within the curling braces I can specify an expression in this case I would use the variable first name name then a space then dollar sign and then last name now I output it and I get the same result what are template literals tempate literals provide an alternative syntax to the traditional strings by using back ticks the benefit is enables us to use string interpolation meaning that with the dollar sign and then curly braces we can utilize that as a placeholder and specify Expressions within it rather than having to use concatenation with the plus [Music] operator in JavaScript we have a built-in date object it stores the date and time it also provides methods for data and time management in JavaScript we would use the date object most commonly to store creation and modification times for a resource the date object can be initialized in multiple ways I'll open up the panel type in node and then enter now we can initialize a date object by going new then date and if I pass in no arguments then this will create a date object based on the current date and time do now and enter this shows my current date and time now I could also create a date object by passing in a number which will represent the number of milliseconds since January 1st 1970 so for example I can say let January 1st of 1970 equal to new date and if I pass in zero representing 0 seconds since January 1st 1970 then when I lock that out then it displays the date and time likewise if I were to do let December 31st 1969 sign to new date and if I do -24 * 3600 * 1,000 then this would be the previous day you could also pass in a date string to construct a date object by just do cons we'll say date one assign it to new date by pass in December 25th 2024 and specify time like can log that out now I can do January 1st of this year and I can say new date passing in the year then the month which is indexed at zero so zero would represent January then the 1 I log that out so check out developer. mozilla.org to read the documentation on the date object there are many methods built in that can't be feasy covered in one video now to cover some of the most common methods I'll clear this out now if I have now assigned to new date one method we could use is now. getet full year we have now. getet month represented as a number and now. getet date we also have now. get time zone offset so this will return the difference between coordinating universal time and your local time zone in minutes this video was just meant to provide an introduction to the date object and to give you an idea of all that this object can do so in this section we covered object literals Factory functions using camel case notation to create a new function we covered Constructor function which uses Pascal notation and we can instantiate objects using the new keyword with these Constructor functions Constructor functions utilize the keyword this which refers to this current object and it implicitly returns a new object we covered the dynamic nature of JavaScript objects and how we can add Properties or delete properties on the Fly we covered that functions are objects in JavaScript and they have properties note that primitive value types are passed by copy and object types are passed by reference you can clone an object with object. assign or use the more modern syntax which is the spread operator represented by three dots we went over template literals and how we can use string interpolation and we briefly covered methods built into the string class and date class so great job completing this section we covered a lot of material and I will see you in the next one arrays are a commonly used data structure which provides a collection of elements in other words a list of items in JavaScript each index position known as an element can be of any data type however in real applications all the elements of an array are usually of the same data type there are many built-in methods for arrays which enable you to modify filter data and retrieve data using clean and modern syntax in this section we'll dive into some of the most commonly used methods what is an array an array is a commonly used data structure in JavaScript that stores a list of data so one of the most common operations when dealing with arrays is adding elements so I'll rename my file to be arrays. JS then I'll declare an array I'll say con call it numbers square brackets and I'll say 5 4 3 2 and 1 so since we have used the const keyword we can't reassign this array to any other value so the numbers variable references the array in memory and an array is an object meaning it contains key value pairs in this case mapping an index value which starts at zero going from 0 1 2 3 and four and that maps and corresponds to this element value so the cons keyword means we can't reassign it but we can modify the array so for adding elements to this array there are three scenarios or three ways that we can add an element to it we can add to the end we can add to the beginning and we can add to the middle so to add a value to the end you would use the push method so I can say numbers. push I'll pass in the value seven and let's console log it then I'll say node arrays. js and here we see the array outputed and the element that I pushed was added to the end of the array so the push method can accept multiple arguments so we can add multiple values at once in one go so let's say I want to add seven8 and n let's save it and we'll log that out and here we see it has added all these values to the end let's comment this out we can also add a value to the front of the array and we would use the method unshift so I'll say numbers unshift and I will say 25 so I'll just copy this console log and I'll paste it here once again in the console and we see the value 25 has been added in the beginning of the array we can also do multiple values of once let's say 25 and 24 and both those values have been added to the beginning of our array comment it out again next you want to consider adding elements to the middle of an array and to do that you would use the splice method so the splice method for adding elements we uses three arguments I can say numbers C splice for the first argument you would specify the index position where you want to start from in this case I'll say from the first index position so this be the index position just after the value five for the second argument you would specify a number which indicates the number of elements that you want to delete since I don't want to delete any elements in this example I would use the value zero now for the third argument is where you would specify what data you want to add and you can add more than one value in this case I say I want to add the values 25 and 24 and then I'll console log it opening up the panel I go up and run it here I see the values 25 and 24 have been added starting from the first index position of the array how would you add an element to the beginning of an array you would use the method unshift to add to the beginning of the array how would you add to the middle of an array you would use the splice method how would you add an element to the end of an array you would use the push method arrays can store both primitive data types or reference data types meaning objects there are three main methods that we can use to check if an array contains a primitive value and that isindex of last index of and do includes let's go over an example of each let's say if we initialize the array numbers is assigned to 5 4 3 2 and 1 now if we want to find the index of the value of three I can say const index of three and assign that to numbers. index of and then the value I want to search for so this will return the index that it's found at starting from left to right now if this value that I pass as an argument is not found in the array then it return the value negative 1 so I can output that and I'm expecting the value of two so I can say console. log of index of three now if I output that in the console and here I see the value of two indicating the index that it's found at now typically I wouldn't just output the index value rather I would use it with bracket notation so I can say numbers and then bracket notation then I would utilize that variable so I can access this value by Index this out now let's say that if we had a duplicate value so if I add three at the end index of always searches from left to right so if I wanted to find out what is the last index of it then I can use the last index of so comp last index of three ass to numbers. last index of that same value so we expecting last index of three to be five cuz we count from 0 1 2 3 4 and 5 that is the index position so let's just output that console. log last index of three and we get the value of five as the index where it is stored at now let's try a case when we search for a value that does not exist we can say const index of 10 and assign that to 2 numbers. last index of 10 so this will have the value of-1 and if we try to access that by bracket notation then we will get the value of undefined so let's output both of those console.log so this will output1 and then when we try accessing it we will get numbers index of 10 and this be undefined let's see that and we get that output now whenever we use index of or last index of we typically do a conditional statement and check and ensure that the value is not negative one before using it to access that element so I can com that out and then I can do for example if index of 10 is equal to1 indicating that the value of 10 is not found in the array then I can conso log 10 is not found in the array can output that so we can utilize index of and last index of with our conditional statements now if we are not utilizing that index value in order to access or change that element then we can just use the includes method which will return a Boolean value of true or false depending on if that value is found in the array so I can say if numbers do includes 10 then I can say console.log 10 is found in the array and so since 10 is not found in the array this will not be console loged let's see if I log it out and there is no output now I could use the exclamation point in the beginning so with the exclamation point this reads if the numbers array does not include the value 10 then I'll put what is in the code block so I can say 10 is not found in the array and when I run in the console I see that output how would you check if an array contains a primitive value there are three main methods you can use you can use index of last index of or do includes consider the following array employees assign it to an array of objects I'll say the ID name gym so then I'll add two more objects to this array I'll copy this and then I'll do shift option and down arrow two more times then I'll update the IDS two and three and update the names say melot and Pam so with this array of objects using the includes method or index of won't help us find an element as comparing two different objects even if they have the same property won't be equal as those objects have different memory addresses so instead you would use the find method going to find that here say const employee equal to employees. find now as the argument you would pass a function in this context the function will be referred to as a callback function we call it a callback function because we pass the function as an argument and it will be invoked at a later time now this particular type of callback function for the fine method is referred to as a predicate function meaning that it will return true or false previously I mentioned that functions are objects so this is what enables us to pass functions around as arguments in JavaScript so we can specify function we will define an anonymous function so we won't give it a name now it will accept an argument we'll specify e as the parameter variable then we can do curly braces and end it with the semicolon now within the code block the predicate function has to return a true or false value so we can do return then the parameter variable e do name equal to and we'll say gy so if this value is not found then it will return undefined otherwise it will return that element so I can console log it console.log employee opening up the panel here you can see it outputs that object so the find method will return the first element that matches we also have the find index method which acts the same way except instead of returning the object it will return the index where that object is found at what array methods would you use to find and locate an object you can use the find method or find index method for both of them you would specify a predicate function to locate an object based on a property but previously we use an anonymous function in order to Define our callback function however there is another more modern syntax that is more commonly used and it's easier to read this syntax is known know as an arrow function so traditional functions will look like by the function add and I specify two parameters num one and num two curly braces and then I just return num one plus num 2 so this is known as function declaration now another syntax to accomplish the same thing is the arrow function so I can name it const I'll comment this out then I'll name it add an equal sign for an assignment and then I specify the parameter variables so I'll say num one and num two and then I will use an equal sign and then the greater than sign so this Den notates an arrow now I would specify that same functionality in the curly braces num one plus num two so remember functions are objects in JavaScript so this is being assigned to the ad variable Arrow function syntax is commonly used for callback functions when you have an arrow function that has just one statement in the code block then you can simplify it you can remove the curly braces and put everything on one line you could also remove the return statement because the arrow function knows implicitly that you are returning this expression this provides a cleaner syntax to use when using predicates so rather than using this implementation with the function declaration we comment that out and here I can remove that function keyword so it's no longer an anonymous function then I use the symbol for Arrow function and I can clean it up and put everything on one line so I can remove this return statement and remove the curly braces so this is a cleaner way to accomplish the same thing how would you define a function for theine method the doine method is a method that exists for the array class and is used in order to find an object for the argument you would specify a function in this case it would be a predicate function meaning that it would result in true or false you could use either an anonymous function or an arrow function in order to implement this what is an arrow function an arrow function is an alternative syntax to the function declaration syntax you would assign it to a variable and Define it with parentheses and then use the symbol for equal sign and greater than symbol and then specify the code block if the code block only consists of one line then you can put everything on one line and you can remove the return keyword so once again let's create an array I'll name it const numbers is assigned to 1 2 3 4 and 5 so for adding elements to an array we can use the push method to add to the end we have unshift to add to the beginning and we have splice to add to the middle now for removing elements we have pop to remove from the end we have splice to remove from the middle and we have shift to remove from the beginning so let me show an example of each of these so if I do cons last element assign to numbers. pop this will remove the last element so in this case the value five stored in this VAR varable so let's output that say console. log now I'll use backticks and we'll use our template literals I'll say last element colon and then dollar sign curly brace last element and let's output that we're expecting the value five so here we see last element and then the value that was removed but I want to remove the first element can say numbers. shift so this will remove the value of one so let's output that console.log by say first element and then sign first element end it with a semicon we can output that go up and run it again so here we see the first element of the array was removed we could also add a space between these values by add back sln so when JavaScript encounters back sln it knows that this means to create a new line so if I run it again we can expect this time there would be a space between these outputs so let's do our last method which is the splice method so for the splice method it could be used to add to the middle of an array or to remove from the middle of array so here we do say cons I'll name it middle element equal to numbers. splice so for splice the first argument is the index to start at the second argument is the number of elements to delete starting from the index specified in the first argument any argument that you pass after that is optional and it will specify the new values to add if I say from index one and I want to remove one element this will return the value and store it in Middle element so if I do console.log middle element and output it here I see the middle element has been outputed with a value of three how would you remove an element from the beginning of an array you would use the shift method to remove an element from the beginning how would you remove an element from the middle of an array you would use the splice method how would you remove an element from the end of an array you would use the pop method so we covered how to add elements to the numbers array as well as how to remove elements now if you wanted to clear all the elements of an array there are different ways that we can do that one way is we can use a while loop we can say while numbers. length is greater than zero then we can call numbers. Pop so repeatedly move from the end so although this works if the numbers array was large this would be an inefficient way to do so we can comment it out and we'll look at a different way so we've covered the numbers. length property we could also use this property in order to assign a value so if we assign it to zero this will clear the numbers array so I can output that I'll say console.log and I'll output this array and there I see that the array is empty let's comment this out now we've used the splice method which can be used for adding and removing elements so we can say numbers. splice starting from the first element at index zero and then for the second argument it specify the number of elements to delete so I can say numbers. length and this will remove every element also the splice method will return all the elements that were deleted in an array so I'll just say cons I'll just say deleted numbers let's log that console.log and template variable deleted numbers qu deleting numbers when we output that we can see all the values that have been deleted comment this out now another way we can do that is simply defining numbers to a new array so remember an array is an object so when we assign it to a new array the previous array will be garbage collected since I use the con keyword that means I cannot reassign it so I would need to change this to let in order for me to reassign this variable another thing to be aware of if I were to have another variable let's say if I name it let another array assign it to numbers then both of these values will be referencing the same array in memory so in this case even though I reassigned numbers to an empty array another array will still be referencing this previous array so it will not be garbage collected how would you empty the contents of an array to empty an array you can simply assign it to to a new array you could also set the length property to zero or use the splice method so let's say we have two arrays and we want to combine them into one array so I can initialize const example numbers a assign to 1 2 and 3 then const example numbers B assigned to four 5 and 6 so now I can combine them using the concat method so I can say con combined array is equal to example numbers a conat example numbers B so this will return a new array console. log combined array and displaying it in the panel here I see it has created a new array now we can also slice the array meaning that we can specify a start index and an end index and it will return a new array with the elements found within that range the slice method will not affect the original array so I can say const First Slice assign to combined array. slice from 0 to 4 so opening up the panel here since I specified the range between 0 and four it will return a new array containing the values of 1 2 3 and four so the second argument is exclusive here if I log that out console.log for slice so these are the two methods to combine and slice arrays so if you're performing this with primitive values then the elements will be passed by copy however if you're dealing with objects then the elements will be passed by reference how would you combine two arrays you would use the concat method to create a new array how would you get a slice of an array you would use the slice method and you can pass two arguments the start index and the nend index there is another way to combine two which is to utilize the spread operator we have discussed the spread operator before so it can be used to copy the properties of an object or the elements of an array so rather than using the concat method I can say let combined is assigned to three dots to spread the elements in this array comma and then the other array so this accomplishes the same thing as the concat method and this is the more commonly used syntax outputting this and we get the same result this syntax also provides more flexibility than the concat method as we can add elements in between these values meaning I can put a value here or perhaps at the end so it provides more flexibility than the concat method so if I remove this if I just say let a is assign to one and two and then let B is assigned to a so arrays are objects which means that they are passed by reference so the references of A and B both reference the same array in memory so the same object in memory so we could also utilize the spread operator in in order to make a copy of an array so instead of saying let B is assigned to a I can say square brackets to create the array and then the spread operator so this creates a new array and spreads the content what is the spread operator the spread operator refers to using three dots in order to copy over an object so this could refer to an object literal and copying over the properties it could also refer to the elements of an array to iterate over an array you could use the four of loop that we covered previously so just a quick reminder if I initialize the numbers array again 1 2 three four and five then I can do four can say let number of numbers and because I'm just going to use one line I don't need the curly braces just to Output that so here I see it outputed every element now there is another built-in method in the array class known as for each so the argument that you would pass into the method is a callback function so if I did numbers. 4 each in camel case then as the argument I can pass in an arrow function specify the number then the arrow and the curly braces then I can console. log the number so if I put that I get the same result since this codeb only includes one statement I could put everything on one line to simplify it so if an error function only has has one parameter then you can remove the parentheses around it helping clean it up even more the 4 method also accepts an optional second parameter which takes into account the index so here if I add that in then I can utilize that when I console log it so if I use template string then I can say at index specified here and then colon and then I'll specify the number at that index so if I log in out then I can see what value is stored at each index how would you iterate through an array you could use the four of loop to iterate through all the elements of an array you could also use the builtin for each method you would pass in a function as an argument which will take an element as a parameter and optionally take in the index as a second parameter to transform an array into a string The Joint method can be utilize so if I initialize the array const numbers assigned to 1 2 3 4 and 5 I can convert that into a string so I can say const join numbers assigned to numbers. jooin so the joint method allows you to specify a separator as the argument and this separator will be placed in between the elements for an example of that it will take in a string and I will specify a comma as a separator then I can console log that console log join numbers open up the panel and I run it and here I see this has been outputed as a string where every element is separated by commas on the flip side the split method is available for Strings enabling the reversal of this process by transforming a string into an array so this will not alter the original string rather it will return an array so let's say if I comment this out so if I do const course name is assigned to JavaScript beginners then I can split up the words into parts and I can say course name. split and as the argument I can specify the separator as an empty string so because I specified an empty string as the separator what JavaScript would do is it will go from left to right and whenever it Encounters this value the empty space it will perform a split so this string will be converted into an array this word JavaScript will be at the zero index of that new array for will be at the first index and beginners will be at the second index so if I log that out console.log Parts output it here I see I've converted that string into an array so to show an example of how this can be useful consider the term of a URL slug so this refers to having a descriptive path in your url your uniform resource locator in url slugs words are separated by a hyphen so in order to perform this we can use the join method so the sentence JavaScript for beginers is what we want to include in our URL We performed a split based on whites space and stored it in an array now I want to join everything together with a hyphen so I can say const and I'll say URL slug is assigned to parts. jooin and I will specify The Hyphen character then I can output that opening up the panel and running it again here I see is now displaying each of the words separated by hyphen now let's say we want to make every word in the sentence lowercase so the simplest way to do that will be to use the two lowercase method in the string class so before performing the split I can say cons and I'll call it lowercase course name is assigned to course name. two lowercase then I can utilize this variable for performing the split so now if I output it and now displays all the words in lowercase and separated by hyphen so we can clean up our code even more here we have course name it's assigned to a string then we call do to lowercase assigning the value to this variable which is a string data type then we call the split method to convert it into an array we can actually clean up these two lines by utilizing something called method chaining so I'll add some spacing to make it more readable and I'll comment this out and show how we can do it with cleaner code so if I do cons parts and assign to course name do2 lowercase so this is still the string data type so I can call Dot split and specify the separator this enables us to implement the same functionality in one line often times when we do method chaining we would add the method calls to their own line so I can add a new line and then tab and the same thing with the split method so when performing method chaining and calling one method after another we often put it on its own line and we're able to do this because they are all the same data type in this case the string data type how does the join method work the join method is available for arrays in order to convert the elements into a string it accepts an argument where you can specify what the separator will be and that separator will be placed in between the elements for the string that it returns how does the split method work the split method exists for the string data type you specify the separator and then it will convert the string into an array [Music] in programming sorting is a common operation JavaScript arrays come with a built-in sort method that allows you to easily sort the array Elements by default when you call sort on an array containing strings or numbers it sorts the elements in ascending order let's see this an action if I initialize this array let characters assign to c d b and a in order to sort these elements we simply need to call the built-in sort method so I can say characters. sort and then I'll log it out console.log characters and we will see it sorted in ascending order so here if I do node arrays. js we see the elements have been sorted another useful method in the array data structure is the reverse method so this can be used to reverse the order of the elements so rather than sort if I say reverse here we will see these elements updated in reverse order so if I output that here I see the array has been updated with the order reversed so if I switch back back to the sort method this approach Works seamlessly for arrays containing strings or numbers however when you have an array of objects you need to provide a callback function to the sort method this function defines the Sorting logic based on the properties of the object in the array so I'll clear this out and let's consider an array of employee objects so if I say let employees and within it I'll specify an object with an ID of one and a name of gen then I'll copy and I'll create four more elements so if I do shift option and down arrow creating former elements and I'll update the IDS to be two 3 and four and for the name I'll say Steven then Andrew then Terry and I end it with the semicolon so here I see these objects are ordered based on the ID however if I want to sort it based on the names then I need to specify a callback function in that callback function I will specify two parameters which represents two elements in this case two objects being compared so if I do employees sort now I can name these parameters whatever I want in this case I'll just name it A and B then I'll specify the arrow function and the curly braces so in our callback function we will compare values based on one of the object's properties so in this case we will use the name property the Callback function returns a number that determines the short order returning a negative value means the first argument in this case a comes before the second argument returning zero means that they are considered equal and in sorted order returning a positive value means that the first argument a comes after a second so since we'll will be sorting based on the name property we'll be performing a comparison based on these characters now characters are internally represented as numbers in computers based on their ask key values this means capital letters are considered less than lowercase letters to handle case sensitivity it's a good practice to convert strings to the same case for comparison so let's Implement our callback function so first I'll make it all lowercase so I can say const lower case a is assigned to a then the name property of that object and then I'll call two lowercase which is a built-in method for Strings then I'll just copy this with shift option and down arrow and I'll name it lower case b and then I'll change the object that we're using B then I can perform the comparison using the comparison operators so if I do if lowercase a is less than lowercase b in this case we will return1 which means that the object to a will come before the object to B so for example if we consider the object a to be this first object and we consider B to be the object just after it we are comparing these two name properties and because we determine gen to come before the name Steven returning a negative value means that object a comes before object B so we compare two elements at a time now in the case when if lowercase a is greater than lowercase b then we return a positive value which means that a comes after the object B otherwise if they are equal then we return zero so this callback function will be used to sort the objects in our array so now if I console log employees I will see that they are sorted alphabetically based on the name property so now I'll put it console.log employees open up the panel and we'll clear it and then we'll run it so here I see the objects are sorted alphabetically how would you sort the elements of an array you can use the built-in sort method to sort the elements of an array you can simply invoke the sort method if the array consisted of elements that are strings or numbers however if the array consists of elements which are objects then you need to specify a callback function this callback function will accept two parameters representing two objects to compare and you would compare those objects based on their properties in JavaScript arrays come equipped with several powerful methods that allow us to process and evaluate the data within them efficiently two such methods are every and sum both of which are used to test elements in an array against a condition let's explore how each of these methods work and when to use them starting with the every method the every method tests whether all elements in Array pass the test implemented by the provided function it returns true if every element in the array satisfies the specified condition and false otherwise this method is perfect for scenarios when you need to ensure that an entire collection meets a certain criteria for example let's check if every number in an array is even so let's instantiate an array of numbers I'll say const numbers assigned to 2 4 6 8 and 10 so I will store the result in a variable R all even which will hold a Boolean value this is assigned to the result of numbers every so when I hover over every I see that it accepts a callback function which is a predicate so this callback function must return true or false and it can accept up to three parameters the first parameter is the current element of the array the second parameter is the index of where the element is stored and the third parameter is the original array of these three parameters only the first one is mandatory and the other two are optional in this case I only the first parameter so I'll name it number then I'll use the arrow function syntax the curly braces and then I will return when that number mod 2 is equal to zero then we know that it is even so I can console log are all even console. log I use my template string R all even callon and then I use string interpolation R all even end it with a semi colon and then we'll log this out up arrow and here I see the value true so we know all the elements are even so because our code block just consists of one statement we can clean it up and put everything on one line so here if I run it again get the same result now let's consider the sum method on the flip side the sum method checks if at least one element in the array passes the test implemented by the provided function it returns true as soon as one element satisfies the condition making it useful for scenarios when you're looking for the presence of an element that meets a specific requirement so let's instantiate an array and say cons numbers sign to 1 3 5 7 8 and 9 I will store the value in a variable has one even number which holds the bulling result and then I'll say numbers. sum so once again this predicate callback function accepts up to three parameters in this case we only need the first one which is the element that we're operating on and I'll name it number and I'll use the arrow function syntax and I will check number mod 2 is equal to Z then I can log that out console. log template string again has one even number colon and then interpolation has one even number ending with a semicolon and let's output that so here I see the value true because this array has the value of eight it's important to note that both the every and some methods operate on arrays in a way that they stop processing elements as soon as the outcome is determined for every it stops and returns false as soon as it encounters an element that does not meet the condition some stops and returns true at the first instance of an element that satisfies the condition these methods are incredibly useful for array processing in JavaScript providing a concise and readable way to evaluate conditions across array elements whether you're checking for consistency with every or searching for possibilities with some these methods offer elegant solutions to Common programming scenarios what is the every method and how does it work the every method is a built-in method in the array data structure and a test whether every single element in an array satisfies a specified condition what is the sum method and how does it work the sum method is a built-in method in the array data structure it returns true if at least one of the elements in the array passes a particular condition and false otherwise one of the most versatile built-in methods for arrays in JavaScript is the filter method this method is designed to go through an array and extract elements that meet a specific condition returning a new array comprised of only those elements it's particularly useful for creating subsets of an array that match certain criteria so consider an array of numbers find instantiate con numbers S 2 1 2 3 4 5 and six if we want to filter the array so that we only have the even numbers we can use the filter method so I can say con even numbers sign to numbers. filter so the filter method works by by accepting a callback function and this function acts as a test often called a predicate function that returns a Boolean value so it returns true or false for each element in the original array the filter method calls this callback function and if the Callback function returns true for an element that element is included in the new array returned by filter if false the element is excluded so I will specify my callback function to be number and I'll use the arrow function syntax so number mod 2 equal to Z so if this is true then we know that the value is even it will be included an even numbers so let's console log that console.log even numbers then run in the panel so here I see the array consist of only the even values so let's look at a more complex example involving an array of objects which is a more common use case for worldw projects thr this out and I'll State an array containing objects so I'll say const employees assign to the array then I'll specify the object ID of one the name of Alice and the role of a developer comma and then shift option and down arrow to create more copies update the IDS and the names I'll say Bob I'll say Charlie and I'll say Danielle update their roles so designer developer and manager so now I want to filter so that we only contain the developers so I'll say developers equals employees filter then I'll specify my callback function I'll name it employee for the element and then when the employee. roll is equal to developer then it will be included in the developer's array I'll outp put this developers and then when we run in the panel here I see both employees with the role of developer are included this demonstrates the filter method's power to work with arrays containing objects and utilizing the objects properties to make very specific selections so the filter method is non-destructive and it does not change the original array instead it creates a new array with elements that pass that test or that match the [Music] criteria how would you filter the elements of an array you would use the built-in filter method and specify a callback function in that callback function you would specify what condition You Want To Be True in order for that element to be included in the array to return the map method is a Cornerstone of array manipulation in JavaScript offering a powerful way to process and transform array elements it operates on each element of an array applying a function you specify and returns a new array composed of the results this makes map an Ideal tool for a transforming data without altering the original array imagine map as a transformative method you give it an array and a transformation Rule and it gives back a new array where each element has been changed according to that rule let's start with a simple example squaring each number in Array of numbers so if I initialize con numbers assign to 2 4 6 8 and 10 using the map method I'll store the result in square numbers sign to numbers. map I'll specify my call back function I'll say num the arrow function num * num in this case map takes each number squares it and includes the result in the new array here if I log it out console.log square numbers opening up the panel or run this file and here I see each value has been squared let's consider another example transforming strings so I'll delete this so map is not limited to numbers it works with any data type so for this example we will convert an array of characters into uppercase characters so let say con characters assigned to a b c and d I'll store the result in uppercase characters that's equal to to characters map for the Callback function I'll specify the element to be character map to character. 2 uppercase ending with a semicolon so now console.log it console.log uppercase characters then I run in the panel so here I see each element has been converted to uppercase I'll clear this out so now I'll show an example working with objects so when using the map method with objects this enables us to update Properties or transform objects entirely for instance if you have an array of employee objects and you need to normalize their email address to lowercase for consistent databased storage map makes this task easy to do so if I initialize const employees to an array and I'll say ID is one name is Alice and email his mixed case so I'll say Alice at gmail.com just in case their email was entered in and mixed case I'll make two more copies and update the IDS and the names so here I'll say Steven and I'll say Joe and for the email I'll say say and mix case and Joe ending with the semicolon so now for performing the map I'll say cons updated employees assign to employees. map un name the parameter to be employee Arrow function and here I'll do a parenthesis and then curly brace so the curly brace is for the object literal that I'll be returning so I'll use the spread operator employee so the spread operator copies over all of the properties into this new object that we are returning now I want to update the email property such that all lowercase so I can do email call in and then I'll do employee. email. to lowercase so in this example map iterates over each employee object creating a new object that preserves the original properties while transforming the emo property to lowercase the use of the spread operator ensures that we're not modifying the original objects showcasing the map's utility and creating modified copies of objects while leaving the originalr right untouched so let's console log that console.log of update employees open up the panel up arrow and run it and here we see update employees shows all the emails and lowercase how would you transform or map over each element of an array you can use the built-in map method with that method you would specify a callback function where you will operate on each element and transform it in some way this would result in creating a new array consisting of those updated values JavaScript has a very powerful array method called reduce it can transform an array into just about anything whether that be a single number a string an object or even another array let's see how this works with a practical example let's consider an array of numbers and we want to calculate their sum here's how you would traditionally implement it instantiate Con numbers and assign to 1 10 5 and 14 then I can initialize the sum and set it to zero then I can use the four of loop to iterate through all the elements in this array so I can say four const num of numbers then I can do sum plus equals num now I can console log that console.log our template string I'll say total sum colon using interpolation say the sum end it with the semicolon and let's run in the panel here I see the total sum is 30 now this approach calculates the sum but JavaScript offers a cleaner way to achieve the same result using the reduce method so I comment this out the reduce method iterates over each element in the array applying a function that you define and accumulates the results into a single value here's how you can use the reduce method to sum an array of numbers so on a new line I'll say con sum is assign to numbers. reduce then specify two parameters the accumulator and the current value using the arrow function syntax ending it with the semicolon then I will return the accumulator plus the current value so the first argument that we specify for the reduce method is this callback function it also accepts a second optional argument which is the initial value of the accumulator so I'll set that to be zero as the initial starting value so a reducer function is called for each element in the array this function receives two parameters the accumulator which is the accumulated result of the previous function calls and the current value which is the current array element being processed the initial value for the accumulator in our case is zero because we're summing the numbers starting from zero the reducer functions job is to combine the accumulator and the current value in some way then return the result which becomes the accumulator value for the the next iteration once reduce has processed every element in the array it Returns the final accumulator value providing initial value is optional if you don't include it reduce will use the first element of the array as the initial accumulator value and start iterating from the second element however it's a good practice to always specify the initial value to avoid unexpected results especially when working with empty arrays or arrays containing elements of different types so I'll copy this console log and I'll put it just to ensure that we get the same value I run the panel we get the sum of 30 so I can comment this out and here is a simplified version of the sum calculation without explicitly providing an initial value so I can do sum assign to numbers. reduce specifying the accumulator as the first parameter then the current value Arrow function syntax and then accumulator plus the current value ending it with a semicolon now I can run in the panel and we get the same result [Music] what is the reduceed method and how does it work the reduce method is a built-in method for the array data structure that reduces all the elements of an array into a single value this value could be a number a string an object or another array it accepts two possible parameters so for the first parameter you would specify a callback function this callback function will accept two parameters the accumulator and the current value now reduce also accepts an optional second parameter you can supply the initial starting value for the accumulator functions are the Cornerstone of JavaScript serving as reusable code blocks in JavaScript functions are objects let's explore two primary methods to create functions in JavaScript through function declaration syntax and function expression syntax I'll rename my file to functions starting with function declarations here we utilize the function keyword a key characteristic of function declarations is their Simplicity and the absence of a semicolon at the end for example you do fun function say hi parentheses and then console.log hi then I can invoke it just say say hi let run in the panel I'll say node functions. js and here I see executed the statement within the code block so this syntax is straightforward and efficient for defining functions now we also have function Expressions which introduce a different approach we close the panel and I'll delete this so now implement it with function expression syntax I'll say let say hi is a assign to function then our curly braces I'll say console. log of high and I'll end the curly braces with the semicolon so in this case we Define an anonymous function which does not have an Associated name and we assign it to a variable say hi note that functions are objects in JavaScript so now I can invoke it say hi running in the panel and we get the same result so if I close this some function Expressions could also be named so rather than using an anonymous function let's say if I were to change the name name with this variable to greeting and I make this a name function and call it say hi and to invoke it I'll just use greeting and then the parentheses so this provides the flexibility of an expression and the clarity of a name function so in this scenario greeting acts as a reference to our function treating it as an object then to execute this function we simply invoke greeting here I just output it again and we get the same result in summary JavaScript functions whether using function declaration syntax or function expression syntax form the building blocks of our applications what are function declarations function declarations are the traditional syntax to create functions in JavaScript You' use the function keyword and then name the function specifying a parameter list and then the implementation within curly braces what are function Expressions function expressions are an alternative syntax in JavaScript where you would imp a function whether it be an anonymous function or a name function and assign it to a variable we can do this in JavaScript since functions are objects in the previous lesson we covered two different ways for creating functions in JavaScript the function declaration syntax and the function expression syntax a key difference between these lies in their behavior related to hoisting to illustrate this let's consider function declaration first so Implement a function call it add and it will accept two parameters num one and num two curly braces and we'll just console log the output console.log num one plus num 2 now to invoke it I'll just do add then I'll do two plus two and let's output that so we see the output is four now with this approach using the function declaration syntax JavaScript allows us to call or invoke the function before it's defined in the code so rather than invoking it after its declaration I can move it before its declaration and this approach would still work so if I output it we get the same result this is due to a JavaScript mechanism known as hoisting hoisting is a process where the JavaScript engine automatically moves all function declarations to the top of their scope before code execution this means that no matter where functions are declared they are moved to the top of their enclosing scope allowing them to be called before they're defined in the program however this doesn't apply to function Expressions so if I try this with the function expression syntax closing the panel I'll comment this out so if I do let add is assigned to Anonymous function with the same parameter list num one and num two and I'll just copy and paste this console log now if I try running it clear this and run it this code results in a reference eror because we cannot access and invoke ad before its initialization the reason is that function expressions are not hoisted in the same way as function declarations since ad is defined using a let variable assignment it cannot be accessed until the execution reaches the point where it is defined in summary hoisting allows function declarations to be lifted to the top of their scope making them available throughout their enclosing scope what is [Music] hoisting function hoisting refers to a JavaScript mechanism where function declarations are moved to the top of their containing scope during the compilation phase this allows you to call or invoke the function anywhere within its enclosing scope let's dive into how functions handle arguments in JavaScript using a simple example here Implement function I'll name it multiply it will accept two num one and num two curly braces and then we'll just return the product so num one * num two now if I invoke it console. log multiply and then 2 * 2 add in semicolon so we can output it so we get the output of four so when we call this function we Supply two arguments in each parameter is assigned to one of these arguments leading to the expected multiplication result but if we were to call this and only pass one ARG arent for example if I remove this second argument and I call it again I get the value of not a number in this case since we didn't Supply two arguments and didn't Supply an argument for the parameter num two then num two will be assigned the value of undefined by default so in JavaScript any parameter that doesn't receive an explicit argument is automatically assigned to the value undefined this default Behavior ensures that functions don't break even when they receive fewer arguments than expected though it may lead to unexpected results in your functions JavaScript functions are quite flexible with a number of arguments you pass to them you can even pass more arguments than there are parameters defined so for example if I pass in two and say if I pass in the value four if I were to call it again here I get the expected result without an error now to actually make use of all these arguments we can leverage the arguments object every function in JavaScript has access to a special object named arguments which captures all the arguments pass to the function so let's see an example of that here if I just console log the arguments object arguments opening up the panel we'll clear this then we'll log it again so here I see this outputs the argument object in this object the keys refer to the index position of the parameter and its corresponding argument value if we want our function to support any number of arguments we can iterate over the arguments object I close the panel I delete our statements in the code block then I'll declare let product assign to one then I'll utilize our four of loop so four I'll say con num of arguments and within it I'll do product times equal the num then I return the product so with this setup our multiply function can now handle two three or even 10 arguments multiplying them all together the argument's object is iterable allowing us to Loop over it with the four of syntax it's important to note that while arguments is array likee it's not a natural array this means that it has some array behaviors like being iterable in having a length property but lacks array methods like map or reduce here I'll clear the panel and just log it out and here I see the result of multiplying 2 * 2 * 4 by understanding the argument object you can create more flexible functions in JavaScript capable of handling a variable number of arguments seamlessly note that we don't often use the arguments object but I wanted to cover it so that you're aware of [Music] it what happens if a function is called with fewer arguments than expects to receive if a function is called with fewer arguments than it expects then the parameters that you didn't Supply a value to will be assigned the value of undefine by default this could lead to unexpected results in your functions previously we covered the spread operator which is used for cloning objects in JavaScript for example if I create the object literal let course sign to the object with a name JavaScript for beginners I'll say duration 3 hours end it with a semicolon now I can make a copy of this let's say if I do let new course assign to object literal then the spread operator with three dots and then the object that I want to copy so if I lck this out new course opening up the panel and running it this outputs a copy of this object so the Sprint operator allows us to easily copy properties from one object to another now if you want to modify the name name property in the process we could do so by put this on new line comma and then I'll do name and I'll change the name to be JavaScript Pro for the name of the course I'll just add the spacing here now if I to the panel and I run it again here I see the name property has been updated so now let's pivot to a similar but distinct use of this syntax in the context of functions so when we use this dot dot dot operator functions we refer to it as the rest operator so unlike the spread operator which expands an array or object the rest operator allows us to gather a varying number of arguments into a single array parameter this is particularly useful when we want a function to accept an indefinite number of arguments so clear this out so consider this example I declare a function I name it multiply then for its parameter I can do dot dot dot args specify the code block I'll say return ARS do reduce so this name of args is arbitrary I can name it whatever I want so this allows me to specify a varying number of arguments which we packed into an array so I can use the array method reduce in order to reduce all the values in the array to a single value so in this case it will result in the product of multiplying all these numbers together so I can do accumulator and then current value the arrow function I'll close the sidebar so more room then I would do accumulator times current value then I'll specify the value of one as a starting value for the accumulator so now I'll put this console. log of multiply 1 2 3 and four so I'll run in the panel and here we get the value of 24 it's multiplying these arguments together so this shows an example of how we can use the rest operator in our parameter list so I clear this out close the panel let's consider another example see if I create a function I call it multiply again now for the first parameter I'll specify that to be multiplier and for the second parameter I'll specify that with the rest operator and I'll name that array numbers so then I'll specify return numbers map in my call back I'll specify number then number times multiplier ending it with the semicolon so this numbers parameter will gather any additional arguments passed into the function and store it in an array called numbers so if I were to use this I can say console.log multiply so for the first argument which be used as the multiplier let's say if I specify two then any subsequent value will be an element in the array numbers so I can do 1 2 3 and four ending with the semicolon now since I'm using the map function this will return a new array with these values being doubled so if I output that I get 2 4 6 and 8 so this demonstrates how the rest operator enables the multiply function to accept any number of arguments beyond the first multiplier parameter it's important to remember that if a function includes multiple parameters the rest parameter must be the last one in the parameter list ensuring it captures all remaining arguments also the name of the rest parameter can be anything whether it be numbers args or any identifier that makes sense in your functions context what is the rest operator the rest operator allows you to represent an indefinite number of arguments as an array this is useful when working with functions that can accept a variable number of arguments let's explore default parameters in JavaScript a feature that significantly enhances function flexibility let's start with a simple function if I use the function declaration syntax I'll say function write code and for the parameter I'll specify that to be language or curly braces and then I'll console log with back ticks I'll say write code in and then interpolation language end it with a semicolon and now I can invoke it so if I say write code for the argument I'll specify that to be JavaScript I run the panel so here we see a log to the console now let's say if I copy this shift option and down arrow and let's say if I do c as the programming language run it again so we implemented a reusable function but what if we were to call right code without any arguments say if I do shift option down again to copy it but I don't pass any arguments I'll clear this if I run it again here I see the last one is write code in undefined so without an argument this parameter is assign the value of undefined by default so this is where default parameters may be used in modern JavaScript we can assign a default value to parameters ensuring our function behaves predictively even when specific arguments aren't provided so here where I specify my parameter I can assign a default value in this case I'll say JavaScript so I'll clear this and if I run it again here I see the last output was write code in JavaScript since language has the default value assigned to JavaScript so let's clear this and let's do another example so now can consider a function with more than one parameter so I'll say function code details for the first parameter I'll use language and I'll have the default value of JavaScript I'll close the sidebar with command and B and I'll do tool is vs code our curly braces and now a console log back tick writing code in language using tool end it with the semicolon so if you set a default value for a parameter then any parameters that follow should also have default values this function has two parameters language and Tool both with default values so this design allows for versatile function calls so if I were to call it with no arguments I'll do another example specifying just one argument let's say if I do python then I'll specify c as the language and visual studio as the tool so if I output this and run it here I see for the first function call with no arguments pass it uses the default values so writing code and jav JavaScript using VSS code the second one I just supplied one argument so it's writing code in Python using VSS code and third one I supplied two arguments this outputed writing code in C using visual studio let's do one more example let's say if I do function create user the first parameter will be name the second parameter will be roll with the default value of guest the third parameter will be status and assign to active do my curly braces and then I'll console log it with back tick user call then the name comma the role and the status ending with the semicolon so now I can do create user and I'll specify the first argument since this parameter is mandatory so I'll say Steven and I'll do another example let's say if I specify the name to be Alice with the role of admin and the status is active here if I output it so for this function the role and the status parameters have defa values so this setup is practical for situations when you might not have all the details up front but still need to ensure your functions executes smoothly default parameters simplify function calls and make your JavaScript code more readable and maintainable especially when dealing with multiple parameters and the potential for missing arguments what are default parameters default parameters allow functions to have predefined values that are used if no argument is passed to the function fun let's dive into the use of Getters and Setters within JavaScript objects which enhance how we interact with object properties so let's Define a simple object I'll name it Con course assign to where the name is JavaScript for beginners and the duration is 3 hours we'll end it with a semicolon and we'll just console log it with back tick say course. name is course. a so output that so we see JavaScript for beginners is 3 hours so this basic approach allows us to access object properties directly however modern JavaScript offers more sophisticated mechanisms to interact with properties such as with methods so if I close this so I'll specify a method in my object I'll name it details and I'll say return back ticks I'll say this as in this current object name is this do ation ending with the semicon so I comment this out I can instead do console.log of course. details for calling that method so if I run this again I'll get the same output so while this details method effectively encapsulates the way we describe a course it's readon so we can't directly modify the course details using this method so this is where Getters and Setters can come in so these special methods allow us to Define custom Logic for reading and writing properties they're defined using the get and set keyword and are used as if they were regular properties so to turn this method into a getter I would use the keyword get before the method name so to specify a Setter I'll do comma and I'll say set details for the parameter that'll be a value so what this allows us to use this method as if it were a property of the JavaScript object so this Setter can be used to be assigned to a value like JavaScript for beginners is 3 hours so a value were to hold this string we would need to break it up and store it in our properties so I can say let Parts is assigned to Value calling the split method which exists for Strings and I'll specify the separator as the space is and then another space so that will break this string up into an array and I can access the elements of the array to update these properties so I can say this fat name assign to Parts at the first index then I can say this do duration is assigned to Parts at the second index at the index of one clear this out so since this is a getter it will act as if it is a property rather than a method so in order to call this I won't need to use the parentheses so I'll put that and when I run it I get the same result now if I already use the setter which is this method we defin here I can say course. details is assigned to I'll say JavaScript Pro is 10 hours now for to access the details of this course I can copy this paste it here and I'll comment this out so let's let's run it again so here I see my properties have been updated and so when I call details this outputs JavaScript Pro is 10 hours so in this enhanced example the getter for detos simply formats and Returns the course information and we're able to access it as if it were a property rather than a method now the setter for details takes a string splits it and updates both the name and duration of the course object it allows us to modify the course's details in a controlled manner Getters and Setters provide a powerful way to create virtual properties that you can read and set like standard properties but with additional logic behind them this feature is especially useful for validation logging and dynamically computed properties remember while Getters and Setters make your objects more robust and encapsulated they also introduce a layer of abstraction that can make debugging more challenging if not used carefully what are the get and set keywords the get and set keywords can be used within object literals or classes in order to Define Getters and Setters this enables you to use a method as if it were a property the benefit of using Getters and Setters is that it can improve data encapsulation and provide a more intuitive interface for interacting with an object's properties in this lesson we'll explore the powerful concept of error handling in JavaScript particularly through the use of Tri catch blocks so let's consider an object course with a getter and Setter for its details property now for this parameter variable that we specify for our Setter there's no guarantee that this value is a string data type for example someone could do course. details and assign it to a number for example so we want to check Ure this parameter is a string so I can check if type of value is not equal to a string then in this case we can just return and stop execution now while this code will prevent the air being thrown there are cases when you want to throw an air in programming we'll call this throwing an exception so here I'll do curly braces and instead I'll do throw new error and I'll specify the message to be value and the value is not a string so now the programmer who is utilizing the setter will now get an exception an error saying that the value they assign it to is not a string so now if I run this with node functions. js then it throws this exception so by implementing this check in our Setter we can throw an exception when the value isn't a string thus preventing unexpected behavior however simply throwing an error halts our program's execution and reports the error which isn't always the desired outcome so in JavaScript errors are objects and when thrown they create exceptions now we don't want unhandled exceptions to terminate our program abruptly so this is where TR catch blocks come into play allowing us to gracefully handle errors so I'll close the panel here when we perform this operation I can wrap it in try catch blocks so I'll do the try keyword curly braces and I'll move this code within this block So within this code block we would Place statements that could potentially throw an exception now if an exception is thrown then we want to catch it I can name this e for error or E for exception so this will allow us to catch the exception without terminating our program so you're going output console.log a descriptive error message so I can say CAU an error and here I'll just say e. message which is a property that exists for errors so now if I run it run the panel so here I see this outputed this airor message rather than terminating the program so to reiterate the catch block specified here catches with the thrown error enabling us to handle it and log it to the console without stopping the program so this pattern of defensive programming particularly the use of Tri catch blocks is crucial for creating robust JavaScript applications it allows us to manage errors effectively ensuring our programs can recover from unexpected situations [Music] gracefully what are Tri catch blocks Tri catch blocks are used for defensive programming in the case when you are executing code that may throw an exception this enables you to catch the exception in order to prevent your program from crashing let's cover the concepts of local scope versus global scope in JavaScript first let's discuss the global scope so a variable declared outside any function block or conditional has a global scope meaning it's accessible from any part of the code after its declaration so CH 2 con's name and the sign two Steven and and just console log it the name we output it and we get our expected string so here this variable is declared in the global scope it's within Global reach meaning any script or function can access it conversely local scope refers to variables declared within a block function or conditional so these variables are only accessible within the confines of their curly braces so I for instead wrap this in a curly brace to Def a block I'll highlight this and do command then the right square bracket to indent it now if I run again I get the same result however if I were to move this console lock statement outside of the code block and if I run again I got a reference there saying that the name is not defined so since we declared this variable within this code block it only exist and is accessible within the Block it's defined in and outside of it is not accessible leading to a reference eror so the scope of a variable determines it's accessibility so declaring variables locally within a specific context rather than globally is generally considered best practice for several reasons one is for avoiding Global pollution Global variables can lead to conflicts especially in large applications or when integrating with third party libraries another reason is maintaining code Clarity local variables ensure data is only accessible where it's needed making the code easier to understand and debug another reason is enhancing performance JavaScript engines can optimize the look of time for local variables better than for Global variables to further illustrate let's see how this works within a function I'll clear this out and I'll close the panel so if I I name a function I'll call it GRE and within it I'll say cons message is assigned to hello world and then I'll conso log this message now when I invoke GRE I'll get the expected console log statement however if I were try to access this variable message say if I do console.log of message and then I run it here I see another reference error saying that the message variable is not defined so this shows that this variable is local to the Greet function it's created when the Greet function is invoked seases to exist after the function completes keeping our Global namespace clean and our code predictable understanding the distinction between local and Global scope is fundamental in JavaScript it helps in structuring your code more effectively preventing accidental data modification and keeping your Global namespace uncluttered always aim to minimize the use of global variables and leverage local scope whenever possible for more maintainable and airror free [Music] code what is the difference between the global scope and the local scope in JavaScript the scope of a variable determines where it can be accessed within the code variables declared outside any function or block are in the global scope making them accessible throughout the entire script in contrast variables declared within a function or block such as Loops or conditional statements are in local scope meaning they are only accessible within that specific Block in this lesson I will discuss the differences between the let and VAR keywords in JavaScript highlighting why modern practices favor the let and cons keyword rather than the VAR keyword in JavaScript versions prior to es6 which stands for ecmascript 2015 the VAR keyword was primarily used to declare variables however the introduction of es6 brought significant improvements including the addition of the let and cons keywords for variable declarations these were introduced to address some of the issues associated with the VAR keyword so the VAR keyword is function scoped meaning that it is only scoped to the function within which it is defined not to any blocks within that function like Loops or conditionals this can lead to unexpected behavior and errors in your code so consider this example using the VAR keyword part to create a function and name it display and if I were to implement a traditional for Loop I'll say four VAR I is assigned to zero I is less than 5 I increments and I'll console log that so if I were also to console log outside of this for Loop the value of I so if I were to invoke it and run it in the panel here I see within my for Loop this outputs the values of 0 to 4 and continues as long as the value of I is less than 5 however I'm still able to access this variable outside of this code block as seen in the outputting of the value of five so in this scenario the variable I which is declared inside a for Loop is accessible outside of the loop block because VAR does not have block scope but rather it is function scope the let keyword in the other hand introduces block scoping to JavaScript this means that a variable declared with let is only accessible within the block it was defined in so to update this to be the let keyword and run it here I see what output every value in the loop however when I try to access this variable outside of the code block then it would throw an exception saying that I is not defined so to reiterate in this version of display attempting to access the variable I outside its defining scope which is the for Loop in this case results in a reference air showcasing that it's a block level scope so why does this matter we want to minimize the global scope pollution and using let helps avoid adding unnecessary variables to the global scope which could conflict with other scripts or third party libraries using the let and cons keyword also helps us reduce our errors so block scoping makes it easier to track where variables are available reducing the risk of accidentally overwriting or misusing variables it also helps improve code readability so code that takes advantage of block scoping is often easier to read and understand as it's clearer where each variable is defined so while VAR has its place in JavaScript history the introduction of the let and cons keyword has provided developers with more robust tools for variable declaration by understanding and utilizing the let and cons keyword and their block scope nature you can write cleaner more reliable jwarp code what is the difference between the let keyword and the VAR key keyword both the Le keyword and the VAR keyword can be used to declare a variable the let keyword is the modern way to declare a variable and it was introduced in es6 the difference is that the let keyword is block scoped and the VAR keyword is function scoped with the let keyword the variable will be accessible within the block it is defined in with the VAR keyword the variable will be accessible within the function it is Def finded in in this lesson we will cover the this keyword in JavaScript understanding that this keyword is crucial because it refers to the object that is currently executing the function or method in JavaScript the value of this depends on the context in which a function is called not where it's declared so let's break this down if I create an object name it course with the name JavaScript for beginners and if I declare a method I'll name it start console.log of this.name now I were to call this method I'll say course do start and if I output that I get JavaScript for beginners so in this example the this keyword points to this course object allowing us to access the name property of course in a regular function meaning not a method of an object that this keyword will reference the global object in browsers it's the window object and in node.js it's the global object so if I to move this and then say create a function and call it start video and here I'll just console log this so I'll call this function call start video and I'll execute it scrolling up so since I executed this with node.js this outputed the global object and in browsers this would output the window object let me clear this out so that covers the function declaration syntax Now Arrow functions don't have their own this context instead they inherit this from the parent scope at the time they are defined so far Crea another object say con course assign to the name es6 syntax then start and I'll have that use an arrow function parenthesis the arrow curly braces this will console.log this.name so now if I use that course. start when I invoke it here I see this do name is undefined this is because when using the arrow function the this. keyword inherits from its parent scope so in this case from the global object and since the global object doesn't have a name property this value would be undefined now you can explicitly set the value of this using bind so bind returns a new function with this bound to a specific object but doesn't immediately invoke it so if I were to clear this to demonstrate that close in the panel so if I create a function and I'll name it introduce with the parameter of language I'll do console.log I'll say this.name then using catenation say teaches language so for to create an object I'll say instructor sign to my name now this function introduce has a bind method so if for to say cons introduction is assigned to introduce bind then I'll pass in this object and of the semicolon then if I were to invoke it using introduction introduction for the language I'll specify that to be JavaScript ending with a semiconon and if I output it here I see the string Steven teaches JavaScript so performing the bind this specifies this.name which is binded to this object so the this keyword in JavaScript plays a critical role in determining the context of function execution its value is determined by the execution context or explicitly bound using bind understanding and mastering this allows for more flexible and Powerful code structures especially when working with object or in a JavaScript how would you explicitly set the value of the dis keyword for a function or method in JavaScript to explicitly set the value of the this keyword for a function you can use the bind method the bind method creates a new function that when called has its this keyword set to the provided value this allows you to call a function with this set to a specific object even if the function is defined in a different context if you're interested in supporting my courses and projects you can follow me on my new YouTube channel and Instagram at Steven codecraft and if you're looking to enhance your health and fitness routine check out my workout and meal planning app at fitfuel planner.com the app offers over 100 recipes workout plans meal plans and a grocery list feature it's designed to make tracking your calories and macronutrients straightforward and stressfree I appreciate your support