JS review


Posted by s103071049 on 2021-05-12

use Google Chrome javascript console
note : the complete web developer in 2021 Zero to Master

Start from 8 Type

(1) Number

NAN not a number

(2) String

"This isn\'t very nice" black slash has a special meaning whatever comes after this just ignore it. This is a piece of string, I just want the back tick.

// Make the string: "HI There! It's sunny out" by using the + sign.
"Hi There! " + "It\'s \"sunny\" out"

adding a number and string, JS convert number to string, which means it becomes a string addiction. Since you can't really subtract the string, string and number substraction will return number. Sometimes it will have unexpected behavior, so ideally never do this.

3+'5'
"35"
44-"33"
11

(3) Boolean

Boolean means true or false. Usually, using with JS comparison.

5>10
false
3<4
true
5>=5
true
5<=5
truefc

3===3
true
3!==3
false

true + true // 2

How does the program remember thing ?

To catch and hold values, JS has sth called variables. variable can be used with word var . notice : using shift + enter, you can go to the new line.

變數命名規則 : variable can't start the number.
1) var 作用範圍大,不建議用
2) let
3) const for object, you can change the properties of the object still you can't reassign the variable

// prompt() it ask for sth and return whatever i typed
prompt('what\'s your username')
"annie"

// alert() I get a pop-up without anything to return, just an OK button

using the knowledge to make the caculator.

var first = prompt('輸入第一個數字')
var second = prompt("輸入第二個數字")
var sum = Number(first) + Number(second)
alert("總和是: "+sum)

(4) undefined

This means the variable has not been assigned

(5) null

Just says the object is null, which means there's nothing in the object.

(6) Symbol

you can make sure 不會有任何衝突。
用途 : ident fire, mostly for object properties

let sym1 = Symbol()
let sym2 = Symbol('foo')
let sym3 = Symbol('foo')
console.log(sym1, sym2, sym3) // Symbol() Symbol(foo) Symbol(foo)
console.log(sym2 === sym3) // false

(7) Object

Object are the collections of property. 參照 what is the data structure? second:Object


Js conditions

(1) if
(2) else
(3) else if
(4) ternary operator
condition ? expr1 : expr2 , which means if condition true provides expr1, otherwise provides expr2.
(5) switch

// it's going to check action
let cost 
switch (action) {
  case 'run':
        cost = 0
        break
  case 'swim':
        cost = 100
        break
  default :
       console.log('there is no action')
}

the good friends with conditions -- logical operators

(1) || (or)
(2) && (and)
(3) ! (not)


the Hardest part -- function

prompt() the bracket is doint the job calling the function. prompt('hello') in this case argumnet is 'hello', argumnets are what given to the function. Depends on the function, we can have multiple arguments.

notice : we write the function, means the function exist there. But, we need to call the function. the function will work.

first way : function declaration

function sayHello() {
    console.log('Hello')
}
sayHello()

second way : function expression

we just assign the function name to variable. Hence, it's called Anonymous function.

var sayBye = function () {
    console.log('Bye')
}
sayBye()

By adding argument, function can execeute more efficient. Arguments make our function more extensible. Thye can be customized.

function sing(song) {
    console.log(song)
}
sing('forever love')
sing('last christams i give u my heart')
sing('love newyork')

It's nice to have a "return" to make sure that the function acts the way we expected. Return is the final way to end the function.

參數與引數

  • parameters : 傳參數是看順序
  • arguments : function can have arguments and they get call with arguments.

Loop

(1) for
(2) while
(3) do while (這裡的 do 是要執行的事, while 是終止條件)
(4) forEach (new in ECMA 5)

let todos = [
    'study math',
    'do homework',
    'exercise',
    'eat healthy',
    'have fun with friends'
]
todos.forEach(function(todo,i) {
    console.log(todo,i)
})
 /*
 $ node try.js
study math 0
do homework 1
exercise 2
eat healthy 3
have fun with friends 4

 */

What's the data structure ?

how do you store all of them that we had learned before ? you don't want to throw everything in variable a huge mess. Data structures are like compartment holders in your desk. 不同的資料夾擅長的項目也不同。 Data structures give us the ability to store information and access it in a way that is useful to us.

First : Array

computer count from 0. Hence, the first index of the array is 0. Array can store strings, numbers, booleans, functions, array, Object,and so on, which means you can put everythins in array.

some methods that create new array like concate, while some methods like pop, push just modify the current one. array 相關 methods
(1) array.shift()
(2) array.pop() : pop off the end of the array (移除陣列中最後一個元素)
(3) array.push()
(4) array.concat()

Second : Object

Object is more dynamic. We can have properties and values. How can I grab properties ? For the array, We have pop, push, concat to change the array. How can we add properties to an object ?

let user = {
    name : 'Sheldon',
    age : 25,
    hobby: 'train',
    isMarried: false,
}
console.log(user.isMarried)
user.girlfriend = 'Amy'
console.log(user)
user.name = 'Sheldon Cooper'
console.log(user.name)

We can also have arrays, objects, functions in an object. A function inside an object is a method. When we don't declare a variable, we get undefined. But with an array or object, we can have sth empty without undefined.


link tags for stylesheet, script tags for JS. Ideally, wanna to put script type in the body. What that means is that the website gets displayed, gets rendered and then we have to still wait for the JavaScript to load - let's say we had a cool animation. I'll have to wait until that loads. But to a user it appears like the website loads a lot faster because they might not click on a dropdown menu, or see the animation right away and notice that there is a lag, but they will see a delay if they don't see anything on the page. So 'script' tags at the bottom.


keyword explanation

1) expression is sth that produces a value.

2) calling or invoking a function 呼叫函式一定要加 ( )

main (a, b)

alert()

3) function vs methods

function thisIsAFunction () {
}

let obj = {
  thisIsAMethod : function () {
   }
}

Also, access them in different ways.

thisIsAFunction ()

obj.thisIsAMethod ()

calling function to do sth is very common.


function 額外補充

function a () {
  console.log('call a')
  return 'A'
}
let result = a() // 先執行這個 function => call a
console.log('result', result) // 將回傳的值印出來 => result A
function a (number) {
  console.log('call a',number)
  return 'A'
}

a() // call a undefined => 預設值為 undefined
a(123) // call a 123
a(456,777) //call a 456 => function 接受參數是依照順序
a('big bang') // call a big bang => 你要傳甚麼進去都可以
// 沒有呼叫,不會有任何東西
function a (number) {
  console.log('call a',number)
  return 'A'
}

function main() {
    a()
}
function a (number) {
  console.log('call a',number)
  return 'A'
}

function main() {
    var result = a(123)
    console.log(result) // 可以簡化成 console.log(a(123))
}

main()
/*
執行步驟: 
1. main()
2. var result = a(123) => 執行function a() log 出來,
再將 return 值 儲存在 result 中
3. console.log(result) => 將回傳值印出來
*/
function a (number) {
  console.log('call a',number)
  return 'A'
}

function main(porameter) {
    console.log(porameter)  
}

main(345) // 345
main(a) // [Function: a]
function a (number) {
  console.log('call a',number)
  return 'A'
}

function main(porameter) {
    console.log(porameter===a)  // true
    parameter() // === a()
    porameter(123) //call a 123
}

main(a)

可以將 function 當作參數傳遞

function isPositive(n) {
    return n > 0
}

function isNegative(n) {
    return n < 0
}

function isValid(number, fn) {

    console.log(fn(number))
}
isValid(100, isPositive) // true
isValid(100, isNegative) // false

也可以在傳參數時,宣告 function 。 也就是,有先 function 未必要先寫好,可以在傳參數時再去宣告他。

function isValid(number, fn) {

    console.log(fn(number))
}
// 用比較迂迴的方式,將函式帶入 fn
isValid(100, function isNegative(n) {
    return n < 0
}) 
// 也可以將 function 的名字拿掉
isValid(100, function (n) {
    return n < 0
})

加 () 是在呼叫 function , 沒加是把 function 當參數傳進去。

isValid(100, isNegative())
=> isValid(100, false)
function handleResult(result) {
    console.log(result)
}

function getData() {
    handleResult ({
        data: 'hi'
    })
}
getData()
// 呼叫 getData()
// 執行 handleResult(),將裡面參數傳進去
// 物件變成 result, 然後會印出來
function handleResult(result) {
    console.log(result)
}


function getData(fn) {
    fn ({
        data: 'hi'
    })
}

getData()
// fn is not a function 
// 我呼叫 fn 這個 function 但我傳進去的是 undefined
// undefined 不是一個 function
function handleResult(result) {
    console.log(result)
}

function getData(fn) {
    console.log(fn === handleResult) // true
    fn ({
        data: 'hi'
    })
}

getData(handleResult)
// 執行 fn 就相當於 執行 handleResult

等價寫法,這個 function 叫做 callback function

getData(function (result) {
    console.log(result)
})

getData(result => {
    console.log(result)
})

結論 : 1) 參數是按照順序,和名稱無關係 2) 函數可以當作參數傳遞 3) callback function










Related Posts

第八天:API Server【二】

第八天:API Server【二】

[ 前端工具 ] - Bootstrap

[ 前端工具 ] - Bootstrap

[Day 7++] 番外篇 設計模式中英對照表

[Day 7++] 番外篇 設計模式中英對照表


Comments