JS Basic Code 基本
JS基本須知道
How to run JS
Browser- inspect
Method1:
Go to inspect > console
Method 2:
inspect> sources> snipperts> create js file
NodeJS environment
寫
XXX.js
//CREATE JS filenode XXX.js
//run .js file using node
adding comment
//
single line comment/**/
: multiply line comment
顯示 print
console.log()
顯示在consolealert()
跳出顯示document.write("\<h1>hello <br\/>")
JS 基本語法- Part 1
1. declare variable 宣告變數
let
(新)可以取代varex:
let myName= "chenchih"
console.log(myName)
var
const
must be inital and not able to change
不被修改變數。如果不想被人修改1
2
3const test= "heloo"
test="world"
console.log(test) //error
2. Data Type
string:
declare String and print string
1 | name="Jessie" |
combind two String
1 | strname="hello" |
template literals (concatenate strings)(ES6)
before ES6:
var message = ‘Hello ‘ + name;
After ES6 using the `
${}
`const message_new =
Hello ${name}
;
console.log(3! is ${3*2*1}
);
console.log(${1+2+4}
);
Ex:
1 | //example1: |
number
let age= 20
boolean:
let boolname=true
undefined type: 空直
value that is not assign
Ex:
1 | let test |
Null Type:空直
empty or unknown value,null 不等 undefined
Ex:
let age = null;
console.log(age)
typeof
check data Type
typeof
- example types:
typeof undefined // “undefined”
typeof 0 // “number”
typeof 10n // “bigint”
typeof true // “boolean”
typeof “foo” // “string”
typeof Symbol(“id”) // “symbol”
typeof Math // “object” (1)
typeof null // “object” (2)
typeof alert // “function” (3)
Ex:
1 | let hellostr="hello"; |
3. Interaction: alert, prompt, confirm
alert
: pop up and shows a message.prompt
: shows a message asking the user to input text.- It
returns the text
or, ifCancel button
orEsc
is clicked,null
.
- It
confirm
: shows a message and waits for the user to press “OK” or “Cancel”.- It
returns true
forOK
andfalse
forCancel/Esc
.
- It
Example:
1 | //prompt and alert |
4. Type Conversions
String Conversion
- string to number convert
1
2
3
4let value = "123";
console.log(typeof value); // string
value = Number(value); // now value is a number
console.log(typeof value); // number
Numeric Conversion
- number to string convert:
toString
1
2
3
4
5let num=500;
console.log(typeof(num))
convertstr= num.toString()
//or convertstr= String(num)
console.log(typeof(convertstr))5. operator
>
<
||
&&
!==
remainder %
1 | let x=10 |
Exponentiation **
The exponentiation operator a ** b raises a to the power of b.
console.log( 2 ** 2 ); // 2² = 4
console.log( 2 ** 3 ); // 2³ = 8
console.log( 2 ** 4 ); // 2⁴ = 16
String concatenation with binary +
using
+
to concatenate string1
2let s = "my" + "string";
console.log(s) // mystring+
to concatenate a string and number
Note: if any of the operands is a string, then the other one is converted to a string too1
2
3
4str1= '1' + 2
str2= 2 + '1'
console.log( typeof(str1) ); // string
console.log( typeof(str2)); // stringcomplex example
console.log(2 + 2 + ‘1’ ); // “41” and not “221”
the first two number add together and then add 1, so it will look like this: 4+’1’=>41
console.log(‘1’ + 2 + 2); // “122” and not “14”
Here, the first operand is a string, the compiler treats the other two operands as strings too.
- other arithmetic operators
binary + is the only operator that supports strings in such a way. Other arithmetic operators will convert string to Numberconsole.log( 6 - ‘2’ ); // 4, converts ‘2’ to a number
console.log( ‘6’ / ‘2’ ); // 3, converts both operands to numbers
Numeric conversion, unary + (convert str to number)
It actually does the same thing as Number(…), but is shorter. In above convert we use Number(…),we can also use +
to convert.
1 | // No effect on numbers |
Chaining assignments ‘=’
Chained assignments evaluate from right to left.
1 | let a, b, c; |
without cain your code have to write pretty long like this:
1 | c = 2 + 2; |
Increment/decrement
- counter++:
counter=counter+1
- counter–:
counter=counter=1
6. Comparisons
!
把結果反向
ex:
const isValid = true
console.log(!isValid)
//false
Strict equality ==
and ===
For a non-strict check
==
==
直比較x==y
//compare value, return bool會幫你轉換想等data type
ex:1 == "1"
//trueFor a strict check
===
===
嚴格判斷x===y
//compare value, and data type, return boolex:
1 === "1"
//false
alert( null == undefined ); // true
alert( null === undefined ); // false
null vs undefined vs 0
null vs 0
console.log( null > 0 ); // (1) false
console.log( null == 0 ); // (2) false
console.log( null >= 0 ); // (3) trueundefined vs 0
console.log( undefined > 0 ); // false (1)
console.log( undefined < 0 ); // false (2)
console.log( undefined == 0 ); // false (3)
7 condition if & ? statement
if else if else
1 | const num= -5 |
output
Number is negative
if (0) Boolean conversion
- false will never execute
1
2
3if (0) { // 0 is falsy
...
} - true will execute
1
2
3if (1) { // 1 is truthy
...
}
? operator
syntax: let result = condition ? value1 : value2;
Ex1: If else and ?
1 | let accessAllowed; |
Now we can use shorter way:
1 | let age = prompt('How old are you?', ''); |
ex2: boolean
- boolean
1
2const isEven = 10 % 2 ==0 ? true : false
console.log(isEven) //true - sting
1
2const isEven = 10 % 2 ==0 ? 'Number is Even ' : 'Number is odd'
console.log(isEven) // Number is Even
ex3 prompt example:
- using if else
1
2
3
4
5
6
7
8
9if (age < 3) {
message = 'Hi, baby!';
} else if (age < 18) {
message = 'Hello!';
} else if (age < 100) {
message = 'Greetings!';
} else {
message = 'What an unusual age!';
} - using ?
1
2
3
4
5
6let age = prompt('age?', 18);
let message = (age < 3) ? 'Hi, baby!' :
(age < 18) ? 'Hello!' :
(age < 100) ? 'Greetings!' :
'What an unusual age!';
console.log( message );
ex3 prompt example:
? method
1
2
3
4let company = prompt('Which company created JavaScript?', '');
(company == 'Netscape') ?
alert('Right!') : alert('Wrong.');if else
1
2
3
4
5
6
7let company = prompt('Which company created JavaScript?', '');
if (company == 'Netscape') {
alert('Right!');
} else {
alert('Wrong.');
}3. function
basic function
1
2
3
4function hello(){
console.log('你好')
}
hello()你好
function with value
1 | function addMoney(price1, price2, discount){ |
output:
NAN
1400
function return value
1 | function addMoney(price1, price2, discount){ |
output:
total 850
function return and if else
1 | function addMoney(price1, price2, discount){ |
output
msg platinum account
JS 基本語法- Part 2 loop迴圈 and condition條件
1. loop
for loop
Syntax:
1
2
3for (begin; condition; step) {
// ... loop body ...
}Example:
for loop
1
2
3for (let i=0; i<10; i++){
console.log("i:", i)
}output:
we can also use :
i++
ori+=2
step by step
1
2
3
4
5
6
7
8
9
10
11// for (let i = 0; i < 3; i++) alert(i)
// run begin
let i = 0
// if condition → run body and run step
if (i < 3) { alert(i); i++ }
// if condition → run body and run step
if (i < 3) { alert(i); i++ }
// if condition → run body and run step
if (i < 3) { alert(i); i++ }
// ...finish, because now i == 3
While
1 | let condition= true |
Ex1: while only true will execute
1 | let i = 1 |
output:
iteration number 1
iteration number 2
iteration number 3
iteration number 4
iteration number 5
Ex2 condition stop when traget match
1 | let condition= true |
output:
0
1
2
3
4
5
6
7
8
9
10
do while loop
1 | do { |
ex1:
1 | let i = 1 |
output:
iteration number 1
iteration number 2
iteration number 3
iteration number 4
iteration number 5
SWITCH
switch(key){
case value
}
1 | let key=900 |
JS 基本語法- Part 3 array object class
1. array
decalare array:
ex1:
decalare array with value
1
2
3
4
5let arrayName=['a','b','c']
console.log(arrayName) //[ 'a', 'b', 'c' ]
const oddNumber=[1,3,4,5,7]
console.log(oddNumber[0]) //1
console.log(oddNumber[4]) //7Trailing comma
1
2
3
4
5let fruits = [
"Apple",
"Orange",
"Plum",
];replace new element
fruits[2] = ‘Pear’; // now [“Apple”, “Orange”, “Pear”]
decalare empty array:
We can use either way to create empty arraylet arr = new Array();
let arr = [];
length長度:
console.log(arrayName.length)
Method push pull shift
push加值 appends an element to the end.
arrayName.push('value')
pop takes an element from the end.
arrayName.push('value')
shift: get an element from the beginning, advancing the queue, so that the 2nd element becomes the 1st.
array with for loop
Example1: loop in array
1 | const numArray=[1,2,3,4,5] |
output:
iteration number 1
iteration number 2
iteration number 3
iteration number 4
iteration number 5
Example2:
1 | let classA = ['80','90','50'] |
output:
i: 80
i: 90
i: 100
2. object
basic object
ex
1 | const person = { |
output
Lee
object with for loop
1 | const posts = [ |
output:
{ name: 'Anna', desc: 'Hello ANNA' }
example 1
1 | const post= { |
output
1 | [ |
example2:
continue above example, and add another post
1 | const post2= { |
output
createCard { name: 'Ma' }
createCard { name: 'Ma2' }
createCard { name: 'Ma3' }