JSbasic

JavaScript

Variables

please use let over var

var

  • function scope
  • use before declaration
  • mutable

let

  • block scope
  • use after declaration
  • mutable

const

a const means the reference is protected from reassignment. The value is not immutable though and can change, especially if it’s a complex construct like an object.

Data Type

There are 6 primitive data types: string, number, bigint, boolean, undefined, and symbol

JavaScript is weak type, variables get their type according to the value

typeof and instanceof will be super useful

1
2
3
4
5
6
7
8
9
10
function show(arg){
console.log(typeof(arg))
}

let a = 1
show(a)
a = "hello"
show(a)
a = true
show(a)
1
2
3
//template string
let a = 123
console.log(typeof(`hi, ${a}`)) //string

Functions

In JavaScript, functions are actually objects

FOP

Just like Python, you can pass functions as parameters

1
2
3
4
function f(){
console.log("Hi")
}
setTimeout( f , 3000 )

Anonymous functions

1
2
3
// f = lambda x : x ** 2
let f = (x) => x*x // arrow
let s = function(x) { return x + 1 } // no arrow

Control Flow

please always use === instead of ==

Similar to C

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let statcode = 400

// normal
if (statcode === 200){
// OK
}
else if ( statcode === 300 ){
//handle
}
else {
//default case
}

// one line
let result = statcode === 200 ? "OK" : "ERROR"
console.log(result)

Array

In JavaScript, arrays are also Objects(like Python).

One major benefit of arrays is that you can store different types of data in one array.

1
2
3
4
5
6
7
8
9
10
11
12
> let arr = []
undefined
> typeof(arr)
'object'
> arr.length
0
> arr.push(1)
1
> arr.length
1
> arr
[ 1 ]

Loop

while and for are again same with C. And we also have Python’s flavor added in

1
2
3
4
let array = [1,2,3,4,5]
for(let number of array){
//do sth to number
}