0% found this document useful (0 votes)
21 views

JS Basic Note

Uploaded by

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

JS Basic Note

Uploaded by

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

- make variables:

let nameVariable = value;


const nameVariable = value; (constant variable, cannot change
later)
var nameVariable = value; (less use than let, the same
function like let)

score -= 5 equal to score = score + 5;

- clear () = command + K
- i++ : it returns the current value on the first print, then if print
again i, it will come the value of i++
- ++i: it right away makes the +1 to i

- BOOLEANS : True or False

- STRING: ‘ ‘ or “ “
- Length: variable.length animal.length
- 1 + “string” = 1string (become a string)
- METHOD:
+ .trim() : remove all the spaces inside the string
+ Make more than 1 method at the same time:
greeting.trim().toUpperCase()
+ Find the position of a character in a string:
“helloooo!”.indexOf(‘lo’);
+ Cut a part of the string and copy it out: “Haha it’s so
funny!”.slice(5, 9) —> it’s
+ "haha that's so funny!".slice(-6) —> ‘funny!’
+ replace(original, what you want it to become)

- TEMPLATE LITERALS:
`You bought ${qty} ${product}s. Total is ${qty * price}$` —> 'You
bought 5 Artichokes. Total is 11.25$'
````````

- NULL : intentionally lack of value. We assign


- Undefined : lack of value or cannot be defined

- Math Object :
+ Math.round(3.9)
+ Math.random() : between 0 and 1
+ Math.floor() or Math.ceil()
+ Math.pow (2,3) —> 8

- COMPARISONS:
+ == : does not care about the type
+ === : care about type —> Recommended to use now

- console.log(“HELLO”) : Print Hello


- Prompt() : take the input from the page
- Alert(): pop up a message on the page
- parseInt() : make a string become an integer / find and extract
the integer in the string

- Make a file with .JS


- Open the file on website —> Inspect —> Console
- Add this to the end of “Body” in html
<script src="app.js"></script>

- IF STATEMENT
+ if (1+1 === 2){ console.log(“Math works!”)
console.log(“It works!”)}
else if (…){
}

- !== -1 : co
- === -1: ko co
- False values : false, 0 , “” (empty string), null, undefined, NaN

- LOGICAL Operations : and && , or || , not


+ when using && or || , else if have to be changed also, otherwise it will come to the next
else if
+ have to be separate: age > 0 && age < 5
0

- ARRAYS (order thing in the group : useful when making a queue…)


+ let days = [‘mon’,’tues’,’wed’]
+ days[1] = ‘tues’

- ARRAY METHODS:
+ Push(): add to the end days.push(‘thurs’) —> add ‘thurs’ to the array
+ Pop: remove from the end days.pop() —> remove ‘thurs’ from array
+ Shift: remove from the start
+ Unshift: add to the start
+ Concat() : merge 2 arrays concat array3 =
array1.concat(array2);
+ .includes(‘cat’) : ask if an element is included in the array or
not —> True/False answer
+ .indexOf(‘cat’): find the place of element . If -1 —> does not
exist
+ .reverse() : reverse the whole array
+ .slice : get a copy of a part of the array . cats.slice(1,3)
cats.slice(-2)
+ .splice(index, (0 is insert, > 1 is replace > 1 element), ‘new
element’)
+ remove multiple things also Array.splice(2,3)
+ insert: dcats.splice(1,0,’red’)
+ add more things : dcats.splice(2,0,’black’,’white’)
+ const array : cannot reassign but can change, replace the interior/
content

- OBJECT LITERALS: (order of things are not important but we have


a lot of sorts of things )
{ firstname: Chi , lastname: Nguyen}
+ key : value (pair)
+ take element out of the Literals : person[‘firstName’] or
person.firstName
+ All keys are turned into strings
+ Change the value: person.firstName = ‘ ‘ or
person[‘firstName’] = ‘ ‘
+ Add values : person.age = 19 or person[‘age’] = 19

- ARRAYS + OBJECTS

LOOPS: For loop, while loop, for…of loop, for…in loop


- For loop: for (let i = 1; i < = 10; i++) {
console.log(i); }

- While loop (prefer to use for unknown times / when play game, as
long as no one has won the game, then the loop keeps continuing)
let num = 0;
while (num < 10) {
console.log(num)
num++ }

- break;

- for…of Loop:
for (variable of iterable) {
statement}

- for…in Loop:
give the key in the object like const testScores = {
chi: 89;
dan: 9;
nhi: 200}

- Object.values(testScores) —> [89, 9 ,200]


Object.keys(testScores) —> [‘chi’, ‘dan’, ‘nhi’]
Object.entries(testScores) —> [‘chi’: 89, ‘dan’ : 9, ‘nhi’: 200]

**** FUNCTION *****


function funcName() { //do sth }
- Argument: function funcName(variable1, variable2) {
console.log(`Hi, ${variable1}!`); }

- Return : Eg: function add (x , y ) {


return x+y; }
+ Everything after return will not be executed
+ Return only 1 thing

- FUNCTION SCOPE
- BLOCK SCOPE: variables exist inside the block { } like if {
} . But var can be executed, var will not be in block
- LEXICAL SCOPE: one function in another. The father function has
to call the child function to access to it.
- Accept other functions as arguments :
function callTwice(func) {
func() ;
func() }
function rollDie() { const roll = Math.floor(Math.random() * 6) + 1
console.log(roll) }
callTwice(rollDie) —> Give 2 different numbers
callTwice(rollDie()) —> Give 1 number 2 times

- Return a function :
- Methods : add function as properties on objects

const myMath = {
PI: 3.14,
square: function(num){
return num * num;
},
cube: function(num){
return num** 3;
}
}

Or square(num) cube(num)
- THIS : refer to the left object before dot

******ARRAY METHODS********
- ForEach() : call a function for each element in the array a time
movies.forEach(function(movie){
console.log(`${movie.title}: ${movie.score}/100`)
}
)

- MAP : like ForEach but store new elements in a new array.


const fullNames = [{first: 'Albus', last: 'Dumbledore'}, {first: 'Harry', last:
'Potter'}, {first: 'Hermione', last: 'Granger'}, {first: 'Ron', last: 'Weasley'}, {first: 'Rubeus',
last: 'Hagrid'}, {first: 'Minerva', last: 'McGonagall'}, {first: 'Severus', last: 'Snape'}];

const fistNames = fullNames.map(function(firstName){


return firstName.first
}
)

- Arrow Function: is ike any other function. Make the function


expression shorter
const add = (x,y) => { return x + y }

- Implicit return when there is 1 single line


const add = (x,y) => ( x + y ) or const add = (x,y) => x+ y

- Pause, set timer, set timeout : delay the execution function


setTimeout ()
- Interval : setInterval () —> Stop : clearInterval ( ID)

- Filter : filter out to make a subset in a new array


const goodMovies = movies.filter(m => m.score > 80
)

- Some and Every : Boolean


const exams = [80,90,98,92,77,78,89,84,81,77]

exams.every(score => score >=80)

- Reduce : const prices = [9.99,1.5,19.99,49.99,30.50];

const minN= prices.reduce((min, price) => {


if(price < min){
return price
} else { return min}
}
)

- Default params :
function rollDie (numSides = 6)
return Math.floor(Math.random()* numSides) +1 ;
}
—> There will be no undefined. If there is no number for numSides,
it takes numSides = 6 automatically

The params variable can stay at last :


function greet(person, msg = 'Hello there' ){
console.log(`${msg}, ${person}`)
}

- Spread (separate) :

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