Introduction To JavaScript and Course Overview
Introduction To JavaScript and Course Overview
•In this complete JavaScript course, we will learn how to build complex websites using
JavaScript from beginner to professional level.
•We will build an interactive multi-page website, similar to amazon.com, where we can add
products to our cart, create orders, and track our order.
•Alongside, we will also build smaller projects like a rock paper scissors game, a to-do list,
and a calculator.
•The course will cover the fundamentals of JavaScript and its major features.
•We will also learn how to use JavaScript with HTML and CSS.
•Part one of the course focuses on the basics of JavaScript and its integration with other
technologies.
•Part two covers skills essential for bigger and more complex projects, culminating in the final
Amazon project.
•Solutions for any issues can be found in the first comment below the video, with the option
to ask questions for additional help.
•JavaScript is a technology used to create websites, working alongside HTML and CSS.
•HTML creates the website's content, including buttons, text, and images.
•JavaScript enables interactivity on the website, allowing for actions when buttons are
clicked.
•To begin learning JavaScript, we need to install a web browser like Google Chrome,
which is commonly used for web development.
•If Chrome is not available, we can use Microsoft Edge for Windows or Safari for
Mac.
•Opening google.com and searching for Google Chrome will allow us to download
and install it.
•JavaScript involves giving instructions to a computer, which the computer will then
follow.
•We can start by opening Google Chrome and typing super simple.dev/j-basics in the
address bar.
•To give instructions, we right-click on a blank area of the webpage, select "inspect,"
and click on the console tab.
•The first instruction we learn is to create a pop-up with the text "hello" using the
alert() function.
•Another instruction is to create a pop-up with the text "good job" using the same
alert() function.
Introduction to JavaScript and its functions
•The instructions given to the computer are called code, and when the computer
follows these instructions, it is called running the code.
•JavaScript is one of many programming languages that can be used to write code.
•By using JavaScript code, various tasks can be accomplished, such as performing
mathematical calculations or modifying webpages.
•JavaScript is case sensitive, so the correct syntax and punctuation must be used.
•Code examples and further explanations can be found in the video description.
•In the code "alert('hello')", the brackets and quotes have specific meanings that will
be explained later.
Syntax and Basics of JavaScript
•Syntax are the rules to follow when using a programming language like JavaScript.
•In English, we have rules of grammar, but in programming, we must follow syntax
rules exactly.
•Not following syntax rules will cause a syntax error, making the computer unable to
understand the code.
•JavaScript has many syntax rules, but we will learn them gradually throughout the
course.
•The code "alert('Hello');" creates a pop-up with the text inside the quotes.
•Changing the text inside the quotes changes the text inside the pop-up or on the
page.
•JavaScript gives instructions to a computer and we ran our first JavaScript code
using the browser's console.
•We can close the console and open a project named "super
simple.dev/projects/amazon" to continue the lesson.
Learning Math and Calculating Costs in JavaScript
•The webpage allows users to view products in the cart and make modifications. It
also includes a section to calculate the cost of the cart, including the cost of products,
shipping, and taxes.
•To access JavaScript code, right-click on a blank area of the webpage, click inspect,
and then click the console.
•The syntax for math in JavaScript is the same as normal math expressions.
•To calculate the cost of products before shipping and taxes, add the cost of each
individual product.
•The cost of two socks at $10.90 each is multiplied by two and then added to the cost
of the basketball at $20.95.
Introduction to Math and Order of Operations in JavaScript
•Pressing enter in JavaScript performs math calculations and displays the result.
•In JavaScript, multiplication and division are performed before addition and
subtraction.
•Brackets can be used to group calculations and control the order of operations.
•The text discusses the importance of correct syntax in calculations and mentions
that incomplete calculations can lead to errors.
•The author suggests doing some setup in the final project, removing all products in
the cart, and adding new products such as one basketball and two t-shirts.
•After going back to the cart, the author explains how to calculate the cost of the
products by adding the cost of the basketball ($20.95) and the cost of the t-shirts
($7.99, multiplied by 2).
•The author demonstrates the use of the order of operations, where the multiplication
of the t-shirts' cost ($7.99 * 2) is done before adding the cost of the basketball.
•The text then introduces the calculation of a 10% tax, explaining that 1% is equal to
one divided by 100 and 10% is equal to 10 divided by 100, which is 0.1.
•The author demonstrates how to calculate the 10% tax manually by multiplying the
total cost ($36.93) by 10%.
•It is noted that the calculated number is slightly different from the displayed amount
on the webpage, and rounding will be covered in a later lesson.
•The text mentions the need to calculate the tax individually by adding the cost of the
basketball to the cost of the t-shirts (multiplied by 2) and then multiplying the sum by
the tax percent (0.1).
•It is acknowledged that this method does not produce the same result as the
previous calculation due to the order of operations - multiplication is done first.
Arithmetic Operations and Float Inaccuracies in JavaScript
•To calculate the cost of products and apply a tax percentage, brackets can be used
to control the order of operations.
•Brackets ensure that the calculation inside them is performed first, followed by the
remaining operations.
•Floating point numbers are decimal numbers and are stored differently in computers,
leading to discrepancies.
•Inaccurate results occur due to the mismatch between the number systems used by
computers and humans.
•Inaccuracies can be avoided by being aware of how floats are stored and using
alternative approaches when dealing with monetary calculations.
Calculation and rounding in JavaScript
•In order to set up the shopping cart, ensure it contains one basketball with free
shipping and one t-shirt.
•Click "update", change the quantity of the t-shirt to one, and save the changes.
•To convert back to dollars, use brackets to calculate the total in cents and then
divide by 100.
•To round a number down, input the number into the function inside the brackets.
•To round a number up, input the number into the function inside the brackets.
•Practical example: Calculate the tax by multiplying the total cost in cents by 0.1 and
rounding the result.
Using Math.round function in JavaScript
•The inner brackets are calculated first and then the outer brackets, followed by the
rest of the calculation.
•The result obtained is 2.894, which is close to the given number on the page.
•The Math.round function is used to round the number to exactly 2.89.
•Rounding the entire calculation would result in rounding 2.89423 to the nearest
integer.
•However, the number to be rounded is specifically 289.40 cents, which rounds down
to 289 cents or $2.89.
•The calculation is rounded using Math.round function without the need for extra
brackets.
•In JavaScript, most math operations are simpler than this example.
Working with Code and Text in JavaScript
•When searching for code on Google, don't worry if you don't understand all the code
you find. Look for familiar parts that you can use.
•In this lesson, the focus was on working with numbers and math operations.
•Float calculations can be inaccurate, and math dot round was introduced to round
numbers.
•The ability to work with text in JavaScript was introduced in the final project.
•The string 'hello' was used in previous lessons to create a popup alert.
Syntax rules for strings and practical examples
•To create a string, surround text with single quotes at the beginning and end.
•Combining a string and a number automatically converts the number into a string.
•Example: Creating a dollar sign text by adding the cost of a basketball and a t-shirt.
Understanding JavaScript's Order of Operations in String Addition
•The order of operations also applies to strings, with brackets indicating priority.
•To add numbers before combining with a string, enclose the calculation in brackets.
•To create a complex text line, combine strings and numbers from left to right.
Using Strings in JavaScript
•To avoid the issue of numbers being treated as strings, brackets can be used to
separate calculations from string concatenation.
•Strings can be broken up into parts, calculations can be performed on the parts, and
then the parts can be added back together.
•By using the alert function, the created strings can be displayed in a popup.
•There are three ways to create a string in JavaScript: using single quotes, double
quotes, or backticks.
•Single quotes are recommended for creating strings as they are easier to read and
type, but double quotes can be used if the string contains a single quote.
Different Ways of Creating Strings in JavaScript
•Single quotes and double quotes can be used to create a string in JavaScript.
•To avoid issues with single quotes within a string, double quotes can be used as
well.
•Another solution to the issue of single quotes within a string is using an escape
character (\) before the single quote.
•Escape characters can also be used to create other special characters within a
string, such as backslash single (\') or backslash double (\").
•The escape character backslash followed by the letter 'n' (\n) creates a new line of
text within a string.
•Back ticks (`) can also be used to create a string in JavaScript, providing another
option.
Features of Template Strings
•Interpolation is the first special feature of template strings, allowing for the direct
insertion of values into a string.
•Interpolation is denoted by using the dollar sign, opening curly bracket, the value to
be inserted, and closing curly bracket.
•Multi-line strings allow for strings that span across multiple lines.
•Multi-line strings are created by using backticks (`) and pressing enter to move to a
new line.
•New line escape characters are automatically added when using multi-line strings.
How to Use HTML and CSS in Web Development
•Even though template strings have more features, it is still common to use single
quotes in JavaScript code by default.
•Strings represent text, and can be created using strings and numbers.
•Three ways to create a string in JavaScript are single quotes, double quotes, and
back ticks (template strings).
•Template strings have useful features like interpolation and multi-line strings.
•JavaScript, HTML, CSS are all essential technologies used in web development.
•HTML creates website content, CSS changes the appearance, and JavaScript
makes the website interactive.
•To write HTML and CSS code, a code editor like VS Code (Visual Studio Code)
needs to be installed.
•VS Code is popular and can be downloaded from Google by searching for VS Code
and following the instructions.
•HTML stands for Hyper Text Markup Language and is used to provide instructions to
a computer.
•Unlike JavaScript, HTML code cannot be written or executed using a console, but is
written inside a file using a code editor.
•To start writing HTML code, create a new folder on the desktop, name it "JavaScript-
course", and open the folder in VS Code.
Basics of HTML Coding
•To start coding in HTML, select the folder and click "Select Folder".
•HTML code is written between less than and greater than symbols. A button can be
created using the element. The text inside the button is defined within the element.
•Save the file, and to view the HTML code, open it in the browser via right-clicking
and selecting "Open with Google Chrome".
•By following the code, a button with the text "Hello" is displayed on the website.
•Save the file and refresh the website to see the paragraph appear.
•HTML elements are the components displayed on a webpage, such as buttons and
paragraphs.
•Each element starts with a less than symbol, followed by the element name, and
ends with a greater than symbol.
Introduction to HTML tags and syntax rules
•The opening tag starts the element, while the closing tag ends it, with a slash before
the element name.
•The contents inside the tags represent the text or other elements within the element.
•New lines in HTML code are treated as spaces and also get combined into one
space on the webpage.
•New lines and extra spaces can be used for code organization and readability.
Reviewing CSS Syntax
•A webpage is a single page like the homepage or the cart page together. This is
called a website.
•HTML stands for Hypertext Markup Language and is used to structure the content
on a webpage.
•CSS stands for Cascading Style Sheets and is used to change the appearance of a
website.
•CSS code is written inside the HTML file using the style element.
•The style element is unique as it does not appear visibly on the page but allows us
to write CSS code.
•CSS code is written inside curly brackets {} and can be used to change the
appearance of specific elements on the page.
•CSS selectors are used to select which elements to change, and CSS properties
and values are used to specify how to change them.
Understanding HTML Attributes and CSS Selectors in Web Design
•An HTML attribute like "title" can be added to an element to provide a tooltip when
hovering over it.
•The text inside the attribute's double quotes determines the tooltip's content.
•Attributes are placed in the opening tag of an element and separated from the
element name by a space.
•The attribute name and its value are separated by an equal sign (=) without any
spaces around it.
•To style elements differently, the class attribute can be used to label elements and
select them in CSS.
Using CSS to Modify Specific Elements and Reviewing HTML Structure
•To modify specific elements using CSS, we start by removing the button selector
and replacing it with the class selector ".red-dash-button".
•Adding a dot before the class name indicates that we are targeting a class. The
styles applied to elements with this class will change accordingly.
•Multiple elements can have the same class, allowing them to share the same styles.
•The HTML structure includes the HTML, head, and body elements, which the
browser automatically adds if missing in the code.
•However, it is recommended to follow the HTML structure in the code for better
access to HTML features.
•The HTML structure typically starts with the doctype declaration followed by the
HTML tag specifying a modern version of HTML.
Overview of HTML Structure and Benefits
•The HTML element represents the entire webpage and contains the head and body
elements.
•The head element contains information about the page, such as the style element
for linking external CSS.
•The body element contains everything visible on the page, like buttons and
paragraphs.
•Following this structure allows for the use of additional elements in the head, such
as the title element for tab text.
•By following this structure and installing a VS code extension like Live Server,
automatic webpage refreshing can be achieved.
•Changing the Live Server custom browser setting to Chrome ensures compatibility.
Simplifying Code Structure and Indentation in VS Code
•To ensure automatic refreshing of webpages when code is changed, open the file
with Live Server.
•Changing the background color of a webpage using Live Server can be done by
modifying the CSS code.
•Proper indentation, or spaces at the front of lines, makes code easier to read and
understand.
•Indentation can be added by typing at the beginning of the line and pressing tab,
and removed by pressing shift tab or using backspace.
•By default, VS Code uses four spaces per indent, but HTML, CSS, and JavaScript
commonly use two spaces per indent.
•To change the default tab size in VS Code, go to settings and modify the "tab size"
option.
•Indents for a specific file can be changed by selecting "indent using spaces" in the
editor and choosing the desired number of spaces.
Setting Up VS Code and Running JavaScript in HTML
•We adjust indents for the head and body elements to improve code readability.
•Line wrapping is enabled in VS Code to prevent the need for horizontal scrolling.
•The script element is placed at the bottom of the body to ensure the webpage is
created first.
•JavaScript code inside the script element can be executed, such as the example
alert("Hello").
•Running code in the console is primarily for testing and not used in real websites.
•We can add the "on click" attribute to a button in HTML to execute JavaScript code
when the button is clicked.
•The JavaScript code is written between double quotes after the on click attribute.
•The script element is used to run JavaScript code when the page is loaded.
•The on click attribute runs JavaScript code only when the button is clicked.
•HTML, CSS, and JavaScript are used together to create interactive websites.
•Comments in JavaScript are used to provide information about the code and to
disable certain sections of code temporarily.
Introduction to Comments and Console.log in JavaScript
•JavaScript, HTML, and CSS all have different syntax for writing comments.
•In JavaScript, multi-line comments are written between /* and */. Single-line
comments are written with //
•We learned how to load JavaScript inside an HTML file using the script element and
the on click attribute.
•We learned how to create comments and use console dot log.
•Next, we're going to learn the next feature of JavaScript called variables.
•We're going to use variables to build a simple version of the cart quantity feature of
the final project.
•We'll create a new HTML file called "zero five dash variables.html" for learning
variables.
•We'll prepare the "variables.html" file for this lesson by changing the title to
"Variables", deleting the CSS, and removing unnecessary HTML and JavaScript
code.
•Finally, we'll save and open the "variables.html" file in our browser using live server.
•A variable is like a container where we can save a value like a number or a string
and use it later.
•We'll create our first variable inside the script element using the "let" keyword and
choose a name for it.
Introduction to Variables in JavaScript
•To create a variable, use the 'let' keyword followed by the variable name and an
assignment operator (=) to save a value.
•Variables can be used in calculations by substituting their value into the code.
•JavaScript will substitute the value inside the variable wherever it is used.
•When we save the sum of four plus two into another variable and log it, the value of
six is saved into the result variable.
•Variables can store any type of value, including strings. We create a string variable
named "message" and save the value "hello" inside it.
•The word "let" is used to create a new variable, followed by the variable name.
Some restrictions exist for variable names: 1) Special words like "let" cannot be used.
2) Variable names cannot start with a number. 3) Special characters (except "$" and
"_") and spaces are not allowed.
•Semicolons (;) indicate the end of an instruction and are used to separate different
instructions in JavaScript.
JavaScript Syntax and Variable Reassignment
•JavaScript has a feature called semicolon insertion that automatically inserts the last
semicolon in a line of code if it is removed.
•Changes to the value stored inside a variable can be made by reassigning the
variable name.
•Reassigning a variable does not require the use of the keyword "let" because it
would create a new variable with the same name.
•To reassign a variable, simply type the variable name followed by the new value.
•To increase the value of a variable, we can take the previous value, add a certain
number, and save it back.
•The project we will be working on is the cart quantity feature, where a number in the
top right corner shows the number of products in the cart.
•Clicking the add to cart button will increase the quantity by one and display it in the
console.
•The plus two and plus three buttons will add multiple products to the cart.
•Clicking the reset cart button will set the quantity back to zero.
•To start the project, create a new HTML file named "05-cart-quantity.html" and copy
the code from "variables.html" into it.
Creating Buttons and Implementing Basic JavaScript Interaction
•In the new file, change the title to "cart quantity" and remove all JavaScript code,
while keeping the script element for new code implementation.
•Create buttons with different functionalities within the body element, using HTML
code with button tags.
•Additional buttons include "add to cart", "plus two", "plus three", and "reset cart".
•Save the changes and view the updated file with live server. All buttons should now
be visible.
•To make the webpage interactive, create a variable within the script element to store
the cart quantity, initializing it as zero.
•Use the on click attribute to run JavaScript code when the "show quantity" button is
clicked.
•Display the cart quantity in the console using the console.log() function and the
message "cart quantity: 0".
'Subject': Making Buttons Interactive in JavaScript
•'Notes':
•To open the console, right-click and select inspect. Then, click on the console tab.
•To display a message in the console, click the show quantity button.
•To insert a value into a string, use a template string with backticks (`).
•Use ${variableName} syntax inside the template string to insert a variable's value.
•To increase the cart quantity by one when the add to cart button is clicked, reassign
the cart quantity variable by adding 1 to itself.
•Display the updated cart quantity in the console by using the same code as for
displaying the initial quantity.
•The plus two button and the rest of the buttons can be made interactive using similar
techniques.
Using 'on click' attribute and shortcuts for reassigning variables in JavaScript
•We are adding the 'on click' attribute to increase the cart quantity by two.
•The code for the 'on click' attribute is copied and pasted to display the updated
quantity.
•The reset cart button sets the cart quantity back to zero.
•Two messages are displayed: "Cart was reset" and the updated cart quantity.
•Shortcuts for reassigning variables, like 'cart quantity += 2', can be used.
Writing Notes on JavaScript Variable Shortcuts and Naming Conventions
•The plus equals operator (+=) is commonly used to add a value to an existing
variable and assign the result back to the variable.
•The plus plus operator (++) is a shorthand for the plus equals operator and adds one
to the variable.
•Shortcut operators also exist for other arithmetic operations: minus equals (-=),
multiply equals (*=), divide equals (/=), and minus minus (
Programming Naming Conventions and Variable Creation in JavaScript
•For instance, instead of using a very short name like 'C' for the variable 'cart
quantity', it is better to use a name that is more descriptive and understandable.
•On the other hand, using long names like 'quantity of products in the cart' can make
the code harder to read.
•JavaScript offers three ways to create variables: using 'let', 'const', or 'var'.
•'let' and 'const' are similar in that they create variables that can be changed later, but
'const' creates a variable with a constant value that cannot be altered.
•Using 'const' is considered a best practice when the value of the variable should not
be changed, while 'let' is used when the value needs to be modified.
•'var' is another way to create a variable, but it is older and less recommended
compared to 'let' and 'const'.
JavaScript Variables and Boolean
•VAR is the original way to create variables in JavaScript, but it has some issues and
is not used in new code.
•There are three ways to create variables in JavaScript: Const, Let, and Var. Const is
used by default, while Let is used to change a variable.
•type of can be used with variables to determine the type of value it holds. For
example, type of 3 would return "number".
•The lesson also covers reassigning variables, naming conventions, and best
practices for variable names.
•The next lesson will cover Boolean and If statements in the context of building a rock
paper scissors project.
Introduction to Boolean Values and Syntax Rules
•In JavaScript, there are two types of values: numbers and strings.
•Boolean values, represented by true and false, are another type of value in
JavaScript.
•We can compare numbers using comparison operators, such as less than (<) and
greater than (>).
•To create a Boolean value, simply type true or false without quotes.
•Surrounding true or false with quotes makes it a string, not a Boolean value.
•Typeof true will return "string", while typeof false will return "boolean".
•There are other comparison operators, such as greater than or equal to (>=), less
than or equal to (<=), triple equals (===), and exclamation double equals (!==).
•JavaScript has two ways to check if two values are equal: triple equals (strict
equality) and double equals (loose equality).
Introduction to Comparison Operators and If Statements in JavaScript
•The double equals (==) operator converts both values into the same type before
comparing them, which can lead to unexpected results when comparing values of
different types.
•To avoid conversion behavior, the triple equals (===) operator should be used to
check if two values are the same.
•The not equal to (!=) operator and the not equal to strict (!==) operator are used to
check if two values are not the same.
•Comparison operators have a lower priority than math operators in the order of
operations.
•If statements allow for conditional execution of code based on a boolean value.
•Code within the curly brackets following the if statement is executed if the boolean
value is true.
•An else statement can be used to specify a block of code to be executed if the if
statement evaluates to false.
Introduction to if statements and syntax rules
•The if-else statement allows for the execution of different code based on a boolean value.
•The code inside the 'if' branch will execute if the boolean value is true.
•The code inside the 'else' branch will execute if the boolean value is false.
•We can use any code that results in a boolean value inside the round brackets of the 'if'
statement.
•Multiple if-else statements can be used to handle different situations and determine which
code to run.
•The syntax for an if statement includes the keyword 'if' followed by round brackets with a
boolean condition, and then curly brackets containing the code to be executed.
Using If Statements and Variables in JavaScript
•The use of curly brackets in a branch is optional if there is only one line of code.
•Curly brackets are mandatory when there is more than one line of code in a branch.
•If statements can have multiple conditions using "else if" and "else" branches.
•Multiple conditions are checked one by one, and the corresponding branch is executed if
true.
•Variables can be used in if statements by assigning values and using the variable name in the
condition.
•The combination of if statements and variables can be used in a rock paper scissors game.
Building a Rock Paper Scissors Game
•The project involves building a simple version of a Rock Paper Scissors game.
•To access the project, open a new tab in the browser and type "super
simple.dev/projects/bulls".
•In the game, players can pick a move, and the computer will randomly pick a move as well.
•The results of the game are displayed, along with a score of wins, losses, and ties.
•Start by creating a new HTML file named "zero six dash rock dash paper dash scissors dot
html".
•Copy all the code from "bullions dot html" into the new file and remove any existing
JavaScript code.
•Create a paragraph element in the HTML to display the text "Rock Paper Scissors".
•Create three buttons for the moves: rock, paper, and scissors.
•When writing JavaScript, it is important to think about the steps involved and convert them
into code.
•To convert the steps into code, JavaScript will be used in the on click attribute of the button.
•To check if a random number is between zero and one third, the and operator can be used.
•The and operator checks if both sides of the comparison are true.
•If the left side and the right side of the and operator are true, the result will be true.
•If one of the sides is false, the result of the and operator will be false.
•The and operator has a lower priority than math and comparisons in the order of operations.
•The and operator is useful for checking if multiple conditions are met in a single comparison.
Program Logic and Logical Operators
•In the program, a condition is checked to determine which move the computer will pick in a
game of rock, paper, scissors.
•The first condition checks if the random number is between 0 and 1/3. If true, the computer
picks rock.
•The second condition checks if the random number is between 1/3 and 2/3. If true, the
computer picks paper.
•The third condition checks if the random number is between 2/3 and 1. If true, the computer
picks scissors.
•The less than operator is used instead of less than or equal to to prevent overlapping of
conditions.
•The NOT operator flips the boolean value to its opposite value.
Scope and Variable Naming in Programming
•The not operator is used to determine the opposite of a statement, i.e., if something is not
true, it is false.
•In the project, logical OR and not operators are not currently required.
•Creating a variable using the const keyword is necessary to save the computer's move and
compare it later.
•The if statement creates a scope, which restricts the visibility of variables to within the curly
brackets.
•Accessing a variable outside the if statement requires defining it before the if statement.
•The variable computer move must be defined above the if statement to avoid the error of it
not being defined.
•Scopes allow for the reuse of variable names without conflicts in larger codebases.
Scope and Variable Assignment in JavaScript
•The variable 'computer move' is created outside any curly brackets and can be accessed from
anywhere in the code.
•The 'computer move' variable is reassigned using 'let' within the if statement, allowing access
to it in subsequent lines of code outside the if statement.
•The use of 'var' for variable assignment is discouraged as it does not follow the rules of
scope.
•A comparison is made between the player's move (rock) and the computer's move using an if
statement with triple equals (===).
•The result of the comparison is saved in the 'result' variable using 'let' to ensure accessibility
outside the if statement.
•Additional branches of the if statement are mentioned but not elaborated on in the given text.
Creating a Simple Version of Rock Paper Scissors
•The code will use if-else if brackets and curly brackets to compare the computer's move to
the player's move.
•If the computer move is "paper" and the player move is "rock", the player loses.
•If the computer move is "scissors" and the player move is "rock", the player wins.
•The computer move and the result will be inserted into the pop-up message using template
strings.
•The code will generate a random number, convert it into a computer move, compare it to the
player move, and display the result in the pop-up.
Overview of Rock, Paper, Scissors Game and Introduction to Truthy and Falsey
Values
•When playing Rock, Paper, Scissors, if the player chooses paper and the computer
chooses rock, the player wins.
•If the player chooses paper and the computer also chooses paper, it results in a tie.
•If the player chooses paper and the computer chooses scissors, the player loses.
•Similarly, if the player chooses scissors and the computer chooses rock, the player
loses.
•If the player chooses scissors and the computer chooses paper, the player wins.
•If the player chooses scissors and the computer also chooses scissors, it results in a
tie.
•The code for the game includes interactive buttons for each move.
•In JavaScript, if statements work with various types of values, not just booleans.
•Certain values behave like true and are called truthy values.
•Other values, like 0, behave like false and are called falsey values.
•False, 0, empty string, NaN, undefined, and null are falsey values.
•One way to use values as shortcuts in our code is by creating a variable and setting
it equal to a truthy value.
•We can use truthy and falsey values in if statements instead of doing comparisons.
•Truthy values behave like true and falsey values behave like false.
•Falsey values include false, zero, empty string, NaN, and undefined.
•The ternary operator is a shortcut for an if-else statement. It uses a boolean value
followed by a question mark and two possible values. The value after the question
mark is returned if the boolean value is true, and the value after the colon is returned
if it is false.
•The ternary operator can be saved in a variable, allowing for more flexibility in code
execution.
•The guard operator, or short-circuit evaluation, is a feature of the and operator. If the
left side of the and operator is false, the right side is not executed.
•The guard operator can be used to block or "guard" code on the right side based on
the value on the left side.
•Like the ternary operator, the guard operator can also be saved in a variable for later
use.
Notes on "Shortcuts for IF Statements: Guard and Default Operators"
•The guard operator stops early if the first value is falsey, resulting in the first value
as the result.
•If the first value is truthy, the guard operator continues and gives the second value
as the result.
•The guard operator is a shortcut for an IF statement and can be written on a single
line.
•The default operator is similar to the guard operator but uses "or" instead of "and".
•The default operator stops early if the first value is truthy, resulting in the first value
as the result.
•If the first value is falsey, the default operator continues and gives the second value
as the result.
•The default operator can be used to set a default value if a variable is undefined or
falsey.
•We learned how to use IF statements to make decisions and comparison and logical
operators.
•We learned about algorithms and created a simple version of rock paper, scissors.
•We learned about truthy and falsey values and some shortcuts for if statements.
•In this lesson, we will learn about functions and how to use them.
•We create a new file called zero seven dash functions dot html.
•We copied the code from bulls dot html to functions dot html.
•The title of the file was changed to functions, and unnecessary code was removed.
•Functions allow us to reuse code and they are created using the 'function' keyword
followed by a name, round brackets, and curly brackets.
•Inside the curly brackets, we can write the code that the function will execute.
•We can call a function by typing its name followed by brackets, which will run the
code inside the function.
•A function allows code to be reused and is executed by calling its name followed by
brackets.
•The word "function" is used to create a new function, and a name must be chosen
for the function.
•Function names follow the same rules as variable names, excluding special words
and starting with a number.
•The code within the curly brackets of a function is called the function body.
•To run the code within a function, the function name must be called with brackets,
also known as calling/running/executing the function.
•The code for generating a computer move is the same for all three buttons, making it
suitable for a function.
•A function named "pick computer move" is created to encapsulate the code for
picking a computer move.
•All the code for picking a computer move is moved into the newly created function.
Explanation of code and use of functions in JavaScript
•The function is created in the script element to ensure it is defined before it is used.
•Calling the function pick computer move brackets upon clicking the scissors button
results in an error because the function creates a scope, and variables defined within
it cannot be accessed outside of it.
•To solve the problem, the variable created within the function should be moved
outside the function to make it a global variable.
•The function pick computer move brackets is called again upon clicking the scissors
button, and the code functions correctly due to the variable now being accessible.
•The function pick computer move brackets is also called upon clicking the paper and
rock buttons, replacing the code that was previously written for each button.
Functions and Return Statements in JavaScript
•Functions allow code reuse and remove duplication, making code cleaner and
easier to update. Updating code in one place inside a function updates it for all
instances.
•Return statements let us get a value out of a function. We can specify a return value
after typing "return" followed by the value, such as a number or a string.
•Using a return statement ends the function immediately and returns the specified
value. If no return statement or value is given, the function returns "undefined".
Understanding Return Statements and Scope in Functions
•The function can be used in other buttons by saving the returned value in variables.
•Reusing code with small differences can be achieved by using functions and
parameters.
•The function uses the cost of the products and the tax rate to calculate the tax.
•The function initially calculates the tax for 1000 cents ($1) only.
•We explore the concept of parameters, which allows us to pass different values into
the function.
•We create a parameter named 'one' and save a value of 2000 into it.
•By using the parameter 'one', the function calculates the tax for 2000 cents (200
cents).
•We demonstrate that we can save different values into the parameter each time we
call the function.
•We create a new line and call the function with the value of 5000, resulting in a tax
of 500 cents.
•The syntax rules for parameters are explained, including naming conventions and
restrictions.
•We clarify that when a value is passed into a function, it is called an argument.
•Functions and parameters have been used throughout the course, starting with the
'alert' code.
Working with Parameters in Functions
•The values for the parameters are passed when calling the function.
•The second parameter can be assigned a default value by using an equals sign
followed by the desired value.
•The code inside each button is the same, with a small difference in the move
chosen.
•To reuse the code, a parameter is created and a new function named "play game
brackets" is defined.
•The code is moved into the function and the value that differs for each button, the
move, is turned into a parameter.
•Inside the scissors button, the function "play game" is called and the move "scissors"
is saved into the player move parameter.
•The code that displays the message is also modified to display the value saved in
the player move parameter.
•The function is now modified to use a parameter instead of always using scissors.
•The function can be used to reuse the code for other buttons as well.
Code structure and function usage explanation
•The code for checking if the player move is paper is pasted within an else-if
condition.
•The code for checking if the player move is rock is copied and pasted within the
function branch for rock.
•A function called "play game" is created to reuse code in the paper and rock buttons.
•The play game function is called with the respective move (paper or rock) as a
parameter.
•The play game function calls the pick computer function to generate the computer's
move.
•The code execution returns to the place where the play game function was called
after completing its execution.
•In this lesson, we learned how to use functions to reuse code and the concept of
returning values from functions using the "return" keyword.
•We also learned how to pass values into functions using parameters and improve
code logic by removing duplication.
•In the next lesson, we will explore objects in JavaScript and how they can be used to
group multiple values together.
•An object is created using the "const" keyword, followed by a variable name and an
open and closed curly bracket.
•A demonstration of an object with properties like "name" and "price" was provided.
•We can log an object to the console using "console.log(object)" to display all its
values.
Syntax and Manipulation of Objects
•To access a value associated with a property in an object, use the dot notation (e.g.,
console.log(product.name) will display "socks").
•Values inside an object can be changed by assigning a new value using dot notation
(e.g., product.name = "cotton socks").
•Object creation involves enclosing properties and values inside curly brackets.
•Property value pairs are separated by a colon, and multiple pairs are separated by
commas.
•If a property that doesn't exist is accessed, the value will be undefined.
•Removal of a value from an object can be done using the delete keyword followed
by the object and property name.
•An object is considered as another type of value.
Working with Objects in JavaScript: Introduction and Practical Example
•We can save an object inside a variable and check its type using the console.log
function.
•Objects allow us to use multiple values together and display them using console.log.
•The project keeps track of the number of wins, losses, and ties in the game.
•There is also a "Reset Score" button to set the score back to zero.
Updating Algorithm and Score in Game
•The second step is to compare the moves and get the result.
•The score variable is an object with properties: wins, losses, and ties.
•The result is checked and if it is a win, the score is increased by one in the "wins"
property of the score object.
Adding Code to Update and Display Score
•We can use the shortcut plus equals one to increase a variable by one.
•We add an else if statement to check for the result "you lose" and update the
"score.losses" property by increasing it by one.
•Next, we add another else if statement to check for the result "tie" and update the
"score.ties" property by increasing it by one.
•We use a multi-line string in the code to display the score in a popup.
•To remove extra spaces in the popup, we remove them in the code before saving
and testing the game.
Adding a Reset Score Button and Accessing Values in Objects
•We need to add a reset score button to the project on super simple.dev.
•Inside the HTML code, we will add a button with the text "reset score" and a code for
the button.
•Clicking the button will execute code to reset the score back to zero using dot
notation.
•The values for wins, losses, and ties in the score object will be set to zero.
•To access the value associated with the name property in object product two, we
can use either dot notation or bracket notation.
•The values accessed using both notations will show the string "shirt".
Bracket Notation and Values in Objects
•Bracket notation is used when properties in dot notation do not work, such as when
the property contains special characters like dashes.
•Bracket notation allows for the addition of properties to objects when they are
created.
•In bracket notation, variables, calculations, or any value can be used between the
brackets.
•Dot notation is usually used by default due to its shorter and easier-to-read syntax.
•When only a string is used between the brackets, the brackets can be omitted when
creating an object.
•Objects can store any type of value, including numbers, strings, booleans, and other
objects.
•Nested objects, or objects within objects, can be used to organize related values
within a parent object.
•Object properties can store different data types such as numbers, strings, objects,
and functions.
•JavaScript has built-in objects like console and math which provide useful
functionalities.
•The Jason object is a built-in object that helps us work with JavaScript object
notation (Jason), which is a syntax similar to a JavaScript object but with fewer
features.
•Jason syntax uses double quotes for properties and strings, doesn't support single
quotes, and doesn't support functions.
•The Jason object's "stringy" method converts a JavaScript object to Jason syntax,
resulting in a string representation of the object.
•The "pars" method of the Jason object converts a Jason string back to a JavaScript
object.
Understanding JSON and localStorage
•To convert a JSON string into a JavaScript object, use the JSON.parse() method.
•Variables are temporary and get deleted when the page is refreshed or closed.
•localStorage does not get deleted when the page is refreshed or closed.
•The setItem() method takes two strings: the name (for accessing the value later) and
the value (saved as a string).
•To retrieve a stored value from local storage, use the method localStorage.getItem().
Pass the desired key as a string to retrieve the corresponding value.
•To save a score in local storage, replace the key "message" with "score" and
convert the score object to a JSON string using JSON.stringify().
•Retrieve the score from local storage using localStorage.getItem() and convert it
back to an object using JSON.parse().
•Update the code to use the retrieved score instead of resetting it to zero.
Using Local Storage to Save and Retrieve Scores in a Game
•When the page loads, the score is retrieved from local storage. If the game is
played, the score starts from the value stored previously.
•To update the score, it is saved in local storage using the local storage dot set item
function. The score object is converted into a JSON string using JSON stringify
before saving.
•When the page is loaded again, the previously saved score is retrieved from local
storage using local storage dot get item function. The JSON string is converted back
into an object using JSON parse.
•The reset score button removes the score from local storage using local storage dot
remove item function. This prevents the game from retrieving the old score when
reset is pressed and the page is refreshed.
•A check is performed to handle the case when there is no score in local storage. If
the score is null, a default value is assigned.
Using shortcuts to simplify code in the rock paper scissors project
•The default object is set to winds zero, losses zero, and ties zero.
•Removing the default object will result in a null score, which can be fixed by
assigning the default value.
•Instead of checking if the score is equal to null, using the "not" operator (!score) is a
shortcut to check if the score exists or not.
•The default operator can be used to set a default value if the left side is falsey or
null.
•Commenting out code using slash star and star slash allows for reference.
•Using the default operator simplifies the code by setting a default value if the score
does not exist.
•The simplified code still allows for the reset score feature and works as intended in
the rock paper scissors game.
Introduction to JavaScript Values and Objects
•Null and undefined: Null and undefined are falsey values in JavaScript that
represent the absence of a value. Null is used intentionally to signify an empty value,
while undefined indicates that a value has not been assigned. Null does not default to
a default value, unlike undefined.
•Auto boxing: Auto boxing is a feature in JavaScript where simple values like strings,
numbers, and booleans are automatically wrapped in a special object. This object
allows these values to have properties and methods, such as the length property for
strings or the toUpperCase() method for strings.
•Auto boxing limitations: Auto boxing does not work with null and undefined, and
attempting to use auto boxing with these values will result in an error.
•When creating an object, the variable only gets a reference that points to the object's
location in the computer's memory.
•Copy by reference allows JavaScript to copy the reference instead of the entire
object, making the language more efficient.
•Modifying the object through the reference is possible, even with the use of the
'const' keyword, as it prevents changing the reference itself.
•Objects with the same reference will point to the same object in memory, resulting in
changes made to one object reflecting in the other.
Object References and Shortcuts
•Two objects with the same values inside are not considered equal because they are
different references.
•When comparing variables that contain objects, the comparison is done based on
the references, not the values inside.
•To compare the values inside objects, it needs to be done manually by comparing
specific properties.
•Object references are initially confusing but become easier to understand with
practice.
•There are shortcuts for extracting specific properties from an object, such as using
destructuring syntax to save a property value in a variable.
•The destructuring shortcut allows for a more concise way of accessing object
properties.
JavaScript Object Destructuring Shortcuts
•The destructuring shortcut allows taking properties out of an object and saving them
in variables.
•The shorthand property allows using the same name for both the property and the
variable.
•A score was added to the rock paper scissors game using objects.
•Built-in objects like console, math, JSON, and localStorage were discussed and
utilized.
•Additional details about objects, such as null, auto boxing, and references were
learned.
•The content from "objects.html" was copied and pasted into "dom.html".
•The previous lesson included code that utilized the document object to modify the
body's innerHTML.
The Document Object Model (DOM) Syntax and Properties
•The code uses the dot notation to access properties of the document object.
•The document object represents or models the webpage and is linked to it.
•Changing certain properties in the document object will also change the webpage.
•The document object has properties like body and title that can be accessed using
the dot notation.
•The title property, accessed with document.title, gives the title at the top of the tabs.
•Changing the document.title property will change the text at the top of the tab.
Title: The Basics of the Document Object Model (DOM) in JavaScript
•The 'document.title' property can be used to get or change the title of the current tab
in a web browser.
•The 'document.body' property is a special property that allows us to access the body
element of an HTML document using JavaScript.
•The 'typeof' operator can be used to determine the type of an object in JavaScript.
•The 'document.body.innerHTML' property controls all the HTML content inside the
body element.
•Changing the 'innerHTML' property of an element will modify the HTML content
within that element.
The Use of InnerHTML and Document.querySelector in JavaScript
•HTML code inside the body can be modified using the innerHTML property.
•InnerHTML can replace the existing HTML with new HTML code, not just text.
•JavaScript code can replace all the HTML inside the body using innerHTML.
•By typing "button" as the string, document.querySelector retrieves the first button
element from the webpage.
•Console logging the result confirms that the selected element has been successfully
retrieved.
•When using document.querySelector, typing "button" will select the first button
element on the page.
•Typing "body" will select the first body element on the page, similar to using
document.body.
•The innerHTML property allows control over the HTML inside an element.
•Changing the innerHTML property changes the HTML inside the element.
•The dot notation for document.querySelector can be written on multiple lines for
readability.
•To select an element with a specific class, use the dot notation in the querySelector
method.
•The class selector, starting with a dot, can also be used in CSS to style elements
with a specific class.
•It is common practice to prefix JavaScript classes with "JS-" to indicate their usage
in JavaScript.
•HTML elements are JavaScript objects, so they can be saved inside variables.
•The DOM allows JavaScript full control of the webpage by combining JavaScript and
HTML.
•Practical examples of using the DOM include modifying YouTube subscribe button,
Rock paper Scissors game, and Amazon shipping calculator projects.
•CSS can be used to style these projects and make them visually appealing.
Creating YouTube Subscribe Button with JavaScript Functionality
•To create the functionality for the YouTube subscribe button, open the "zero nine-
dash dom-dash projects.html" file.
•Copy and paste the code from "dom.html" into the new file.
•Change the title to "Dom projects" and remove the HTML code, leaving only the
script element.
•Save the file and open it in the browser using Live Server.
•Create the HTML elements for the YouTube subscribe button: a paragraph with the
text "YouTube subscribe button" and a button with the text "Subscribe."
•The JavaScript code should check the current text of the button and change it to
"Subscribe" if it is currently "Subscribe", or change it back to the original text
otherwise.
How to Create a Subscribe Button Using JavaScript and DOM
•We can use document.querySelector() to select the button element by its class
attribute.
•To get the HTML inside the button, we can use buttonElement.innerHTML.
•We can check if the text inside the button is equal to "subscribe" using an if
statement.
•If the text is not equal to "subscribe", we change it back to "subscribe" using
buttonElement.innerHTML = "subscribe".
•It is important to ensure that there are no spaces or new lines around the text inside
the button for the code to work correctly.
Introduction to HTML Element Properties and Cleaning Up Code
•The innerHTML property of an HTML element can return the text inside the element,
but it includes any surrounding spaces as well.
•To avoid the issue of spaces around the text, the innerText property can be used to
retrieve the text inside the element without the extra spaces.
•Separating JavaScript code from HTML by placing it in a function helps to make the
code cleaner and easier to read.
•The code can be grouped together at the bottom of the file, and the function can be
called using the onclick attribute.
•In the rock paper scissors project, the score will be displayed on the page instead of
in a pop-up, and the result and moves will also be shown on the page instead of in a
pop-up.
•A new file will be created for the rock paper scissors game.
• We need to copy and paste the previous code for rock paper scissors and
save it as zero nine dash rock dash paper dash scissors dot html.
•We scroll up to the HTML section and add a paragraph element after the scissors
button.
•We use "innerHTML" to put the score value inside the element.
•We create a string with the score value and paste it inside the back ticks.
•The paragraph element is a block element, which is why it appears below the
buttons.
Updating Score Element in JavaScript
•The layout of the webpage is discussed, with a note on how the placement of certain
elements affects the appearance.
•To update the score on the page, the JavaScript code is modified to include a
function called "update score element".
•The function is created to avoid duplication of code and to make it possible to reuse
the code.
•The function is called after updating the score and saving it in local storage.
•The "update score element" function is also called when the reset score button is
clicked, ensuring that the score is updated on the page.
Working with the DOM and Creating an Amazon Shipping Calculator
•The author begins by mentioning the return to a simpler development style and
introduces a game.
•The author explains the process of displaying results and moves in paragraphs on
an HTML page using DOM manipulation.
•The author instructs the reader to use the DOM to place the result and moves inside
specific paragraphs.
•The author demonstrates how to display the result and moves by using
document.queryselector and modifying the innerHTML property.
•The author mentions deleting a popup and saving the changes to the webpage.
•The author introduces the next project, which involves creating an Amazon shipping
calculator.
•The author explains the functionality of the shipping calculator, based on the order
cost entered in a text box.
• Soit will display the same total down here.
•Create a button.
•When we click the button, we'll get the text inside the text box.
•If the amount is below $40, add $10 shipping.
•We use the calculate button to retrieve the input element from the page.
•We access the text inside the input element using the `value` property.
•Finally, we display the total cost on the page using a paragraph with class "JS-total-
cost".
Adding functionality to calculate cost and display total
•Console log the cost to verify the number obtained from the text box.
•Console log the cost down below to check if the math is working properly.
•The console log shows that the cost is a string, which is why the math is not
working.
•To convert the string into a number, use the number function before the code.
•Add the attribute on key down and set it to console log the string "typing".
Creating a Keyboard Feature in JavaScript
•We can create a keyboard feature in JavaScript that performs an action when a key
is pressed.
•We can use the `onkeydown` event listener to check for key presses.
•To check which key was pressed, we can access the `event` object, which is
provided to us by JavaScript.
•The `event` object contains information about the event, including the key that was
pressed.
•By using `event.key`, we can retrieve the specific key that was pressed.
•We can check if the key is the "Enter" key by using an if statement with the condition
`event.key === "Enter"`.
•If the key is "Enter", we can perform the desired action, such as calling a function or
executing a block of code.
•We can move the code into a separate function to keep our code organized and
reusable.
JavaScript Basics
•The webpage is inside the browser, so the document object is inside the window
object.
•Pop-ups, like alerts, are also part of the browser, accessible using window.alert.
•The window object has a shortcut, allowing us to omit "window." when accessing its
properties.
•The Document Object Model (DOM) allows JavaScript to control the webpage.
•This lesson will involve creating a copy of the previous lesson's HTML file for the
projects.
Adding CSS to Projects
•To add CSS to our projects, we first click on the file icon in the code editor to display
our files.
•Next, we select the "09-dom-projects" file, right click to copy it, and right click in the
desired location to paste it.
•We then rename the file by removing "copy" at the end and changing the beginning
to "10".
•After hiding the files, we open the "10-dom-projects" in a browser using live server.
•To start adding CSS, we focus on styling the YouTube subscribe button.
•We create a "style" element within the head section and write CSS code inside it.
•By using the class attribute, we add a second class, "subscribe-button," to the button
element.
•The CSS code inside the curly brackets will style the subscribe button, such as
removing its border.
•This approach allows us to adapt the appearance of specific elements without
affecting others.
Styling Elements with CSS
•An introduction to CSS and its application in changing properties and values.
•Changing the text color to white with the property "color: white;".
•Increasing spacing on the left and right sides of the element for further design
improvements.
'Subject': "Styling a Subscribe Button using CSS and JavaScript"
•'Notes':
•The writer explains the process of styling a subscribe button using CSS and
JavaScript.
•The writer begins by adding padding to the button and adjusting it until it matches
the final design.
•Next, the writer increases the font weight to make the text bold.
•The writer then makes the corners of the button rounded using the border radius
property.
•They explain how adjusting the pixel value changes the roundness of the corners.
•Finally, the writer adds the pointer icon when hovering over the button using the
cursor property in CSS.
•They mention that clicking the button will change the text, background color, and text
color, and that they will show how to achieve this using JavaScript.
•The writer indicates that the JavaScript code will be written in a separate section of
the code.
Changing CSS Styles on Button Click
•To change the style of a button when clicked, we can add a class to the button
element.
•This class can be added using the "classList.add()" method, followed by the name of
the class.
•To override previous styles, we should place the new styles below the original button
styles.
•The background color can be changed using "background-color: gray", and the text
color using "color: black".
•To find the exact color used in the final design, we can inspect the button element in
the browser's elements tab.
Notes on CSS button styling and text formatting
•The CSS code of the button includes the background color that should be used.
•The color value is in RGB format, which stands for red, green, and blue.
•The first number represents the amount of red in the color, the second number
represents the amount of green, and the third number represents the amount of blue.
•Each number ranges from 0 to 255, with 0 being less color and darker, and 255
being more color and lighter.
•The color used in the button code is a light gray with an RGB value of (240, 240,
240).
•Clicking the button again reverts it back to the original style, which can be achieved
by removing the "subscribed" class from the button element.
•To style all paragraph elements on the page, the CSS code would be "p { }".
•Alternatively, styling the body element will apply the text formatting to the entire
page.
Styling Text and Elements with CSS
•To change the font of the text, use the property font-family: aerial to style all text
inside the body.
•Write styles for the body at the top to allow for later overrides if needed.
•Add margin-bottom: 30 pixels to create space between the subscribe button and the
second project.
•To style the Amazon shipping calculator, add the class "cost-input" to the input
element and use .cost-input { } in CSS to style it.
•Add padding of 10 pixels to the top, bottom, left, and right of the text box using
padding-top, padding-bottom, padding-left, and padding-right.
•Alternatively, use the shortcut padding: 10 pixels; to add padding to all sides
simultaneously.
Styling Elements in CSS
•This line of CSS code achieves the same result as the previous four lines.
•The background color of the button is set to green and the text color to white.
•The padding is adjusted to 15 pixels horizontally and 12 pixels vertically to align with
the text box.
•Scroll down and click on the link to view the final design for rock paper scissors.
•When clicking a move, display the result in bold and show the chosen and
computer's move.
•Create a copy of the Rock Paper Scissors project and rename it.
•Hide files and close the previous file, then open the new file in the browser.
•We add the class "title" to the paragraph element to style it in CSS.
•In CSS, we change the font size of the title class to 30 pixels.
•We make the text bold by using the font-weight property in CSS.
•To style the buttons, we save the rock, paper, and scissors images in the project
folder.
•The image elements use the src attribute to specify the image files to load onto the
page.
•To style a class called "movedash icon", the height of an image can be adjusted by
using the CSS property "height" followed by a pixel value.
•To create a folder, click on the folder icon and give it a name.
•The computer may fail to load an image if its file path is not updated after moving it
into a folder.
•The file path can be updated by adding the folder name followed by a slash in the
source attribute.
•The code used to load one image can be used to load other images by changing the
file name and adding the appropriate class.
Styling buttons with images and CSS
•We'll replace the text with an image element and set the source attribute to
"images/scissors-emoji.png".
•The image element will have a class of "icon" for resizing purposes.
•We'll add a class of "move-button" to the buttons to style them with CSS.
•The buttons will have a white border with a thickness of 3 pixels and a solid style.
•The size of the buttons will be set to 120 pixels width and height.
•The buttons will have a border radius of 60 pixels to make them round.
•There will be some margin on the right side of the buttons for spacing.
Styling the Game Interface
•To set the right margin for an element, use the 'margin-right' property with a value of
10 pixels.
•To change the cursor to a pointer when the mouse is over a button, apply the
'cursor: pointer' property.
•For the result section, assign the class 'result' and use CSS to increase the font size
to 25 pixels.
•Make the text in the result section bold by using 'font-weight: bold'.
•Add a top margin of 50 pixels to create space between the result section and the
buttons.
•Style the moves section by adding fake moves, including images and text.
•Use the 'move-icon' class to resize the images in the moves section to match the
size of the buttons.
•In the score section, add a class of 'score' and set a top margin of 60 pixels to create
spacing.
Styling the Reset Score Button and Inserting Results with JavaScript
•Add class and styling to the reset score button, including a white background, no
border, increased font size, padding, and a pointer cursor.
•Adjust the padding values to create more space inside the button.
•Use JavaScript to generate the code for the results and insert the player and
computer moves.
•Remove the fake result text and replace it with the JavaScript-generated code.
•Save the changes and test the functionality of the Rock Paper Scissors project.
•Learn how to organize the code into different files for better organization.
Organizing Code in Separate Files
•The current code is in one HTML file, making it difficult to read and mixing three
different languages.
•Steps to organize the code: - Separate JavaScript by creating a new file named "10-
dash-rock-dash-paper-dash-scissors.js". - Move JavaScript code from HTML file to
the newly created file. - Delete JavaScript code from HTML file. - Load JavaScript file
onto the webpage using the "src" attribute of the script element. - Save HTML file and
observe that the project functions the same way, but with better code organization.
•The "src" attribute can also use file paths, allowing JavaScript files to be placed in
folders for easy accessibility.
•Multiple script elements can be used to split JavaScript code into multiple files and
load them onto the page sequentially.
Separating and loading CSS code using the link element
•To separate CSS code from HTML, create a new folder called "styles" and save the
CSS file inside it.
•Use the link element instead of the style element to load the CSS file onto the
website.
•The link element has two attributes: REL, which denotes the type of file being loaded
(set to "stylesheet" for CSS), and Href, which specifies the file path of the CSS file.
•Separating code into separate files improves code readability and makes it easier to
maintain.
Learning Arrays and Loops in JavaScript - Exercise
•We learn about the class list property to control the class attribute of an element.
•We finish our rock paper scissors project and learn how to organize JavaScript and
CSS code into separate files.
•We create a new file named "11-arrays-and-loops.html" and copy the previous
lesson into it.
•We change the title of the file to "Arrays and Loops" and remove all CSS and
JavaScript code.
•We open the file in the browser using live server and open the console.
•We create our first array with three numbers: 10, 20, and 30.
•To access a specific value in an array, we use square brackets with the index
representing the position in the array (zero-based indexing).
•Syntax rules for creating an array include using open and closed square brackets,
separating values with commas, and potentially using multiple lines.
•Any type of value can be stored in an array, including numbers, strings, booleans,
and objects.
•To check if a value is an array, use the code Array.isArray([]), which will return true if
it is an array.
•Arrays have properties and methods, such as "length" to determine the number of
values in the array.
•The "splice" method removes a value from the array based on the index and the
number of values to remove.
•Practical examples of using arrays include creating a to-do list project in a web
browser.
Creating a To-Do List Project
•The final version of the project includes the ability to add a to-do, select a due date,
and delete tasks when completed.
•The first version of the project allows users to add a to-do in a text box and displays
it in the console after clicking "add".
•The JavaScript file is loaded into the HTML file using the "SRC" attribute.
•The project is opened in a browser using the Live Server and the console is opened
for debugging.
Creating HTML elements and writing JavaScript for a to-do list
•To rearrange the windows for the final design, start by creating HTML elements.
•Begin by creating a paragraph element inside the body tag, with the text "to do list".
•Create a text box using the input tag and add a placeholder attribute with the value
"to do name".
•Add a button using the button tag with the text "add".
•When the add button is clicked, get the text from the text box and add it to the array.
•To display user input in the console, resize the browser window and use the
'console.log' function.
•Use the 'push' method to add user input to the to-do list array.
•Use 'console.log' to display the entire array with the added to-do items.
•Reset the text box by changing the value property to an empty string.
•In the second version, display the user input on the web page instead of the
console.
•Learn and utilize loops in JavaScript to display each value from the array on the web
page.
Looping and Console Output in JavaScript
•We use the keyword "let" to create a variable named "I" and set it equal to 1.
•To create a loop, we use the keyword "while" followed by brackets and curly
brackets.
•Inside the loop, we use the code "console.log" to display the variable "I" in the
console.
•The loop continues as long as a condition inside the round brackets evaluates to
true.
•In this case, the condition checks if "I" is less than or equal to 5.
•We update the variable "I" by incrementing its value by 1 inside the loop.
•The loop stops when "I" becomes greater than 5, resulting in false as the condition.
•A while loop is a type of loop that continues running its code as long as a specified
condition is true.
•The syntax for a while loop consists of the keyword "while" followed by round
brackets and curly brackets.
•The code inside the round brackets is the loop condition, while the code inside the
curly brackets is the loop body.
•The loop variable is the variable that is incremented with each iteration, ensuring the
loop ends at some point.
•Any variable created within the curly brackets of a loop has a limited scope and
exists only within the loop.
•The syntax for a for loop involves the keyword "for" followed by round brackets and
curly brackets.
•Inside the round brackets, there are three components: the loop variable
initialization, the loop condition, and the increment step.
•A for loop is typically used when the number of iterations is known or the loop needs
to iterate through a range of values.
Looping and its variations
•The "for" loop is a shorter and more organized version of the "while" loop. It
combines the loop variable, condition, and increment step in a concise format.
•For standard loops with a loop variable, condition, and increment step, it is
recommended to use the "for" loop.
•Non-standard loops, such as generating random numbers until a certain condition is
met, are better suited for the "while" loop.
•Looping through an array involves iterating through each value of the array and
performing an action with each value.
• Generate a subject title: "Looping through an Array in JavaScript"
•Note: The code provided demonstrates how to loop through an array in JavaScript
using a for loop. The loop iterates through each index of the array, starting from index
0 and ending at the last index. Inside the loop, the value at each index is accessed
using the index variable. This value is then saved in a variable and displayed in the
console. This technique allows for performing actions on each value in the array. The
text also mentions shortcuts for looping through an array.
Introduction to the accumulator pattern in JavaScript
•Instead of checking if index is less than or equal to the length of the to-do list minus
one, we can shorten this to index less than to-do list length.
•Naming the loop variable as I instead of index can also be done as a shortcut.
•To calculate the total of all numbers in an array, the technique we can use is the
accumulator pattern.
•The first step of the accumulator pattern is to create a variable to store the result,
commonly called the accumulator variable.
•We loop through the array, using the loop variable to access each value and save it
in a variable.
•We then add each number to the total by using the "total += number" shortcut.
•The first part explains how to create a copy of an array with doubled numbers using
the accumulator pattern.
•The writer emphasizes that the accumulator variable can be of different types,
depending on the problem being solved.
•The second part introduces creating a dynamic to-do list using HTML and
JavaScript.
•The writer demonstrates how to add items to the list and have them appear on the
webpage by updating the array.
Generating HTML code from an array and displaying it using the DOM
•To display an array of to-dos on a webpage, we need to loop through the array,
create HTML code for each to-do, and then use the DOM to put the code on the
page.
•To make looping easier, we can make a copy of the array and use a for loop to
iterate through it.
•Inside the loop, we can retrieve the string for each index and create HTML code
using a template string with a paragraph element.
•We can combine all the HTML code together using the accumulator pattern, storing
the result in a variable.
•After the loop, we can log the variable to see the combined HTML code.
•Finally, we can use the DOM to put the HTML code on the webpage by creating an
element for it.
Creating a To-Do List with HTML and JavaScript
•Unlike a paragraph, a div element does not add extra space above or below and has
no default styling.
•The HTML content of the to-do list is inserted into the div element using the
innerHTML property.
•Adding a new to-do does not update the HTML on the page, so the code to display
the to-do list needs to be run again.
•A function named "renderToDoList" is created to display the to-do list on the page.
Creating a To-Do List with Interactive Features
•We start by defining a function to render the to-do list on the page.
•By calling the function "render to-do list" and brackets, we display the initial to-do list
on the page.
•Each time a new to-do is added, we refresh the list by calling the "render to-do list"
function again.
•The "render to-do list" function loops through an array and generates HTML using
JavaScript.
•We create a final version of the to-do list with additional features like due dates and
a delete button.
•To add a delete button, we simply append it inside the paragraph element for each
to-do item.
•We reformat the HTML for readability by adding new lines and placing the content
and delete button on separate lines.
•Template strings allow for multi-line strings, which helps improve the code's
readability.
Using JavaScript to Generate HTML and Create Functionality
•To add functionality to a delete button in HTML generated using JavaScript, we use
the on click attribute to run JavaScript code when the button is clicked.
•The JavaScript code uses the splice method to remove a value from an array, using
the index provided by a loop variable.
•The splice method takes two arguments: the index to remove and the number of
values to remove.
•After updating the array, the updated list is displayed on the page using the render
to-do list function.
•The delete button successfully removes the corresponding value from the list when
clicked.
•Moving on to adding the due date feature, an additional input element is added to
the HTML, with the type attribute set to "date" to create a date selector input.
Updating To-Do List to Include Due Dates
•In order to include due dates for each to-do item, we will convert the to-do list into an
array of objects.
•Each object will have a "name" property to represent the task and a "due date"
property to indicate the deadline.
•In the render function, we will modify the loop to handle the object format of each to-
do item.
•The name and due date will be extracted from the object using object destructuring
to simplify the code.
•A shortcut using curly brackets will be used to extract multiple properties from the
object at once.
•The add to-do function will retrieve the name and due date from the input fields and
store them in the list.
Code Refactoring and CSS Styling in a JavaScript To-Do List
•We create a constant date input element by using the document.querySelector
method to select the element with the class "js-do-date-input".
•To retrieve the selected due date from the date input element, we use the value
property and assign it to a constant called due date.
•The addition of a to-do now involves adding an object that includes a name property
(using the variable name) and a due date property (using the variable due date).
•The project now allows adding and removing to-dos, and the final design is achieved
by adding CSS in a separate file within the styles folder.
Styling a To-Do List with CSS Grid
•To load the CSS file, use the link element with the attributes "style sheet" and "href"
to specify the file location.
•Start by changing the font family of the text on the page to Arial.
•Add more to-do items to the list by typing them in and selecting a date, then clicking
"add".
•To create a grid layout for the to-do list, add a class "to-do-grid" to the div element.
•In the CSS, style the "to-do-grid" class using display: grid and grid-template-columns
to set the number and size of columns in the grid.
•Each element inside the grid div will be placed in the corresponding column. If there
are more elements than columns, a new row will be created.
•The writer then moves on to layout the inputs and add button in a grid by wrapping
them in a div element and applying grid styles.
•Finally, the writer adjusts the spacing within the grid by using the properties column-
gap and row-gap, setting both to 10 pixels.
Styling Inputs and Buttons - Detailed Notes
•To add space between two separate grids, use margin at the bottom to style the 'to-
do-input-grid' and add some margin under that grid (margin-bottom: 10 pixels).
•Start styling the inputs by adding a class name 'input' and 'do-date-input' to the
respective elements.
•Apply styling using CSS for '.name-input' and '.do-date-input'.
•Style the add button by adding a class 'add-to-do-button' and apply styling using
CSS for '.add-to-do-button'.
•Style the delete buttons by adding a class 'delete-to-do-button' in the JavaScript file,
then apply styling using CSS for '.delete-to-do-button'.
Styling a Delete Button and Aligning Text and Button Vertically
•The design uses the color dark red for the delete buttons.
•The grid style property align-items: center is used to vertically align the text and
button in the center.
•The align-items property is changed back to stretch to make the grid stretch
vertically.
•The text and button are not vertically aligned in the center. To align them, the align-
items property is used with the value center.
•The ad button no longer stretches to match the inputs. To solve this issue, the align-
items property is changed back to stretch to make the grid stretch.
•The current tab is switched to "11 arrays and loops.html" and other tabs are closed.
•Creating a copy of the array variable doesn't create a copy of the values.
Array References, Array Slice, Destructuring, and Loop Features
•Arrays are references, so modifying one array also modifies other arrays that point
to the same array in memory.
•To avoid this behavior, the slice method can be used to create a copy of the values
in an array.
•The continue statement allows for skipping one iteration of the loop.
Various Uses of Loops in JavaScript
•The "continue" keyword allows skipping the rest of the code in a loop and continuing
with the next iteration.
•Using the remainder operator (%) helps determine if a number is divisible by another
number.
•By checking if the remainder of a number divided by three is equal to zero, we can
skip numbers that are divisible by three.
•When using "continue" in a while loop, the increment step must be done manually to
avoid an infinite loop.
•The increment step in a for loop is done automatically after every iteration.
•The cons, numbs equals array, and one, one and three.
•Using the loop, an array can be created with each number doubled.
•The function called "double array" loops over the given parameter array.
•Using a return statement in the function ends the loop and returns the result.
•A return statement can also be used to break out of the loop if a specific condition is
met.
•This lesson covers arrays, loops, and the use of functions in manipulating arrays.
Advanced Functions and Using Functions as Values
•We learned the accumulator pattern for loops and created a to-do list project.
•We explored additional features of loops such as break, continue, and using loops
inside a function.
•We need to create a new file for this lesson and copy the code from the previous file.
•Change the title to "Advanced Functions" and remove the previous JavaScript code.
•We can save a function in a variable using the syntax `var functionName = function()
{ ... }`.
•Functions can be called using brackets after the variable name, e.g.,
`variableName()`.
•Anonymous functions don't require a function name and can be used when the
function is accessed through a variable.
•Hoisting allows calling a function before it is defined in the code, but it doesn't work
for functions saved in variables.
•Functions saved inside objects are called methods and can be called using dot
notation.
•Anonymous functions can be used when there is no need to access the function by
name.
•Values can be passed into a function as parameters, allowing them to be used like
variables.
•The passed function can be called and used within the containing function.
•JavaScript has a feature called set timeout that allows a function to be executed in
the future.
•Set timeout takes two parameters: a function and a time delay for execution.
Understanding Asynchronous Code in JavaScript
•The first parameter of the set timeout function specifies the code to be executed in
the future.
•The set timeout function sets up a timer and waits for a specified amount of time
before calling the specified function.
•The second parameter of the set timeout function specifies the time to wait before
running the function, in milliseconds.
•Asynchronous code, like set timeout, allows the computer to move on to the next
line of code without waiting for the timer to finish.
•Synchronous code, on the other hand, requires the computer to wait for each line to
finish before moving to the next line.
•All code written in JavaScript is synchronous, except for the parts that use
asynchronous features like set timeout.
Introduction to Asynchronous Code and Set Interval Function
•The first parameter of set interval is the function to be executed, and the second
parameter is the time delay in milliseconds.
•The function specified in set interval will be executed every three seconds in the
future.
•Set interval is also asynchronous, allowing other code to run without waiting for it to
finish.
•Inside the section, change the load to "12 rock paper scissors".
•Open the file with the "lesson 12 JavaScript" and replace the previous file being
loaded in the HTML.
•Save the changes and open the file in the browser by right-clicking and selecting
"open with live server".
•Go back to "super simple.dev" and create an "autoplay" button next to the "reset
score" button.
•In the CSS file, add a style for the "auto-play-button" class, similar to the style of the
"reset score" button.
•Make the button interactive by adding an "onclick" attribute and a function called
"autoplay" that will be created in the JavaScript file.
•Create the "autoplay" function in the JavaScript file, above the "play game" function.
•Inside the "autoplay" function, use the "setInterval" function to run a code every
second. Use a time interval of 1000 milliseconds or one second.
Automatically playing a game with start and stop functionalities
•Inside a function, the game can be automatically played by using the "play game"
function.
•Before starting the game, a random player move should be generated using the
"pick computer move" function.
•To initiate the game automatically, a variable "is auto playing" should be created and
set to false initially.
•The game will start if "is auto playing" is false and the necessary code will be
executed. The variable "is auto playing" will be set to true.
•A new variable "interval ID" should be created outside the function to store the ID
returned by the "set interval" function.
•To stop the automatic gameplay, "clearInterval" function can be used with the saved
"interval ID".
Using the forEach method for array looping
•To stop the interval, change the autoplaying property to false and save.
•The function passed to forEach has a parameter that represents each value in the
array.
•The function saves each value in the parameter and runs the function.
•The forEach method is considered the preferred way to loop through an array.
Using the forEach method to loop through an array
•The index parameter in the function represents the position of the value in the array.
•To use the forEach method, the array is specified followed by dot notation and the
forEach method.
•To use the forEach method, iterate through an array using a loop and use the index
parameter.
•Use a forEach loop instead of a regular for loop to make the code more readable.
•Removing comments and unnecessary code improves the clarity of the forEach
method.
•The continue statement can be replaced with a return statement in a forEach loop to
skip certain iterations.
•The forEach loop does not have a break statement, so a regular for loop should be
used in such cases.
•Curly brackets are used to enclose the code inside the arrow functions.
•Arrow functions can be called the same way as regular functions by using
parentheses after the function name.
•Return statements work the same way in arrow functions as in regular functions.
•Arrow functions have some shortcuts such as optional round brackets for single
parameters and optional curly brackets and return statement for one-line functions.
Use of Arrow Functions in JavaScript
•They have a few shortcuts, such as removing the word "function" and using the
arrow symbol instead.
•Arrow functions are recommended when passing a function into another function, as
they make code easier to read.
•In the rock paper scissors game, an arrow function is used in the autoplay function
to improve code readability.
•However, in the function autoplay, the regular function syntax is preferred because it
enables hoisting and is easier to read.
•In the to-do list project, an arrow function is used inside the render to-do list function
for the forEach method to improve code readability.
•Similarly, the regular function syntax is preferred in other parts of the code for
readability and hoisting purposes.
Using arrow functions and addEventListener in JavaScript
•We can use arrow functions inside an object to create shorthand methods.
•Arrow functions have some differences compared to regular functions, which will be
explained later in the course.
•Rather than using the "onclick" attribute, a better way to run JavaScript code when
clicking a button is to use the addEventListener method.
•The addEventListener method has two parameters: the event we want to listen for
(in this case, "click") and the function to run when the event occurs.
•Event names can be found by looking at the attribute values in the HTML code.
Using addEventListener vs onclick attribute in JavaScript
•In the given example, the onClick attribute is used to assign a function to the click
event of a button.
•By using addEventListener, multiple event listeners can be added to the same
event. In the example, two click event listeners are added.
•Using addEventListener is considered a best practice over the onclick attribute due
to its advantages in flexibility and control over event listeners.
•The rock paper scissors project will be updated to use addEventListener instead of
onclick.
HTML Button Events
•The same process is followed for the paper and scissors buttons, with respective js-
paper-button and js-scissors-button classes.
•The playGame function is invoked with "paper" and "scissors" arguments for the
paper and scissors buttons.
Adding Event Listeners for Keyboard Inputs
•Let's save and remove the onclick attribute, save the HTML, and test the scissors
button.
•As exercises, let's switch the reset score button and autoplay button separately.
•Add an event listener to the body using the key down event.
•Get the body element and add the event listener, passing the event as a parameter.
•Display "key down" in the console when a key is pressed on the page.
•Display the specific key that was pressed by accessing the event object's key
property.
•Check if the pressed key is "R" and play the game with rock if true.
•Add another branch to check if the pressed key is "P" and play the game with paper
if true.
Switching to addEventListener for Rock Paper Scissors and ToDo List projects
•In the Rock Paper Scissors project, different events are being listened for using
addEventListener.
•An event listener is added for the keydown event to check if the user pressed 'R', 'P',
or 'S' keys.
•Inside the event listener, different actions are performed based on the key pressed -
playing the game with rock, paper, or scissors.
•The event object is accessed using a parameter to get information about the event.
•In the ToDo List project, the add button is switched to use addEventListener.
•An event listener is added for the click event, which calls the addToDo() function
when the button is clicked.
•The delete buttons in the ToDo List project are also switched to use
addEventListener.
•An event listener is added for the click event on each delete button, which calls a
function to delete the corresponding ToDo item.
Adding Event Listeners to Delete Buttons in JavaScript
•However, make sure to place the HTML on the page first before adding the event
listener.
•To select all delete buttons instead of just the first one, use the
document.querySelectorAll() method.
•For each iteration in the loop, the forEach() method provides the value and index of
the element.
•To add an event listener to each delete button, use the addEventListener() method
and specify the event to listen to (click) and the function to run when this event
occurs.
Exploring Array Methods: forEach, addEventListener, filter, and map
•The code snippet demonstrates how to implement event listeners for the delete
buttons on a webpage using JavaScript.
•The use of querySelectorAll retrieves all the delete buttons on the page, and forEach
is used to loop through the list.
•The click event listener is added to each delete button, allowing the associated code
to be executed when clicked.
•The removal of the onclick attribute allows for a more efficient and scalable way to
handle button functionalities.
•The author's projects have been successfully improved using addEventListener
instead of onclick.
•The subsequent lesson will cover two additional array methods: filter and map.
•Filter is used to create a new array by filtering out negative numbers from an existing
array.
•The filter method iterates over each value in the array and executes the provided
function criteria.
•The inner function in filter returns either true or false, determining whether a value
will be added to the new array.
•The method "filter" is used to create a new array by removing certain elements from
the original array based on a given criteria.
•To filter out negative numbers from an array, an inner function can be used with a
conditional statement. If the number is positive, the function returns true and includes
it in the new array; otherwise, it returns false and does not include it.
•The logic for filtering can be simplified by using the code "return value >= 0", which
compares the value to zero and returns true or false accordingly.
•The method "map" is used to create a new array by performing a specific operation
on each element of the original array.
•When using "map", a function is provided with two parameters: the first parameter
represents each value in the array, and the second parameter represents the index.
•The return value of the function will be added to the new array created by "map".
•Using the value itself in the return statement allows for computations to be
performed on each element of the original array before adding it to the new array.
Shortcuts in Arrow Functions and the Concept of Closures
•The map function can transform an array by returning a new array with values that
have been doubled or manipulated in some way.
•In arrow functions, if there is only one parameter, the round brackets can be omitted,
making the code more compact.
•If an arrow function contains only one line of code, the curly brackets and the return
statement can be removed, and the code can be written on one line.
•In a closure, values like the index can be encapsulated and retained by the function.
'Subject': Notes on JavaScript Course
•Closures are a feature in JavaScript that allow a function to have access to variables
even after the function has finished executing.
•The set timeout and set interval functions allow for delayed execution of a function.
•Arrow functions and add event listeners can be used to improve projects.
•The course will focus on building bigger and more complex projects in the second
part.
•HTML and CSS full course is available for those who want to learn more.
•Support the channel by liking the video and recommending the course.