---
title: JavaScript Syntax
tags: Web Directory, JavaScript
description: JavaScript Notes
---
{%hackmd U6g0skbVTIyVdJhvWCgo2Q %}
<aside style="position: fixed; bottom: 20px; right: 20px; border: 5px solid white; background-color: aqua;">
<a href="https://jsfiddle.net/" target="_blank">editor</a>
</aside>
# <span class="big-title">JavaScript Structure</span>
- colon isnt necessary (optional)
- `whitespace` (including whitespace, tab, break) will be ignore
- it's free to use them to format the code.
## <span class="intext-title">Single Thread and Event Queue</span>
- JS is **Single Thread**
- But JS support **Synchronous** and **Asynchronous**
- when meeting asynchronous, they will be put into event queue
- after main thread complete, event queue will be call back
- cause **precision problem**
## <span class="intext-title">Tag</span>
```htmlmixed=
<!--Can be placed in head, body, any where-->
<script type="text/javascript">
// JavaScript...
</script>
<!--Outer js resource-->
<script src="<outer_js_file.js>"/>
```
> `type` can be ometted now.
## <span class="intext-title">Embed JavaScript</span>
1. event of an element
- trigger when event happen
2. directly write in document
3. from outer file
## <span class="intext-title">Show Data</span>
```htmlembedded=
<script>
function outputString(str){
var target = document.getElementById("show output");
target.innerHTML=`${str}`;
}
</script>
<input type="button" value="write to innerHTML" onclick="outputString('JavaScript!')"/>
<font id="show output">No Output</font>
```
1. `windows.alert()`
- can be shortten to alert()
3. `document`
- `document.write()`
- `document.getElementById().innerHTML`
5. `console.log()`
- write to
## <span class="intext-title">Combinational Example</span>
```htmlmixed=
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Embed JS</title>
<!--function-->
<script>
Student = function(name, age, id){
this.name = name;
this.age = age;
this.id = id;
this.introduce = function(){
alert(`Hello, I am ${this.name}.\nI am ${this.age} old.\nMy Id is ${this.id}.`);
}
}
s = new Student("John", 15, 102334)
Student.prototype.getName = function(){
return this.name;
}
alert(null==NaN);//false
alert(null==undefined);//true
alert(undefined==NaN);//false
</script>
</head>
<body>
<!--embed as event handler-->
<input type="button" value="Hello" onclick="window.alert('Hello JavaScript!')"/>
<input type="button" value="Instance" onclick="s.introduce();
alert(`${s.getName()}`);"/>
<!--alert will stop loading website-->
<script type="text/javascript">
var i = 5
if (i > 10)
{
window.alert("hello world!");
}
</script>
<!--Outer JS-->
<script type="text/javascript" src="scripts/test.js"></script>
</body>
</html>
```
# <span class="big-title">Variable</span>
| class | member |
| -------- | -------- |
|primitive data types| `undefined`,`number`,`string`,`boolean`,`null` |
|composite data types| `Object`, `Array`|
- variable type is dynameic judging
- if dont give initial value, the type is `undefined`
- with different value, same variable can have different type
```javascript=
var num = 123;
console.log(typeof(num)); //number
num = "Hello";
console.log(typeof(num)); //string
```
> keyword `typeof` can be used to recognize type of variable.
- Identifier
- name we defined to access variables
- `reserved word` cant be used as identifier
### <span class="intext-point">number</span>
- NaN, infinity integer, float...
- function
- `parseInt()`, `parseFloat()`
- parse number from string
- `Math.ceil()`, `Math.floor()`
### <span class="intext-point">Boolean</span>
- `Boolean()`
- change things to boolean value
- false
- NaN
- 0
- null
- Undefined
### <span class="intext-point">String</span>
```javascript=
var str = "Hello"; // String
var str = String("Hello"); // Object
alert(str.length) // get length
```
- functions
- `indexOf`, `lastIndexOf`
- `replace`
- `substr`, `substring` -> they are diff
- `toLowerCase`, `toUpperCase`
- Format String
- by using concatenate
```javascript=
var age = 10;
var name = "John";
alert("Hello, I am " + name + "\n" +
"I am " + age + "old.");
```
### <span class="intext-point">Object</span>
- Base class for all class
- Property
- `prototype`: dynamic extend properties and function
- Methods
- `toString()`
- `valueOf()`
- `toLocalString()`
### <span class="intext-point">null, NaN, undefined</span>
- different type
- null can be equal to undefined
```javascript=
alert(null==NaN);//false
alert(null==undefined);//true
alert(undefined==NaN);//false
```
## <span class="intext-title">Global vs Local</span>
- declared in `var`
- can be accessed anywhere
- Other rigion variable (package region)
1. `let`
2. `const`
- (ES6 extension)
- Define in scope -> local variable
- can only be accessed in same block
- eliminated when block ended
# <span class="big-title">Operator</span>
- [MDN](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Guide/Expressions_and_Operators)
- Type of Operator
1. Assignment
2. Compare
3. Arithmetic
4. Bitwise
5. Logical
7. Conditional (ternary)
### <span class="intext-point">Compare Operator</span>
- Special
- `===`
- absolutely equal (value and class)
- `!==`
- not absolutely equal
### <span class="intext-point">Bitwise Operator</span>
- `|` `&` `^` `~`
- or, and, XOR, NOT
- bitwise computation
### <span class="intext-point">Logic Operator</span>
- `&&` `||` `!`
- in `Logical Ooperator`, all things besides `undefined` `false` are logical **true**
### <span class="intext-point">Unary Operator</span>
- `delete`
- can delete property, array element
- if delete element of an array, it will leave `undefined`
```javascript=
var fruits = ['Apple', 'Banana', 'Orange'];
delete fruits[0];
// fruits = [undefined, "Banana", "Orange"]
```
- `typeof`
- `void`
### <span class="intext-point">Relation Operator</span>
- `in`
- can judge index, property of an Object
- if judging Array, use index but things actually in that index
- `instanceof`
- can judge if an instance is some class
## <span class="intext-title">ES6: Spread Operator/ Rest Operator -> `...`</span>
- this operator is used for spread array
- can be used to spread arr into function arguments -> spread
- can be used to let function accept unsteady function argument
- Combinational Example
```javascript=
function foo(a, b, ...args){
// pass in args is an array
// keep using rest operator to map other array
return [a, b, ...args];
}
var a = 10, b = 15, c = 23, arr = [5, 6, 7, 8]
let val = foo(a, b, c, ...arr);
console.log(val);
// [10, 15, 23, 5, 6, 7, 8];
```
# <span class="big-title">Flow Control</span>
- There are ways to control flow in javascript
- `if/else`
- `switch/case`
- `for`
- `while`
- `label`
- `try catch finally`
### <span class="intext-point">label</span>
```javascript=
// <loop_name>:
countingNums:
for (let i=0; i<10; i++){
sum += s[i];
for (let j=0; j<10; j++){
if (!jedgeValid(b[j])){
// jump outer loop
break countingNums;
}
else if (s[i] == 5){
// jump now loop
break;
}
}
}
```
> Way to jump out embeded loops
> > also can use on `continue`
## <span class="intext-title">for loop</span>
```javascript=
var arr = [1, 2, 3, 4, 5];
for (var i=0; i<arr.length; i++){
console.log(arr[i]);
}
```
## <span class="intext-title">Error handling</span>
- related keywords
- `try`, `catch`, `finally`
- `throw`
- all exceptions in JS are inheritanted from Object `Error`.
- `var err = new Error("QQ You are wrong")`
- Defined a new kind of error is acceptable
- a caught error will have two attribute -- `name` and `message`
- `name` represents error type
- `message` represents error message inside
### <span class="intext-point">Throw</span>
```javascript=
var ele = document.getElementById("show-information");
ele.innerHTML = 123;
try{
if (ele.innerHTML == 123){
throw RangeError("Hey, you got range error!");
}
}
catch (err) {
console.log(err.name + ": " + err.message);
}
```
> it should give message to error object, or the message field will be `undefined`
- Error can be thrown
- allow type: `number` `string` `error object`
- Judge thrown error -> usage of `instanceof`
```javascript=
try {
//...
if (expression){
throw RangeError;
}
else {
throw "This is an error";
}
}
catch (err){
if (err instanceof RangeError){
console.log(err.name)
}
else {
console.log(err);
// now error is a string
}
}
```
### <span class="intext-point">Types of Error</span>
- EvalError
- RangeError
- ReferenceError
- SyntaxError
- TypeError
- URLError
# <span class="big-title">Function</span>
- in JS, functions **are** `first-class object`
- means that object can be a params, return_value, object_value, etc.
- so we have two way to declare a function -> `function expression`/`anonymous function (function literal)`
- it have `prototype`... works like normal object
- function expression
```javascript=
function addition(x, y){
return x + y;
}
```
- Anonymous Function (passing as a variable value)
```javascript=
var addition = funciton (x, y){
return x + y;
}
```
## <span class="intext-point">rest parameter </span>
- ES6 extension
- rest opertator
```javascript=
function f(a, b, ...Args){
return Args[0] + Args[1];
}
```
- `...` can represent the following parameters been a rest argument
- Args is an array, it can use array method or use destruct in it
## <span class="intext-title">OOP</span>
- talk about JS OOP (In google Drive)

> https://drive.google.com/u/1/uc?id=16n9btMFxA183vv_ryPYKo6bRq4BSMT1t&export=download
- function can use to define `Object` in JavaScript
- It's a implementation of OOP
- `prototype-base`
- within the chain of prototype, it's possible to implement `polymorphism`, `inheritance`
- Knowladge should know
- prototype chain
- constructor function
### <span class="intext-point">Example Code</span>
```javascript=
var Animal = function(name){
this.name = name;
}
// Define Prototype Properties and Method
Animal.prototype.gender = "Girl";
Animal.prototype.hello = function(){
console.log(`Hello, I am ${this.name}.
I am a ${this.gender}`);
}
// instantiate
var dogA = new Animal("Mike");
var dogB = new Animal("Snake");
dogA.hello();
dogB.hello();
```
- Both dogA, dogB have no attibute `gender` and method `hello()`
- when accessing properties, methods of a instance, it will search the `prototype chain` of them.
- finally, it will find those two methods/properties in it Prototype (not meaning the property)
- then, how and what does the JS do to search for it?
- it will search the `__proto__` properties in `dogA` and `dogB`
- it will be relevent with their prototype --- `Animal`
### <span class="intext-point">Other Methods</span>
- use for instance check -> `instanceof`
- common use on compare with the `__proto__` property
- This method will check the prototype chain untill it find null (like the way prototype search in normal)
# <span class="big-title">Objects</span>
- Objects include multiple key-value pair
- `key`: properties, methods name
- `value`: value, function...
- It **should** be noticed that primitive types and native object are different thing
- then, why things like `a.toLocalString()` work when a is a primitive types?
```
since it will be converted to object and trigger methods
then wiped up back to primitive types.
```
- **Declaration**
- `new` operator
```javascript=
var newObj = new Object();
```
- **`Object Literal`**
```javascript=
var newObj = {
'color': 'yellow',
'gender': 'boy'
}
```
- **Access**
```javascript=
// use '.'
console.log(newObj.color);
// use '[]'
console.log(newObj['color']);
```
- **Addition**
```javascript
newObj.myprop = "hello";
newObj['myprop'] = "hello";
// available to use variables when using '[]' operator
var propName = 'myprop';
newObj[propName] = "hello";
// avalible to make new properties when using object literal
var newObject = {
color: 'yellow',
height: 175,
gender: 'boy'
}
// Quotation Marks can be ignored
```
- `this` keyword
- `this` keyword can be used to represent object itself
- **Native Objects**
1. Number
2. Boolean
3. String
4. Array
5. Math
6. Date
7. RegeExp
## <span class="intext-title">Number</span>
- representing number
- `var x = 017` -> octal
- `var x = 0xaf` -> hexadecimal
- methods
- `parseInt`, `parseFloat`
- `toFixed()` (fixed precision)
- `toPrecision()` (fixed length)
- `valueOf()` (number object -> primitive type)
## <span class="intext-title">Boolean</span>
- followings will be treated as `false`
1. `null`, `undefined`, `NaN`
2. 0, `` (empty string)
## <span class="intext-title">String </span>
- \`\` is equal to \"\"
- Multiple Line
```javascript=
// there shouldn't have any space after backslash
var str = "Hello, This is a very long string, \
and I need to change a line, \
or I should say \
I want to break line which is <br /> in HTML?"
// or use concatenate on string
var str = "Hello, This is a very long string, " +
"and I need to change a line, " +
"or I should say " +
"I want to break line which is <br /> in HTML?"
```
- <span class="important">Methods</span>
- `indexOf`
- `str.indexOf(searchValue[, fromIndex])`
- can use to find specified substring
- `match` -> work with `Regex()`
- return array (first is matched content, others are group, nor is `null`)
- `search`
- similar with `indexOf`, but it can use regex as params
- `split`
- return Array, can use Regex
- matched group will be put into return array
```javascript=
var str = 'a,b,c,d,e';
var strAry = str.split(',');
console.log(strAry);
// ['a', 'b', 'c', 'd', 'e']
str = 'a1b 1 c 1d 1';
strAry = str.split(/\s*(\d)\s*/);
console.log(strAry);
// ['a', '1', 'b', '1', 'c', '1', 'd', '1', 'e']
```
- `substring`, `substr`
```javascript=
var sentence = "Hello";
console.log(sentence.substring(0, 2)); //Hel
console.log(sentence.substr(0, 2)); //He
```
> `substring` -> start and end index
> `substr` -> start and length
## <span class="intext-title">Regular Expression -- [`RegExp()`](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Guide/Regular_Expressions)</span>
```javascript=
// Declaration
var reg = new RegExp(/Mark/, 'g');
var reg2 = /HAHA/i;
// test
var j = reg.test("Mark");
var i = reg2.test("Mark");
if (j){
alert(`Yes, i is ${i}`);
alert(`${String("MarkMarkMark").match(reg)}`);
}
else{
alert("NONO");
}
```
- Mind the flags (decoration syntax)
- `i`: Upcase, Downcase doesnt matter
- `g`: full test (not retuen for one match)
- `m`: multiline match
- Match & test
- use `match` on str
- multi match all if set `g`
- use `test` for RegExp obj
- [MDN -- using RegExp](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Guide/Regular_Expressions#%E9%81%8B%E7%94%A8%E6%AD%A3%E8%A6%8F%E8%A1%A8%E9%81%94%E5%BC%8F)
## <span class="intext-title">Array</span>
- Declaration
```javascript=
// (1)
var names = new Array();
names[0] = 54;
names[1] = 95;
//(2)
var students = ["John", "Mia", "Tyler"];
//(3)
var classes = new Array("class A", "class B", "class C");
```
- Property
- `length`
### <span class="intext-point">Add and delete</span>
- add element
- `push`
- push to the back of array
- `unshift`
- push to the front of array
- delete element
- `pop`
- pop last ele
- `shift`
- delete first ele
- `delete`
- check <a href="#Unary-Operator">operator</a>
- it will leave `undefined`
```javascript=
var arr = [1, 2, 3]
arr.push(4); // arr = [1, 2, 3, 4];
arr.unshift(0); // arr = [0, 1, 2, 3, 4];
arr.shift(); // arr = [1, 2, 3, 4];
delete arr[3]; // arr = [1, 2, 3, undefined];
arr.pop(); // arr = [1, 2, 3];
```
### <span class="intext-point">Method: map</span>
```javascript=
Array.map ( callback (currentVal[, currentIndex[, allArray]))
```
> **call back function** can accept following params:
>> `currentVal` : representing now iterating ele
> `currentIndex` : Now iterating index
> `allArray` : representing passing array (caller array itself)
- this function will iterate in current array, and map a new one.
- example
```javascript=
var numbers = [1, 2, 3, 4, 5]
var new_arr = numbers.map( (x, index, arr) => {
console.log(`current iterating: ${arr[index]}\n` +
`current x: ${x}`);
return x * 2;
});
// new_arr = [2, 4, 6, 8, 10];
```
## <span class="intext-title">Date</span>
- getting date via this object
- `getDate`, `getDay`, `getFullYear`
- `getHours`, `getMinutes`, `getSeconds`
- ...
- [MDN -- Date](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Date)
## <span class="intext-title">Math</span>
- Some Math Lib
- Math.PI
- Math.max
- Math.min
- [MDN -- Math](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Math)
## <span class="intext-title">Template String (formating string)</span>
```javascript=
var name = "John";
var age = 10;
alert(`Hello, I am ${name}.`);
// to place \n between strings
alert(`Hello, I am ${name}.
I am {age} year old.`);
```
## <span class="intext-title">Class</span>
- In JS, **function definition is also class definition.**
- and it will include constructor
- Usage
```javascript=
// Class Student
function Student(name, age, id){
this.name = name;
this.age = age;
this.id = id;
this.introduce = function(){
alert("Hello, I am ${this.name}.");
}
}
s = new Student("Mike", 102, 3483843);
s.introduce();
/*also can write:
* Student = function(name, age, id){
* //...
* }
*/
```
- access class property
```javascript=
var name = s.name;
var name_2 = s["name"];
```
- like key -- value pair'
### <span class="intext-point" style="text-decoration: line-through;">Extend Properties, Methods with `prototype`</span> -> You should never use it, it will destroy the encapsulation
```javascript=
Student.prototype.getName = function(){
return this.name;
}
```
- Not allowed another form