0% found this document useful (0 votes)
5 views37 pages

Cost of Cart

The document provides an overview of JavaScript fundamentals, including mathematical operations, string manipulation, HTML and CSS integration, and variable management. It covers topics such as order of operations, rounding numbers, string concatenation, and the use of comments. Additionally, it discusses the structure of HTML documents, the role of JavaScript in interactivity, and the implementation of conditional statements and algorithms for games like Rock Paper Scissors.

Uploaded by

kiboame27
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views37 pages

Cost of Cart

The document provides an overview of JavaScript fundamentals, including mathematical operations, string manipulation, HTML and CSS integration, and variable management. It covers topics such as order of operations, rounding numbers, string concatenation, and the use of comments. Additionally, it discusses the structure of HTML documents, the role of JavaScript in interactivity, and the implementation of conditional statements and algorithms for games like Rock Paper Scissors.

Uploaded by

kiboame27
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

JAVA SCRIPT IS RUN THROUGH CONSOLE

alert(‘hello’);

COST OF CART(maths javascript)

CALCULATIONS ARE RUN IN NORMAL MATHS

1ORDER OF OPERATIONS

 + - * / ARE OPERATORS
 ORDER OF OPERATION IS ALSO CALLED OPERATOR PRSIDENCE
 * / are calculated 1st then + - are calculated 2nd
 Add from left to right
 ( ) nUMBERS INSIDE THE BRACKETS are CALCULATED FIRST
 % - CANNOT BE CALCULATE _*_%
 1%= 1/100=0.01

2WEIRD BEHAVIOR OF MATHS IN JAIVA SCRIPT

 2,3,4 ARE CALLED INTERGERS


 2.2, 2.5 – DECIMALNUMBRS - FLOATING POINT NUMBERS(FLOATS)
 BEST WAY TO DEAL WITH FLOATS IS TO CONVERT DOLLARS TO CENTS E.G
20.95 + 7.99
28.939999999999998 INACURRATE
(2095 +799) / 100
28.94

3ROUNDOFF A NUMBER IN JAIVA SCRIPT

 CODE TO ROUND OF A NUMBER Math.round()


 E.g Math.round(2.2)
2
Math.round(2.8)
3

((2095 + 799) * 0.1) /100


2.894
Math.round((2095 + 799) * 0.1) /100
2.89

WORK IN TEXT

 STRING = TEXT = ‘hello’


 SPTRING IS WHAT IPPEARS IN THE POPUP

1SYTRAX RULES OF STRINGS

 REQUIRE A TEXT AND SINGLE QUOTE ‘’ E.g ‘hello’


 ADD SPRINGS TOGETHER E.g 'some' + 'text'
"sometext"

 WHEN YOU COMBINE TEXT TOGETHER IS CALLED CONCATENATION

2TYPE OF VALUES

 typeof E.g typeof 2

1st "number"

typeof 'hello'

2nd "string"

 'hello' + 3
"hello3" type of coercion

3STRING E.g

 '$' + 20.95 +7.99


"$20.957.99" incorrect
'$20.95' + 7.99
"$20.957.99" incorrect
'$' + (20.95 +7.99) order of operation
"$28.939999999999998"
'$' + ( 2095 + 799) /100 Math.round
"$28.94"

 'Items ( ' + (1 + 1) + '): $' + ( 2095 + 799) /100 -concatenation(breaking down then adding
together)
"Items (2): $28.94"

3 type of ways to create string


 ‘‘
 ““
 ` ` - template strings

TEMPLATE STRING

 Have 2 Special features


 1. Interpolation = insert a value directly to the string
 Interpolation is far better than concatenation
 `Items (${1 + 1}): $${(2095 + 799) / 100}`
"Items (2): $28.94"
 2. MULTI-LINE STRING
 `some
text`
"some\ntext" newline

ESCAPE CHARACTERS

 \’ - 'I\'M LERANING JAVASCRIPT'

"I'M LERANING JAVASCRIPT"

 \’’
 \n(newline character)

HTML CSS AND JAVASCRIPT TOGETHER

 HTML(HYPER TEXT MARKUP LANGUAGE) - CREATE THE CONTENT OF THE WEBSITE E.g button
 CSS(CASCADIND STYLE SHEETS)– CHANGES THE APPEARANCE
 JAVASCRIPT – MAKES IT INTERACTIVE

1HTML ELEMENTS

 TO CREATE A HTML ELEMENT U START < THEN ELEMENT NEME THEN >
 E.g <button> - called HTML TAG
 Opening tag -<button> closing tag - </button>

 ELEMENT INSIDE A ELEMENT E.g


<p>paragraph of <button>hello</button> text</p> - CALLED NESTING

 NEWLINE ACT AS A SPACE TO MAKE IT MORE READABLE AND FLEXIBLE

1.1CSS

 <style></style> - doesn’t appear in the page but it let us write css code
<link rel="stylesheet" href="styles/10-rock-paper-scissor.css">
 .css – file(hperlink)
 CSS SYTRAX
 Button called CSS SELECTOR(ELEMENT U WANT TO CHANGE)
-{}- inside CSS STTLE(HOW TO CHANGE THE APPEARANCE)
-LEFT SIDE CALLED CSS PROPERTY RIGHT SIDE IS CALLED VALUE

<style>
button{
background-color: red;
color: white;
border: none;
}

HTML ATTRIBUTE

 CHANGE THE BEHAVIOUR OF THE ELEMENT


 SYTRAX RULE
On the left it is ATTRIBUTE NAME on the right ATTIBUTE VALUE
<button title="tooltip">

 CLASS ATTRIBUTE ADDS A LABEL TO AN ELEMENT


.red-button{
background-color: red;
color: white;
border: none;

.blue-button{
background-color: blue;

</style>
<button title="tooltip" class=" red-button">
hello
</button>
<p>
paragraph of
<button class= "blue-button">hello</button> text
HTML STRUCTURE

 <!DOCTYPE html> - tells the browser to use a modern version of html for better features
 <html></html> - represent an entire webpage
 <head></head> - contain information about the page(not visible)
 <body></body> - represent everything visible on the page

<!DOCTYPE html>
<html>
<head>
<style>
.red-button{
background-color: red;
color: white;
border: none;
}

.blue-button{
background-color: blue;
}
</style>

</head>

<body>
<button title="tooltip" class=" red-button">
hello
</button>

<p>
paragraph of
<button class= "blue-button">hello</button> text
</p>
</body>

</html>

 <title></title> - SET THE TEXT IN THE TAP


1.2JAVASCRIPT

 CAN AlsO BE RUN THROUGH HTML


<script src="scripts/10-rock-paper-scissor.js">
 .js – file(hyperlink)
 <script></script>
<script>
alert('hello');
</script>
 Code in the script element run 1st when a page is loaded
 Or onclick=””
<button title="tooltip" class=" red-button"
onclick="
alert('good job');
"
 Code in the onclick run after when you click the button on the page

COMMENTS

 // - SINGLE LINE COMMENT


 PROVIDE MORE INFORMATION FOR PEOPLE READING THE CODE
// alert('hello');
 CALLED COMMENTIG OUT THE CODE
-USEFUL WHEN U DON’T WANT TO RUN THE CODE OR DELETE IT
 /**/ CALLED MULTI LINE COMMENT
 WRITE A COOMENT IN MULTIPLE LINE
 // AND /**/ ARE COMMENTS FOR ONLY JAVASCRIPT
 <!----> - COMMENT FOR html
<!---THIS IS A COMMENT-->

 /**/ - comment for also CSS


/*THIS A
COMMENT*
VARIABLES

 IS LIKE A CONTAINER YOU CAN A SAVE NUMBER OR STRING THEN USE IT LATER
 let create a variable
 Consol.log
let variable1 = 3;
console.log(variable1);

let calculation = 2 + 2;
console.log(calculation);
console.log(calculation + 2);

let result= calculation + 2


console.log(result);

let message = 'hello'


console.log(message);

 SYDRAX RULE FOR VARIABLES


 CANT USE SPECIAL WORD E.g let
 CANT START WITH A NUMBER
 CANT USE SPECIAL CHARACTERS BUT $ _
 CANT HAVE SPACES BETWEEN A VARIABLE NAME
 ; - MEAN IS THE END OF THE ISTRUCTION

 CHANGE VALUE SAVED IN THE VARIABLE(RE-ASSIGNING A VALUE) E.g


variable1 = 5;
console.log(variable1);
jj

variable1 = variable1 + 1;
console.log(variable1);

 SYNRAX RULES FOR RE-ASSIGNING


 DON’T USE THE WORD ‘let’
CART QUANTITY

<body>
<button onclick="
console.log(`cart quantity: ${cartQuantity}`); <!--template
string-->
">Show Quantity</button>

<button onclick="cartQuantity = cartQuantity + 1; /*reassigning the


value*/
console.log(`cart quantity: ${cartQuantity}`);
">add to cart</button>

<button onclick="cartQuantity = cartQuantity + 2;


console.log(`cart quantity: ${cartQuantity}`);
">+2</button>

<button onclick="cartQuantity = cartQuantity + 3;


console.log(`cart quantity: ${cartQuantity}`);
">+3</button>

<button onclick=" cartQuantity = 0;


console.log('cart was reset'); // STRING //
console.log(`cart quantity: ${cartQuantity}`);
">Reset Cart</button>
</body>
<script>
let cartQuantity = 0; = do this 1st

 VARIABLE RE-ASSIGNMET SHORTUTS

<button onclick="cartQuantity = cartQuantity + 1; or


cartQuantity ++ ;
 Are the same
 E.g +=2 variable = variable + 2
-=2 variable = variable -2
*=2 variable = variable * 2
/=2 variable = variable / 2
++ variable = variable + 1
-- variable = variable – 1

NAMING CONVENTION(camelCase)

 COMBINING NAMES TOGETHER AND CAPATILIZE EVERY WORD EXCEPT THE 1 ST WORD e.g
cartQuantity
 camelCase is the standard naming convection for javascript
 PascalCase is another naming convention
 kebab-case cannot work in javascript because the dash is used as a subtraction sign
 We use kebab-case in html and css and file naming
 Snake_case is not used in used in javascript

3 WAYS TO CREATE VARIABLES JAVASRIPT

 1ST WAYS IS TO USE let


 2ND WAY IS TO USE const
 const you cannot change the value later. The value stay constant
 makes the code safer and easy to understand
 Best practice const as default and use let when we know we’re going to change the
value

let variable1 = 3; // value is goona change so we


use let

console.log(variable1);

const calculation = 2 + 2; // constant


console.log(calculation);
console.log(calculation + 2);

const result= calculation + 2


console.log(result);

const message = 'hello'


console.log(message);

variable1 = 5; // value is changed


console.log(variable1);

variable1 = variable1 + 1;
console.log(variable1);
 3rd way is to use var (variable)
 Is the original way to create variable
 We no longer use var in new javascript code because it has problems problems

Typeof

 WE USE typeof TO CHECK THE TYPE OF VALUE SAVED IN THE VARIABLE


console.log(typeof variable1);
console.log(typeof message);
 Result appear in chrome under console
1. typeof variable1 = number
2. typeof message = string

BOOLEANS AND IF-STATEMENTS

 BOOLEANS ARE ANOTHER TYPE OF VALUE


 THE ARE ONLY W BOOLEAN VALUES – true, false
 BOOLEAN VALUE REPRESENT WHETHER SOMETHING IS TRUE OR FALSE e.g
console.log(3 > 5);
console.log(3 < 5)

 Result appear in chrome under console


 3 > 5 false, 3 cannot be greater 5
 3 < 5 true, 3 is less than 5
 Syntax rule for Booleans
 We don’t surround Booleans with quotes(‘true’) because it will be a string
 > is called a comparison operator
 Comparison operator
 > - greater than
 < - less than
 >= - greater than or equal to
 <= - less than or equal to
 === equal to
o == double equal converts both values into the same type

console.log( 5 == '5'); //Boolean and string (true)


o Javascript we only use === to avoid conversion because a number ad
string are not equal
 !== - not equal to
o != we also don’t use it javascript
IF-STATEMENT

 LETS US WRITE MULTIPLE GROUPS OF CODE AND THEN DECIDE WHICH CODE TO RUN

if (true) {

console.log('hello');
 if true 'hello' appear in console, if false it doesn’t display
in console

if (true) {
console.log('hello');

} else {
console.log('else')
}
 if true 'hello' appear in console
 if false 'else'appear in console

e.g driving age

if (30 >= 18) {


console.log('you can drive'); //you can drive

} else {
console.log('you cannot drive');

 syntax rule for if-statement


 we type if then,
 ()- boolean value called condition
 {}-code to run called branches
 WE CAN HAVE MORE THAN ONE CONDITION E.g

if (17 >= 18) {


console.log('you can drive');
}
else if (17 >=16) {
console.log('almost there'); //almost there
}

else {
console.log('you cannot drive');
}

 You can use age as a constant


const age = 17;
if (age >= 18) {
console.log('you can drive');
}
console.log('almost there');
}

else {
console.log('you cannot drive');
}

ROCK PAPER SCISSORS

 STEPS YOU FOLLOW IS CALLED ALGHORITHM


 STEPS(algorithm) –WHEN WE CLICK A BUTTON
1. COMPUTER RANDOMLY SELECTS A MOVE
2. COMPARE THE MOVES TO GET THE RESULT
3. UPDATE THE SCORE
4. DISPLAY THE RESULT AND SCORE IN THE POPUP
 Following the code line by line is called tracing the code
 Math.random – generate a random number between 1 and 0
 1> Number=>0
 Space between 0 and 1
 Rock 1/3 – between o and 1/3
 Paper 2/3 –between 1/3 and 2/3
 Scissor 1- between 2/3 and 1
 Scope –limits were a variable exist, and help us avoid naming conflict
 {} – any variable created in this brackets only exist there not outside the bracket E.g

if(randomNumber >= 0 && randomNumber <1 / 3){


const computerMove = 'rock';
}
else if(randomNumber >= 1 / 3 && randomNumber < 2 / 3){
const computerMove = 'paper';
}
else if(randomNumber >= 2 / 3 && randomNumber < 1){
const computerMove = 'scissor';
}
console.log(computerMove);

o So variables need to be created outside the {}-bracket.

1. COMPUTER RANDOMLY SELECTS A MOVE


const randomNumber = Math.random( );

let commputerMove = ''; //VARIABLE

if(randomNumber >= 0 && randomNumber <1 / 3){ //IF-STATE &


AND GATE
computerMove = 'rock'; //RE-
ASSIGNING A
}
else if(randomNumber >= 1 / 3 && randomNumber < 2 / 3){
computerMove = 'paper';
}
else if(randomNumber >= 2 / 3 && randomNumber < 1){
computerMove = 'scissor';
}
console.log(computerMove);

2. COMPARE THE MOVES TO GET THE RESULT


let result = '';

if (computerMove === 'rock'){ //IF-STAT &


COMPARI
result = 'Tie';
}
else if (computerMove === 'paper'){
result = 'Loss';
}
else if (computerMove === 'scissor'){
result = 'Win';
}

4. DISPLAY THE RESULT IN THE POPUP


alert(`You picked rock. Computer picked ${computerMove}. You
${result}`); //TEMPLATE STR
LOGICAL OPERATORS

 AND operator &&


 Check if Boolean values from left to right are true
consol.log(true && true);
e.g conso.log(0.2 >= 0 && 0.2 < 1 / 3); // true
 OR operator ||
 Check if at least one side is true
consol.log(false || true); // true
 NOT operator !
 Only uses one Boolean value
 AND IT FLIPS IT INTO THE OPPOSITE
consol.log(!true); //false

TRUTHY AND FALSELY VALUE

 FALSELY VALUE BEHAVE LIKE FALSE – FALSE, 0, ‘’ , NaN, undefined and null ANY VALUE THAT IS
NOT HERE IS TRUTHY VALUE

if (cartQuantity) =5; //truthy


consol.log('cart has product');
 NaN- when you do faulty math
consol.log('sweet' / 2);
 Undefined-
let variable1
console.log(variable);

SHORTCUT OF IF STATEMENT

 TERNARY OPERATOR ?:
 similar to if else-statement
true ? 'truthy' : 'falsy'
 1st word is the condition; ? ” if branch , : “ else branch
 GUARD OPERATOR &&

 DEFAULT OPERATOR ||

 USE IT AS DEFAULT
FUNCTIONS

 FUNCTION LET US REUSE CODE AND MAKE IT LEANER BY REMOVIND DUPLICATING


<script>
function function1(){ /original code/DOESN’T RUN
console.log('hello');
console.log(2 + 2);
}
function1(); // run the code from the orig
reus
function1();

 SYNTAX RULE
 THE WORD FUNCTION CREATES A FUNCTION
 THE CODE INSIDE THE FUNCTION DOESN’T RUN IT CREATES
 PICK VERB FOR NAMING
 FUNCTIONS ALSO CREATE SCOPES

RETURN STATEMENT

 LET USE GET A VALUE OUT OF A FUCTION


return 5; //can use a number or string.
written in
a function pickComputerMove
}
</script>

<button onclick=" //scissors value is =5


console.log(pickComputerMove());
 SYNTAX RULE
 TYPE THE WORD RETURN AND A VALUE AND YOU WILL GET THE VALUE OUT OF THE
FUNCTION
 WE CAN ALSO RUTURN A..
o A CALCULATION return 2 + 2;
o A VARIABLE return variable1;
o Or anything result in a value Math.random();
 AFTER USING THE RETURN STATEMENT IT ENDS THE FUNCTION IMMEDIENT

ROCK PAPER SCISSORS ALTERNATIVE

 FOLLOWING THE CODE LINE BY LINE IS CALLED TRACING THE CODE


 GLOBAL VARIABLE(RAN OUR 1ST CODE) & RETURN (ALTERNATIVE CODE)
1. 1st code (GLOAL VARIABLE)
<button onclick="
console.log(pickComputerMove());

<script>

let commputerMove = ''; // WRITTE OUTSIDE AVOID


SCOPE

function pickComputerMove(){
o CODE RUN FROM TOP TO BOTTOM
2. ALTERNATIVE ODE(RETURN)
<button onclick="
const computerMove = (pickComputerMove()); //what we return
computeMove are 2
diff

<script>

function pickComputerMove(){
const randomNumber = Math.random();

let commputerMove = ''; //scope- variable is not


affected bcause it is returned

if(randomNumber >= 0 && randomNumber <1 / 3){


computerMove = 'rock';
}
else if(randomNumber >= 1 / 3 && randomNumber < 2 / 3){
computerMove = 'paper';
}
else if(randomNumber >= 2 / 3 && randomNumber < 1){
computerMove = 'scissor';
}

return computerMove; //return statemet


}
 The two computerMove do not conflict because they are different variable. The other is
in a function scope the other is not

 TRACING THE CODE OF THE ROCK PAPER SCISOOR ALTERNATIVE


 When clicking the button(e.g rock), the code is going to run the function(pick
ComputerMove) then return what is inside (computerMove) to were we called the
return function value(pickComputerMove). Then after we save the return
value(pickComputerMove) into a new variable(computerMove).
 THE 2 (computerMove) ARE DIFFERENT BECAUSE ONE IS WRITTEN IN A SCOPE{} AND
ONE NOT

PARAMETERS

 OPPOSITE OF A RETURN STATEMENT


 PARAMETERS PUTS A VALUE IN A FUNCTION

funtion calculateTax(parameter1){ //parameter is = 2000


console.log( parameter1 * 0.1);
}
calculateTax(2000);
 PARAMETER NAME
 NO SPECIAL WORDS, CANT START WITH A NUMBER , CANT USE SPECIAL CHARACTER
EXCLUDING($ AND _) BEST PRACTISE IS TO USE camelCase
 PUTTING A VALUE IN A FUNCTION IS CALLED PASSING A VALUE INTO A FUNCTION (); IT CALLED
A ARGUMENT
 WHEN A FUNCTION HAS A PARAMETER IT IS CALLED TAKING A PARAMETER
 FUNSTION HAS A NUMBER IT IS CALLED TAKING A NUMBER
 YOU CAN HAVE 2 PARAMETERS
funtion calculateTax(parameter1, cost = 0.1 ){
console.log( parameter1 * cost);
}
calculateTax(2000, 0.2);
calculateTax(5000)
 calculateTax - Parameter1= 200 , cost =0.2
 calculateTax - 5000 is also = parameter1 but the is no value for cost so it gives an
error(NaN)u must set a default which is 0.1 for cost
 = 0.1 is a default

OBJECTS

 GROUPS MULTIPLE VALUES TOGETHER


const product = { // OBJECTS

name : 'socks', // COMMA TO SEPARATE THE


PROPERTY

price : 1040
}
console.log(product);
console.log(product.price);
 Code on the left(name & price) is called PROPERTY

}
console.log(product);
console.log(product.price);
product.name = 'cottonon' ; //changed the value
console.log(product);

 SYNTAX RULES
 Start with a { -open then end - }
 : - separate the value and a property. Al together it is called PROPERY-VALUE PAIR
 Product.price – is called a DOT NOTATON or use
 Bracket notation –let use properties that don’t work in DOT notation e.g
delivery-time : '11 h 0' , // doesn’t work. Think it’s a
subtract
['delivery-time'] : '11 h 0' //property value pair

}
console.log (product.delivery-time);
console.log(product['delivery-time']) //bracket notation

delete product.name //delete a property e.g name


console.log(product)

 NESTED OBJECT – object inside a object


 Make our values more organised

rating : {

stars : 4.5 ,
count : 86
}
console.log(product.rating.stars)
console.log(product.rating.count)

 FUNCTIONS ARE ALSO VALUES THEY CAN BE SAVED IN A OBJECT. Function inside a object are
called(METHOD) e.g console.log is also a method(console is a object .log is a function saved
inside console object) and also Math.random

fun : function function1(){


console.log('fuction inside a object')
}
product.fun(); //DOT NOTATAION

BUILD- IN OBJECTS

 Math and console ARE BUILD-IN OBJECT BECAUSE THEY ARE PROVIDED BY THE LANGUAGE
 JSON and localStorage are 2 MORE BUILD-I OBJECT
 JSON(JavaScript Object Notation)
 IT IS A SYNTAX SIMILAR TO A JAVASCRIPT OBJECT BUT LESS FEATURES E.g all properties and
strings must use “ ” . And does not support functions in the object
 JAVASCRIPT OBJECT only make sense in javascript on the other hand JSON can be
understood by all programming languages
 We use JSON when we send data to between computers and also when we store data
 Build-in JSON object helps use convert javascript object to JSON (JSON.stringfy)
o Only support strings
JSON.stringify(product) // product value become a string
 Convert JSON back to a javascript object
JSON.parse(JSON.stringify(product))

 localStorage
 saves values more permanently
 only save strings
localStorage.setItem('message', 'hello'); //set item

console.log(localStorage.getItem('message')); //get item


 when u want to remove the value I the local storage
localStorage.removeItem();


3. UPDATE THE SCORE(ROCK PAPER SCISSOR)

score.win = 0;
score.lose = 0;
score.tie=0;
localStorage.removeItem('score')

">reset button</button>

const score = JSON.parse(localStorage.getItem('score')) || { NULL ||-


DEFAULT OP

win : 0,
lose : 0,
tie : 0
};

if(result === "win"){


score.win += 1;
}
else if(result === 'lose'){
score.lose += 1;
}
E
lse if(result === 'tie'){
score.tie += 1;
}
localStorage.setitem('score', JSON.stringify(score))

alert(`you picked ${playerSet}. Computer picked ${computerMove}. You $


{result}
win:${score.win} lose:${score.lose} tie:${score.tie}`)
}
 when something does not exist it going to give us null(e.g rock paper scissor)
o score=null then - score === null(true) - !score(true)
o score=rps then – score ===null(false) - !score(False)
o ||(DEFAULT OPERATOR)-when one side is falsey it will default the truthy side

Null vs undefined

 BOTH REPRESENT SOMETHING DOES NOT A VALUE


 WE USE NULL WHEN WE INTENTIONALLY WANT SOMETHING TO ME EMPTY
 FUNC(UNDEFINED) – DEFAULT
 FUNC(NULL)-NULL

OBJECTS ARE REFERENCES

const object1 = {
message: 'hello'
};
const object2 = object1
object1.message = 'good job'

const object3 = {
message: 'goodjob'
}
console.log(object1 === object3); // false - cant compare object(ref)
directly
console/log(object1 === object2) // true –both point to the same
reference
 Object1 is actually a reference the value in the object is saved in the computer memory .So
reference is like a shortcut pointing the location of the value. JUST LIKE A COMPUTER
SHORTCUT
 Object2=object1 does not make a copy of the object it makes a copy of a reference point to the
object(it is called = COPY BY REFERENCE).
 Both point to the same object 2 = object1 = ‘hello’
 object1.message = 'good job'
o now object1 and object2 are both = ‘good job’

SHORTCUT

const object4 = {
message: 'goodjob'
}
const message = object4.message
const {message} = object4 //called destructuring

const {message} = object4


const object5 ={
// message: message //two similar names//
message // message = ‘goodjob’//called – shorthand
property

method: function function1(){ //function and function name is not


required
console.log('method')
}
method(){ //shortcut names is called- shorthand
method
console.log('method')
}

DOCUMENT OBJECT MODEL(DOM)

 IS ANOTHER BUILD IN OBJECT CALLED DOCUMENT OBJECT


 Document and web page are linked together
document.body.innerHTML = 'good job'
document.title = 'changed'

PROPERTIES AND METHOD

 document.title = <tittle></title> - linked to the title of the webpage


 use document.title to get the title or to change the title
 document.body is the <body></body>
 We can have html elements inside javascript
 DOM combines html and javascript together
 When a html element(<body>) is inside our javascript(document.body), the html element is
converted into an javascript object
 document.body.innerHTML – controls all the html inside the body element(<body></body)
document.body.innerHTML= '<button>good job</button>'
 all the previous html is replaced with the button good job’
 inner.HTML replaces previous html code

method of the document object

 method is a function saved inside ab object


 document.queryselector()
 let use get any element from the page and put it inside the javascript e.g

document.querySelector('button') //got the 1st element writeen


<button >hello</button>
1. every html element has property .innerHTML e.g
document.querySelector('button').innerHTML = 'changed'
//now button= changed
2. when the is a second button
<button>hello</button> //1st
<button class="js-button">second button</button> //2nd

document.querySelector('.js-button') or
const buttonElement = document.querySelector('.js-button')

 class attribute –start the class with a js- to make it clear it used in javascript
 class selector (.js-button)-it is also used in css

DOM PROJECT

YOUTUBE SUBSCRIBE BUTTON

 STEPS – when we click the button


1. If the text is subscribe change to subscribed
2. Otherwise change it back to subscribe

function subscribeElement(){
let buttonElement = document.querySelector('.js-subscribeButton')

if(buttonElement.innerText === 'Subscribe'){


buttonElement.innerHTML = 'Subscribed'
}else{
buttonElement.innerHTML = 'Subscribe'
}
}

SHIPPING CALCULATOR

 HTML ELEMENT FOR A TEXTBOX - <input>


 grey text(inside the box) is called a - placeholder

<input placeholder="Cost of order">


<button>Calculate</button>
 STEPS-WHEN WE CLICK THE BUTTON
1. GET THE TEXT IN THE TEXT BOX
2. IF AMOUNT <$40, ADD $10
3. DISPLAY TOTAL ON THE PAGE
 For input element we don’t use .innerHTML we use .value
 Whenever we get a value from the DOM the value will be string
 To change the value to be a number u will use Number()
let cost = Number(inputElement.value);
 To change a value to a string you use String()
 WHEN YOU PRESS key(ENTER)-
 onkeydown=”” run javascript when u press a key
o clicks and keydowns are events
o onclick and onkeydown are event listeners
 event – is a javascript object which contain information about an event object
onkeydown="console.log(event)">key:“” –event for typing
number&Enter
 EVENT DOES NOT EXIST IN A FUNCTION SO YOU MUST USE A PARAMETER
unction handleKeyDown(event){
if(event.key === 'Enter'){
calculateTotal();

CSS SUBSCRIBE BUTTON AND THE SHIPPING CALCULATION

 A element can have multiple of classes you just separate with space

class = "js-subscribe-buttons subscribe-button"> //2 classes


 change CSS when clicking a button
 classList – gives us control of the class attribute
o .add() add a class to an element

if(SubscribeElement.innerText === 'Subscribe'){


SubscribeElement.innerHTML = 'Subscribed'
SubscribeElement.classList.add('is-subscribed');//class added
} //don’t add a dot(.is-) cuz it only makes sense in
queryselector
o .remove() removes a class to an element

else{SubscribeElement.innerHTML = 'Subscribe'
SubscribeElement.classList.remove('is-subscribed')//class removed
}

CSS ROCK, PAPER, SCISSOR

 for image - <img src=””>


ARRAY AND LOOPS

 Array is a list of values


const myArray = [10, 20, 30]
 Position in the array(called index)
 Position number start from 0,1,2,3....
o Number is called a index e.g index 1,2,3,4….
console.log(myArray[1]) //number[] represent the postion in the
array
 change a value
myArray[1] = 99
 an array is value and a special type of object
[1, 'hello', true, {neme: 'socks'}, [1, 2]]
 to check something if it is an array
Array.isArray([1, 2]) //true
 since an array is an object is has methods and properties
 .length – check the amount of arrays
console.log(myArray.length) // 3
 .push – adds a value in the end of an array
console.log(myArray) //[99, 20, 30, 1000]
 .splice- removes a value in the array
myArray.splice[0, 1]
o 1st number-is the value with want to remove
o 2nd number-how many values we want to remove

 Loops let us run code over and over again


 There are 2 type of loops- while loop and for loop
 Loops create scopes
 WHILE LOOP-if the condition is true the loop will run over and over again
 When you run a loop is called iteration

let i = 1; -called loop variable

while(i <= 5){ ()- anything between()called loop condition


console.log(1); {}-anything between {}called loop body
i ++ ; -increase the loop variable called increment step
}

 i = 1 , condition i <= 5 which means 1 <= 5(true) increment step (++) increases the value
i(e.g 1,2,3,4,5,6,7…). When it reaches 6 it will be false because the condition is (i <=5)
and the loop will stop
 Increment step makes sure the loop end at some point
 FOR LOOP-

for(let i = 1; i <= 5; i++){


console.log(1);
}
 Shorter and more organized than WHILE
 When you have standard loop(has condition,body and increment) you use a FOR loop
 When you have NON-standard loop uou use WHILE loop
o E.g generate random numbers until one that’s at least 0.5
let randomNumber = 0;

while(randomNumber < 0.5){


randomNumber = Math.random();
}
o Doesn’t have increment and loop variable that you increase everytime

LOOPING THROUGH AN ARRAY

 go through each value of an array one by one and do something with each value
const todoList = [
'make dinner', index = 0
'wash dishes', index = 1
'watch youtube' index = 2
]

for(let i = 0; i < todoList.length; i ++){


console.log(i) show 0,1,2
const value = todoList[i] show all the strings[‘’,’’,’’]
console.lo(value)
}
 todoList.length is = array.length -1 (last array -1)
 i < todoList.length(shortcut) = i <= todoList.length – 1
 Accumulator Pattern-e.g
 Calculate the total of the loop
o Create a variable to store the result
o Loop through the array and update the result
const nums = [1, 1, 3]
let total = 0;

for(let i = 0; i < nums.length; i++){


const num = nums[i];
total += num; console.log(total) = 5
}

 Double the loop in the array[1, 1, 3] to [2,2,6]


const numsDoubled = [];

for(let i = 0; i < nums.length; i++){


const num = nums[i];
numsDoubled.push(nums * 2);
}

ARRAY TO DO LIST

 Steps(todo list)-
1. create array to to store todos
2. when we click ’add’
3. get text from textbox
4. add it to array
5. console.log() the array

const todoList = []; 1.

function addTodo(){
const inputElement = document.querySelector('.js-name-input')

const name = inputElement.value;

todoList.push(name);
console.log(todoList);

inputElement.value = ''; //clears the textbox after


writing
}

 Steps(-
1. Loop through the array
2. Create some html code for each todo
3. Put the code on the web page
const todoList = ["dinner table", "wash dishes"];

renderTodoList();

function renderTodoList(){
let todoListHTML = '';

for(let i = 0; 1 < todoList.length; i++){ 1.


const todo = todoList[i];
const html = `<p>${todo}</p>`;2. // we use <p> because each
array must take the entire line(block element) //
todoListHTML += html; //+= add all the html together
}
console.log(todoListHTML); //<p>make dinner</p><p>wash
dishes</p>

document.querySelector('.js-todo-list').innerHTML = todoListHTML;
}
3. 3rd step-(put the code on the web page)

 Since we have the html(todoListHTML) we need to put it in the web page –


 Cant use <p></p> because it is already used (cant have <p> inside another
<p>) `<p>${todo}</p>`; we use <div></div>)
o <div></div> - represent a container. Purpose is to contain other element like
<p>, <button> even other <div>

todoListHTML += html
}
console.log(todoListHTML);

document.querySelector('.js-todo-list').innerHTML = todoListHTML

<div class="js-todo-list">text</div>

Difference between <div> and <p>

 Both are block element – they take the entire line


 Difference is a <p> have extra space between other elements and a <div> doesn’t have the
natural styling

ADDING THE DELETE AND DUE DATE BUTTON

 Date code is –
<input type="date">

 ARRAYS ARE ALSO REFERENCES TO AVOID ARRAY1 = ARRAY2 YOU USE.slice()


const array1 = [1, 2, 3]
const array2 = array1 // equal
array2.push(4);
console.log(array1) //=[1, 2, 3, 4]
console.log(array2) //=[1, 2, 3, 4]
 Array1 and array2 are references they point to where the array
is([1,2,3])
o When you .push(4) both array1&2 will be affected because
both point to where the array is[1, 2, 3, 4]
 To avoid array1&2 pointing at the same array we use .splice
const array2 = array1.slice() //=not equal array1[1,
2, 3] /
//=array2[1, 2, 3, 4]

Short-cut destructuring

 when you get a specific value out of the array you use destructuting
const [firstvValue, secondValue] = [1 , 2 , 3]
console.log(firstvValue) //=1 ‘firstvalue’ 1st array(0)
console.log(secondValue) //=2 2nd array(1)

MORE DETAIL AOUT LOOPS

 break and continue-


 break let use exit a loop early
for(let i = 0; i < 10; i++){
console.log(i); // count from 1 to 10
if(i === 8){
break; //when reaching 8 it will break and
stop
}
 continue let use skip 1 interation for one run of the loop
for(let i = 0; i < 10; i++){
if(i === 3){
continue; //it will skip 3 when counting from 1
to 10
}
o skip a number if it is divisible by 3
for(let i = 0; i < 10; i++){
if(i % 3 === 0){ //reminder === 0
continue; // 3, 6, 9 are skipped
} //because if i===0([3,6,9]-skipped)
//[1,2,4,5,7,8,10]-not skipped not(reminder
of 0)
7 % 3 =>1 – reminder 1
6 % 3 => 0 – reminder 0
I. on a while loop i++ must be written manually to
avoid a infinite loop

while(i <= 10){


if(i % 3 === 0){
i++;
continue
}

 loops with function


function doubleArray(nums){
const numsDoubled = [];
const num = [1, 1, 3]; // nums is written as parameter
for(let i = 0; i < nums.length; i++){
const num = nums[i];
numsDoubled.push(nums * 2);
}
}
doubleArray([1, 1, 3]) = [2, 2, 6]
doubleArray([2, 2, 6]) // = [4, 4, 12]
//use multiple arrays(reuse a loop)

Or

function doubleArray(nums){
const numsDoubled = [];

for(let i = 0; i < nums.length; i++){


const num = nums[i];
if(num === 0){
return numsDoubled //return works as break here(loop stops at
0)
//=[4, 4, 10]
}
numsDoubled.push(nums * 2);
}
return numsDoubled // =[2, 2, 6] and =[4, 4, 10]
}
console.log(doubleArray([1, 1, 3]))
console.log(doubleArray([2, 2, 5, 0, 1]))

ADVANCED FUNCTIONS

 Functions are values you can save a function inside a variable


const function1 = function greetings(){
console.log('hello')
}

console.log(function1)
 Anonymous function – function without a name(shortcut)
const function1 = function(){
console.log('hello')
}
console.log(function1)
function1()
o As long as the is a way to access a function the is no need to have the name of a
function
 Objects and fuction
const object1 = {
num : 2,
fun : function(){ //anonymous function
console.log('hello3')
}
}
object1.fun() //excess the function
 Passing a value in a function
function display(param){
console.log(param)
}
display(2);
 Passing a function to another function
function run(param){
param()
}
run(function(){ //called a callback
console.log('hello4')
})
 The advantage of using the old method of function is that it is already a shortcut and its easy to
read it. It also gives us a feature called hoisting
 Hoisting is calling a function before you created in the code, so the order does not
matter to were you call the function

 setTimeout()- let use run a function in the future


 takes 2 parameters 1. A function you want to run in the future
2. how long to wait before running the function(millisecond e.g
3000 millisec = 3 sec)

setTimeout(function(){
console.log('Timeout')
}, 3000);

 Asynchronous code means wont wait for a line to finish before going to the next line
e.g(console.log(‘hello4’))
o console.log('Timeout') will display after the line(3 second delay),
console.log('hello4')) this line is going to display 1st
 Synchronous code mean it will wait for the line to finish before going to the next line
o All the code we written in this course are synchronous code
 Code is only asynchronous when we use setTimeout
o Advantage of asynchronous code is that it doesn’t block other code for 3 second

 setInterval()- let us run the function every period of time


 takes 2 parameters 1. A function you want to run in the future
2. how long to wait before running the function(millisecond e.g
3000 millisec = 3 sec)’

setInterval(function(){
console.log('Interval')
}, 3000)
 every 3 seconds the code will run

Rock paper scissors(Autoplay)

 to autoplay the game

function autoPlay(){
setInterval(function(){
const playGame = computerRandom();
gameMove(playGame);
}, 1000)
}
 keep track whether we are playing or not
let isAutoPlaying = false;
let intervalId

function autoPlay(){

if(!isAutoPlaying){
intervalId = setInterval(function(){
const playGame = computerRandom();
gameMove(playGame)
}, 1000);

isAutoPlaying = true;

}else{
clearInterval(intervalId)
isAutoPlaying = false
}
}
 setInterval () returns a number and this number is like an iD and this iD can used to stop
the interval (clearInterval())

Another way to loop through an array

 previously when you loop trough an array we used a for loop and a while loop
 another way is using .ForEach()
 forEach is preferred than for loop
[
'make dinner',
'wash dishes',
'watch youtube'
].forEach(function(value, index){ //value-parameter
for[]
console.log(index) //index-position of each
array
console.log(value)
})
 forEach needs a parameter(value) to loop through all the array and foreach of the
values it will save the values in the parameters the runs it
 the 2nd value in forEach() is index

todo list forEach

function renderTodoList(){

let todoListHTML = '';

todoList.forEach(function(todoObject, index){

// const name = todoObject.name//


// const dueDate = todoObject.dueDate//
const{ name, dueDate } = todoObject;

const html = `
<p>${name} ${dueDate}
<button onclick="
todoList.splice(${index}, 1)
renderTodoList();
">Delete</button>
</p>
`;
todoListHTML += html;
})

document.querySelector('.js-todo-list').innerHTML = todoListHTML
}

 .forEach() –continue doesn’t work but a return statement does


[
'make dinner',
'wash dishes',
'watch youtube'
].forEach(function(value, index){
if(value === 'wash dishes'){
return; //return skips the index and goes to the
next one
} //return does the same thing as continue
console.log(index)
console.log(value)
})
 If u want to break then use a regular for loop

ARROW FUNCTIONS

 Work the same way as a regular function


const arrowfunction = () => { //function arrowfunction(){
console.log('hello') console.log(‘hello’)
} }// -similar
 the difference is that instead of writing function you write =>
 parameters and return statement work the same way as a regular function

const arrowfunction = (param1, param2) => { //arrow function

console.log('hello')
return 5;
}

const regularFunction = function(param1, param2){ //regular


function
console.log('hello')
return 5;
}

 difference is that arrow functions have some shortcut that doesn’t work on a regular function

SHORTCUTS

 if the is a single(1) parameter then- you don’t include the () -


const oneparam = param => { //param(parameter)//
console.log(param + 1) // =3
}
param(2)
 when an arrow function has one line
const oneLine = () => 2 + 3; 2 + 3 – return statement
{}-optional and also writing return
console.log((oneLine))
 when passing a function to another function we must use arrow function
 When saving a function to an object it is better to use the shorthand method

.addEventListener()

 Let us run some code when we interact with the element


 Does the same thing as onclick=””
 AddEventListener has 2 parameters-
 Event-what type of interaction to listen for
o Ways to find the event-after on. E.g(onclick = ‘click) event is click
 Function-a function you want to run
<Button onclick="" class="js-button">click</Button>
<script>
const buttonElement = document.querySelector('.js-
button')

const eventListner = () => {


console.log('click')
}
buttonElement.addEventListener('click', eventListner)

buttonElement.addEventListener('click', () => {
console.log('click2')
})

Advantages of .addEventListener()

 You can gave multiple event listeners for an event


 You can remove an event listener
 Using .removeEventListener
buttonElement.removeEventListener('click', eventListner)

Rock paper scissors(addEventListener)

 Changing the parameter on the buttons to addEventlistner


document.querySelector('.js-rock').addEventListener('click', () => {
playGame('rock') <button onclick =”plaGame(‘rock’)
} ) “>rock</button> -similar

 Playing the game with the keyboard using(rps)


document.body.addEventListener('keydown', (event) => {
if(event.key === 'r'){
gameResult('rock');
}else if(event.key === 'p'){
gameResult('paper');
}else if(event.key === 's'){
gameResult('scissor')
}
})

Todolist(addEventListener)

document.querySelectorAll('js-delete-todo-button')
.forEach((deleteButton, index) => {
deleteButton.addEventListener('click', () => {
todoList.splice(index, 1);
renderTodoList();
})
})
 .querySelectorAll() – gives all the categories that match js-‘’ ,event if it’s a string

2 more array method

 .filter()-works the same way as for each


 2 parameters(value, index)
 Creates a new array using a return statement
 Return is true – put a value in a new array
 Return is false – not put a value in a new array
console.log([1, -3, 5].filter((value, index) => {
/*
if(value >= 0){
return true
}else{
return false
}
*/
return value >= 0
})) new array[1, 5]

 .map()-works the same way as for each


 2 parameters(value, index)
 Creates a new array then whatever we return
 Added to the new array
[1, 1, 3].map((value, index) => {
return value * 2;
}) new array[2, 2, 6]

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy