SlideShare a Scribd company logo
1 of 74
Download to read offline
Babel Coder
JAVASCRIPT
FUNDAMENTALS
Babel Coder
WHY JAVASCRIPT
Babel Coder
CSS
HTML
JavaScript
THE WEB TECHNOLOGIES
Structure — HTML
Presentation — CSS
Behavior — JavaScript
Babel Coder
JAVASCRIPT IN THE BROWSER
Render
HTTP Request
Babel Coder
JAVASCRIPT IN THE SERVER
Render
HTTP Request
Babel Coder
HOW COMPUTERS WORK
0 or 1
0 or 1
0 or 1
0 or 1
011001100111
Babel Coder
HOW PROGRAMS WORK
Load
Execute
Display
Babel Coder
TRANSLATION
Interpreter
Compiler
011100011000100011
Babel Coder
VARIABLES
Name
Age
Gender
Height
Weight
Babel Coder
VARIABLES
• A variable is a named value in your program.
• Whenever you use the name in the program, it’s replaced with the value.
var age
The var keyword tells the computer to
take the next word in the statement and
turn it into a variable.
Variable
name
age = 12
The assignment operator
var age = 12
Declare a
variable
Assign a
value
Babel Coder
VARIABLE NAMES
var thisIsMyBook;
var $whatMyName;
var _withUnderscore;
var StartWithCapital;
var 123;
var 456abc;
var &special;
var separate by space;
var if
Valid variables
Invalid variables
DYNAMIC TYPING
Variables in JavaScript are not
directly associated with any
particular value type, and any
variable can be assigned (and re-
assigned) values of all types.
var foo = 42 // foo is now a Number
var foo = 'bar' // foo is now String
var foo = true // foo is Now Boolean
Babel Coder
DATA TYPES
Primitive
• Boolean
• Null
• Unde
fi
ned
• Number
• String
• Symbol
Object
• Array
• TypedArray
• Dates
• Map
• Set
• WeakMap
• WeakSet
typeof(<VARIABLE>)
Check data type of this variable
Babel Coder
BOOLEAN
P / Q T F
T T F
F F F
P / Q T F
T T T
F T F
AND OR
Babel Coder
NUMBER
Number
10 / 3
3 rem 1
10 % 3
Math.random() 0 <= number < 1
Math.PI // 3.14
Math.round(4.7) // 5
Math.round(4.4) // 4
Math.pow(8, 2) // 64
Math.sqrt(64) // 8
Math.abs(-4.7) // 4.7
Math.ceil(4.4) // 5
Math.
fl
oor(4.7) // 4
Babel Coder
OPERATORS
8 == “8”
8 === “8”
Strict Equality Operator
var num = 10
num = num + 10
num += 10
Shorthand
2 + 3 // Addition
3 * 4 // Multiply
5 / 2 // Divide
7 % 2 // Remainder
Babel Coder
STRING
Template String
Code Output
n New line
t Tab
 Backslash
’ Single quote
” Double quote
var myStr1 = 'Hello World'
var myStr2 = "Hello World"
var myStr3 = "HellonWorld"
var myStr4 = `
Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.
`
var myStr5 = `${myStr1} Krub`
Babel Coder
STRING
var name = ‘BABELcoDER’
name B A B E L c o D E R
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
name.length
name[3]
name.endsWith(‘ER’)
name.startsWith(‘BABEL’)
name.includes(‘oDE’)
name.indexOf(‘L’)
Babel Coder
STRING
B A B E L c o D E R
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
B A B E L C O D E R
b a b e l c o d e r
name.toUpperCase()
name.toLowerCase()
Babel Coder
STRING
B A B E L C O D E R
B A B
B A B E L B A B E R
name.replace(‘COD’, ‘BAB’)
Babel Coder
STRING
B A B E L C O D E R
name.substr(2, 3)
name.slice(2, 5)
Babel Coder
SYMBOL
Every symbol value returned from Symbol() is unique. A
symbol value may be used as an identi
fi
er for object
properties; this is the data type's only purpose.
const str1 = 'Hello'
const str2 = 'Hello'
const sym1 = Symbol('hello')
const sym2 = Symbol('hello')
console.log(str1 === str2) // true
console.log(sym1 === sym2) // false
Babel Coder
PRINTING
var msg = 'Hello'
console.log(msg) // Hello
console.log('Hello') // Hello
console.log(msg, 'World') // Hello World
Babel Coder
IF-ELSE STATEMENT
num > 0.5
Yes No
Y N
var num = Math.random()
if (num > 0.5) {
console.log('Yes')
} else {
console.log('No')
}
Babel Coder
COMPARISON OPERATORS
Operator Name Example Evaluates to
> Greather than 15 > 3 true
>= Greather than or equal to 12 >= 12 true
< Less than 7 < 3 true
<= Less than or equal to 3 <= 5 false
== equal to 3 == 5 false
!= not equal to 3 != 5 true
=== strictly equal to 3 === “3” true
!== not strictly equal to 3 !== “3” true
Babel Coder
IF-ELSE-IF STATEMENT
score >= 80
Grade A
Y N
score >= 70
Grade B
Y N
score >= 60
Grade C
Y N
score >= 50
Grade D
Y N
Grade F
var score = 50
var grade
if (score >= 80) {
grade = 'A'
} else if (score >= 70) {
grade = 'B'
} else if (score >= 60) {
grade = 'C'
} else if (score >= 50) {
grade = 'D'
} else {
grade = 'F'
}
Babel Coder
SWITCH STATEMENT
Default Case
switch(new Date().getDay()) {
case 0:
day = 'Sunday'
break
case 1:
day = 'Monday'
break
case 2:
day = 'Tuesday'
break
case 3:
day = 'Wednesday'
break
case 4:
day = 'Thursday'
break
case 5:
day = 'Friday'
break
case 6:
day = 'Saturday'
break
}
var text
switch (new Date().getDay()) {
case 4:
case 5:
text = 'Soon it is Weekend'
break
case 0:
case 6:
text = 'It is Weekend'
break
default:
text = 'Looking forward to the Weekend'
}
Babel Coder
FOR LOOP
var sum = 0
for (var i = 1; i <= 3; i++) {
sum += i
}
Initial
Condition
Post Condition
Loop i sum
1 1 0
2 2 1
3 3 3
6
i <= 3
sum += i
Y N
var sum = 0
sum += 1
sum += 2
sum += 3
Babel Coder
WHILE LOOP
var sum = 0
var i = 1
while (i <= 3) {
sum += i
i++
}
Initial
Condition
Post Condition
var sum = 0
sum += 1
sum += 2
sum += 3
Babel Coder
TERNARY OPERATOR
var i = 22
console.log(i % 2 === 0 ? 'Even' : 'Odd')
true false
Babel Coder
EXPRESSIONS VS STATEMENTS
• Expressions only contain identifiers, literals and operators, where operators include
arithmetic and boolean operators, the function call operator () the subscription
operator [] and similar, and can be reduced to some kind of "value", which can be any
JavaScript object.
• Statements, on the other hand, are everything that can make up a line (or several lines) of
JavaScript code. Note that expressions are statements as well.
Expressions Statements
if (x % 2 === 0) {
console.log('Even')
}
3 + 5
"Hello".substr(1, 2)
Babel Coder
FUNCTIONS
var sum = 0
for (var i = 1; i <= 3; i++) {
sum += i
}
console.log(sum)
sum = 0
for (var i = 10; i <= 20; i++) {
sum += i
}
console.log(sum)
sum = 0
for (var i = 9; i <= 100; i++) {
sum += i
}
console.log(sum)
sum of 1 to 3
sum of 10 to 20
sum of 9 to 100
“Sum” function
Babel Coder
FUNCTIONS
function () {
}
keyword function
Parentheses
Code block between curly b
for the function body
function sayHello() {
console.log(‘Hello')
}
sayHello() // Hello
var sayHello = function() {
console.log(‘Hello')
}
sayHello() // Hello
Babel Coder
FUNCTIONS
function sum(start, end) {
var sum = 0
for(var i = start; i <= end; i++) {
sum += i
}
return sum
}
var result = sum(1, 3)
console.log(result)
result = sum(10, 20)
console.log(result)
console.log(sum(9, 100))
sum of start to end
returns sum
Parameters
Arguments
sum(1, 3)
function sum(start, end)
Parameters
Arguments
Babel Coder
ARROW FUNCTION
function foo(a) {
return a + 1
}
const foo = (a) => {
return a + 1
}
const foo = a => {
return a + 1
}
const foo = a => a + 1
const foo = a => let b = a + 1
Babel Coder
RECURSION
5! = 5 x 4 x 3 x 2 x 1
4! = 4 x 3 x 2 x 1
3! = 3 x 2 x 1
2! = 2 x 1
1! = 1
0! = 1
function factorial(n) {
var result = 1
for(var i = 1; i <= n; i++) {
result *= i
}
return result
}
console.log(factorial(5))
Babel Coder
RECURSION
fac(5)
5 fac(4)
4 fac(3)
3 fac(2)
2 fac(1)
1
X
X
X
X
2
6
24
120
120
function factorial(n) {
if (n <= 1) return 1
return n * factorial(n - 1)
}
Babel Coder
SCOPING
var result = 0
function plus(a, b) {
result = a + b
return result
}
function sum(start, end) {
for(var i = start; i <= end; i++) {
result += i
}
return result
}
plus(100, 200)
console.log(sum(1, 10)) // 355
function plus(a, b) {
var result = a + b
return result
}
function sum(start, end) {
var result = 0
for(var i = start; i <= end; i++) {
result += i
}
return result
}
plus(100, 200)
console.log(sum(1, 10)) // 55
Babel Coder
HOISTING
var a = 1
function foo() {
var b = 2
if(b > a) {
var c = 3
}
console.log(c) // 3
}
foo()
var a = 1
function foo() {
var b
var c
b = 2
if(b > a) {
c = 3
}
console.log(c) // 3
}
foo()
Babel Coder
LET AND CONST
function foo() {
let x = 1
x = 2
}
foo()
function foo() {
const x = 1
x = 2
}
foo()
Babel Coder
OBJECTS
function printDetails(gender, name, age) {
console.log(`Gender: ${gender}`, `Name: ${name}`, `Age: ${age}`)
}
printDetails('male', 'Somchai', 24)
var person = {
gender: 'male',
name: 'Somchai',
age: 24
}
function printDetails(person) {
console.log(
`Gender: ${person.gender}`,
`Name: ${person.name}`,
`Age: ${person.age}`
)
}
printDetails(person)
Babel Coder
KEYWORD THIS
var person = {
name: 'Somchai',
age: 24,
gender: 'male'
}
person.printDetails = function() {
console.log(
`Gender: ${this.gender}`,
`Name: ${this.name}`,
`Age: ${this.age}`
)
}
person.printDetails()
Object Methods
Babel Coder
METHODS
var person = {
name: 'Somchai',
age: 24,
gender: 'male',
printDetails: function() {
console.log(
`Gender: ${this.gender}`,
`Name: ${this.name}`,
`Age: ${this.age}`
)
}
}
person.printDetails()
Object Methods
Babel Coder
OBJECTS AND MEMORY
var person = {
name: 'Somchai',
age: 24,
gender: 'male'
}
person.printDetails = function() {
console.log(
`Gender: ${this.gender}`,
`Name: ${this.name}`,
`Age: ${this.age}`
)
}
person
name: ‘Somchai’
age: 24
gender: ‘male’
printDetails fn
person.printDetails
person[‘printDetails’]
Babel Coder
ARRAYS
var arr = [1, ‘Hello’, true, { a: 1, b: 2 }]
1 Hello true
arr
[0] [1] [2] [3]
{ a: 1, b: 2 }
arr[1] arr[3].b
arr[3][‘b’]
false
arr[2] = false
arr.length
Babel Coder
ARRAYS
var dayOfWeek = 1
var day
switch(dayOfWeek) {
case 1:
day = 'Sunday'
break
case 2:
day = 'Monday'
break
case 3:
day = 'Tuesday'
break
case 4:
day = 'Wednesday'
break
case 5:
day = 'Thursday'
break
case 6:
day = 'Friday'
break
case 7:
day = 'Saturday'
break
}
var dayOfWeek = 1
var daysOfWeek = {
1: 'Sunday',
2: 'Monday',
3: 'Tuesday',
4: 'Wednesday',
5: 'Thursday',
6: 'Friday',
7: 'Saturday'
}
var day = daysOfWeek[dayOfWeek]
var dayOfWeek = 1
var daysOfWeek = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
]
var day = daysOfWeek[dayOfWeek - 1]
Babel Coder
ARRAY METHODS
1 Hello true
arr
[0] [1] [2]
arr.pop()
5
arr.push(5)
[3]
arr.join() 1Hellotrue
arr.slice(1, 3)
arr.includes(1)
Babel Coder
FOREACH
const arr = [1, 'Hello', true]
arr.forEach(i => console.log(i))
1
2
3
1
Hello
true
console.log(1)
console.log(‘Hello’)
console.log(true)
Babel Coder
FOR-OF
const arr = [1, 'Hello', true]
for(let i of arr) {
console.log(i)
}
1
2
3
1
Hello
true
console.log(1)
console.log(‘Hello’)
console.log(true)
Babel Coder
FOR-IN
const obj = {
a: 1,
b: 2,
c: 3
}
for(let i in obj) {
console.log(i)
}
1
2
3
a
b
c
console.log(‘a’)
console.log(‘b’)
console.log(‘c’)
Babel Coder
OBJECTS AND ARRAY
const person = {
name: 'Somchai',
age: 24
}
const arr = ['A', 'B', 'C']
person.name
person['name']
const arr = {
0: 'A',
1: 'B',
2: 'C',
length: 3
}
arr[0]
Babel Coder
DESTRUCTURING
let person = {
age: 24,
gender: 'male',
name: {
fi
rstName: '
fi
rstName',
lastName: 'lastName'
}
}
let age = person.age
let gender = person.gender
let name = person.name
let
fi
rstName = name.
fi
rstName
let lastName = name.lastName
let { age, gender, name } = person
let {
fi
rstName, lastName } = name
let { age, gender, name: {
fi
rstName, lastName } } = person
Babel Coder
SPREAD OPERATORS
const obj1 = { a: 1, b: 2 }
const obj2 = { c: 3, d: 4 }
console.log({ ...obj1, ...obj2 })
const arr1 = [1, 2, 3]
const arr2 = [4, 5, 6]
console.log([...arr1, ...arr2])
Babel Coder
REST OPERATORS
const somchai = {
name: 'Somchai',
age: 24,
gender: 'male'
}
const { name, ...rest } = somchai
console.log(name)
console.log(rest)
Somchai
{ age: 24, gender: ‘male’ }
MAP
const nums = [1, 2, 3]
console.log(nums.map(num => num * 2)) //
[2, 4, 6]
const students = [
{ id: 1, advisorId: 1 },
{ id: 2, advisorId: 2 },
{ id: 3, advisorId: 3 },
{ id: 4, advisorId: 1 },
{ id: 5, advisorId: 3 }
]
console.log(
students.map(student =>
student.advisorId === 1 ?
{ ...student, advisorId: 2 } :
student
)
)
// [{"id":1,"advisorId":2},
{"id":2,"advisorId":2}, {"id":3,"advisorId":3},
{"id":4,"advisorId":2}, {"id":5,"advisorId":3}]
FILTER
const students = [
{ id: 1, advisorId: 1 },
{ id: 2, advisorId: 2 },
{ id: 3, advisorId: 3 },
{ id: 4, advisorId: 1 },
{ id: 5, advisorId: 3 }
]
console.log(
students.filter(student => student.advisorId === 1)
)
// [{"id":1,"advisorId":1},{"id":4,"advisorId":1}]
FIND / FIND INDEX
const nums = [1, 2, 3, 4, 5]
nums.find(num => num % 2 === 0) // 2
const nums = [1, 2, 3, 4, 5]
nums.findIndex(num => num % 2 === 0) // 1
REDUCE
const nums = [1, 2, 3, 4, 5]
nums.reduce((sum, num) => sum + num)
nums.reduce((sum, num) => sum + num, 0)
nums.reduceRight((sum, num) => sum + num)
Babel Coder
CLASSES
const printDetails = function() {
console.log(
`Gender: ${this.gender}`,
`Name: ${this.name}`,
`Age: ${this.age}`
)
}
const somchai = {
name: 'Somchai',
age: 24,
gender: 'male'
}
somchai.printDetails = printDetails
somchai.printDetails()
const somsree = {
name: 'Somsree',
age: 21,
gender: 'female'
}
somsree.printDetails = printDetails
somsree.printDetails()
Behaviors Properties Properties
Babel Coder
CLASSES
class Person {
constructor(name, age, gender) {
this.name = name
this.age = age
this.gender = gender
}
printDetails() {
console.log(
`Gender: ${this.gender}`,
`Name: ${this.name}`,
`Age: ${this.age}`
)
}
}
const somchai = new Person('Somchai', 24, 'male')
somchai.printDetails()
const somsree = new Person('Somsree', 21, 'female')
somsree.printDetails()
Initialize
Properties
Behaviors
Create an instance
Babel Coder
INHERITANCE
class Woman extends Person {
constructor(name, age, hasPregnent) {
super(name, age, 'female')
this.hasPregnent = hasPregnent
}
printDetails() {
super.printDetails()
console.log('Pregnent', this.hasPregnent)
}
}
const somsree = new Woman('Somsree', 21, true)
somsree.printDetails()
Inherite
Babel Coder
STATIC PROPERTIES & METHODS
class Circle {
static PI = 3.14
static withRadius(radius) {
return new Circle(radius)
}
constructor(radius) {
this.radius = radius
}
getArea() {
return this.constructor.PI * Math.pow(this.radius, 2)
}
}
static properties
static methods
Circle.PI // 3.14
const circle = Circle.withRadius(10)
circle.getArea() // 314
function Circle() {}
Circle.PI = 3.14
Alternative
Babel Coder
EXCEPTION HANDLING
const person = {
name: 'Somchai',
age: 24
}
console.log(person.address.street)
Uncaught TypeError: Cannot read property 'street' of unde
fi
ned
try {
console.log(person.address.street)
} catch(ex) {
console.log(ex.message)
}
Babel Coder
ASYNC
Fetching
Babel Coder
TIMING
console.log(1)
setTimeout(() => console.log(2), 1000)
console.log(3)
1
3
2
1,000 ms
Babel Coder
FETCHING
Fetch Articles
fetch(‘https://www.babelcoder.com/api/v1/articles')
Fetch Users
fetch(‘https://www.babelcoder.com/api/v1/users')
Babel Coder
FETCHING
fetch('/api/v1/articles/1', function(response) {
fetch('/api/v1/users/' + response.authorId, function(response) {
// ...
})
})
fetch('/api/v1/articles/1')
.then(function(response) {
return fetch('/api/v1/users/' + response.authorId)
})
.then(function() { })
Babel Coder
JSON RESPONSE
Fetch Articles
fetch('https://www.babelcoder.com/api/v1/articles')
.then(res => res.json())
.then(json => console.log(json))
Babel Coder
AXIOS
import axios from 'axios'
axios.get('/articles')
.then(res => console.log(res.data))
axios.post('/articles', { title: 'Title#1', content: 'Content#1' })
.then(res => console.log(res.data))
GET
POST
PROMISE
var promise = new Promise(function(resolve,
reject) {
setTimeout(function() {
resolve('Done')
}, 1000)
})
promise.then(function(result) {
console.log(result)
}).catch(function(error) {
console.log(error)
})
Pending
Fulfilled
var promise = new Promise(function(resolve,
reject) {
setTimeout(function() {
reject('Fail')
}, 1000)
})
promise.then(function(result) {
console.log(result)
}).catch(function(error) {
console.log(error)
})
Pending
Rejected
ASYNC / AWAIT
promise.then(function(result) {
console.log(result)
}).catch(function(error) {
console.log(error)
})
async function doAsync() {
try {
const result = await promise
console.log(result)
} catch(error) {
console.log(error)
}
}
EXAMPLE 1
Fetch content from URL: https://jsonplaceholder.typicode.com/todos
import axios from 'axios'
async function fetchPosts() {
const res =await axios.get(URL)
console.log(res.data)
console.log(res.status) // 200
}
fetchPosts()
HTTP GET HTTP POST
import axios from 'axios'
async function createPost() {
const res =await axios.post(
URL, { title: 'Test', completed: true })
console.log(res.status) // 201
}
createPost()
ES MODULE - NAMED EXPORTS
export const DEFAULT_COLOR = 'white'
export function walk() {
console.log('Walking...')
}
{
DEFAULT_COLOR: 'white',
walk() {
console.log('Walking...')
}
}
dog.js
main.js
syntax: 1
import * as lib from './dog.js'
lib.DEFAULT_COLOR // white
lib.walk() // Walking...
main.js
syntax: 2
import { DEFAULT_COLOR, walk } from './dog.js'
ES MODULE - DEFAULT EXPORT
circle.js
main.js
syntax
export default class Circle {
area() {
}
}
import Circle from './circle.js'
ES MODULE - BOTH
circle.js
export const PI = 3.14
export default class Circle {
area() {
}
}
main.js
syntax
import Circle, { PI } from './circle.js'

More Related Content

Similar to javascript for modern application.pdf

Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
Varun C M
 
ES6 General Introduction
ES6 General IntroductionES6 General Introduction
ES6 General Introduction
Thomas Johnston
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Paulo Ragonha
 

Similar to javascript for modern application.pdf (20)

DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScript
 
Polyglot Programming in the JVM - Øredev
Polyglot Programming in the JVM - ØredevPolyglot Programming in the JVM - Øredev
Polyglot Programming in the JVM - Øredev
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
JavaFX Your Way: Building JavaFX Applications with Alternative Languages
JavaFX Your Way: Building JavaFX Applications with Alternative LanguagesJavaFX Your Way: Building JavaFX Applications with Alternative Languages
JavaFX Your Way: Building JavaFX Applications with Alternative Languages
 
Testing most things in JavaScript - LeedsJS 31/05/2017
Testing most things in JavaScript - LeedsJS 31/05/2017Testing most things in JavaScript - LeedsJS 31/05/2017
Testing most things in JavaScript - LeedsJS 31/05/2017
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
recap-js.pdf
recap-js.pdfrecap-js.pdf
recap-js.pdf
 
Polyglot Programming in the JVM - 33rd Degree
Polyglot Programming in the JVM - 33rd DegreePolyglot Programming in the JVM - 33rd Degree
Polyglot Programming in the JVM - 33rd Degree
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
Ruby Blocks
Ruby BlocksRuby Blocks
Ruby Blocks
 
Weird Javascript Weekends first session presentaion
Weird Javascript Weekends first session presentaionWeird Javascript Weekends first session presentaion
Weird Javascript Weekends first session presentaion
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
 
JavaOne 2016 -Emerging Web App Architectures using Java and node.js
JavaOne 2016 -Emerging Web App Architectures using Java and node.jsJavaOne 2016 -Emerging Web App Architectures using Java and node.js
JavaOne 2016 -Emerging Web App Architectures using Java and node.js
 
Building and Distributing PostgreSQL Extensions Without Learning C
Building and Distributing PostgreSQL Extensions Without Learning CBuilding and Distributing PostgreSQL Extensions Without Learning C
Building and Distributing PostgreSQL Extensions Without Learning C
 
ES6 General Introduction
ES6 General IntroductionES6 General Introduction
ES6 General Introduction
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 

More from NuttavutThongjor1

8 iac.pdf 8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf
8 iac.pdf 8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf 8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf
8 iac.pdf 8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf
NuttavutThongjor1
 
6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf
6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf
6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf
NuttavutThongjor1
 
mean stack mean stack mean stack mean stack
mean stack mean stack  mean stack  mean stackmean stack mean stack  mean stack  mean stack
mean stack mean stack mean stack mean stack
NuttavutThongjor1
 

More from NuttavutThongjor1 (20)

Intro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdf
Intro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdf
Intro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdf
 
10 วัฒนธรรมองค์กรของ DevOps.pdf10 วัฒนธรรมองค์กรของ DevOps.pdf
10 วัฒนธรรมองค์กรของ DevOps.pdf10 วัฒนธรรมองค์กรของ DevOps.pdf10 วัฒนธรรมองค์กรของ DevOps.pdf10 วัฒนธรรมองค์กรของ DevOps.pdf
10 วัฒนธรรมองค์กรของ DevOps.pdf10 วัฒนธรรมองค์กรของ DevOps.pdf
 
9 logging and monitoring.pdf 9 logging and monitoring.pdf
9 logging and monitoring.pdf 9 logging and monitoring.pdf9 logging and monitoring.pdf 9 logging and monitoring.pdf
9 logging and monitoring.pdf 9 logging and monitoring.pdf
 
8 iac.pdf 8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf
8 iac.pdf 8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf 8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf
8 iac.pdf 8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf
 
7 cicd.pdf 7 cicd.pdf 7 cicd.pdf 7 cicd.pdf
7 cicd.pdf 7 cicd.pdf 7 cicd.pdf 7 cicd.pdf7 cicd.pdf 7 cicd.pdf 7 cicd.pdf 7 cicd.pdf
7 cicd.pdf 7 cicd.pdf 7 cicd.pdf 7 cicd.pdf
 
6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf
6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf
6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf
 
5 Kubernetes.pdf 5 Kubernetes.pdf 5 Kubernetes.pdf
5 Kubernetes.pdf 5 Kubernetes.pdf 5 Kubernetes.pdf5 Kubernetes.pdf 5 Kubernetes.pdf 5 Kubernetes.pdf
5 Kubernetes.pdf 5 Kubernetes.pdf 5 Kubernetes.pdf
 
4 Docker.pdf 4 Docker.pdf 4 Docker.pdf 4 Docker.pdf
4 Docker.pdf 4 Docker.pdf 4 Docker.pdf 4 Docker.pdf4 Docker.pdf 4 Docker.pdf 4 Docker.pdf 4 Docker.pdf
4 Docker.pdf 4 Docker.pdf 4 Docker.pdf 4 Docker.pdf
 
3 Microservices.pdf 3 Microservices 3 Microservices.pdf.pdf
3 Microservices.pdf 3 Microservices 3 Microservices.pdf.pdf3 Microservices.pdf 3 Microservices 3 Microservices.pdf.pdf
3 Microservices.pdf 3 Microservices 3 Microservices.pdf.pdf
 
2 เทคโนโลยี cloud computing.pdf 2 เทคโนโลยี cloud computing.pdf
2 เทคโนโลยี cloud computing.pdf 2 เทคโนโลยี cloud computing.pdf2 เทคโนโลยี cloud computing.pdf 2 เทคโนโลยี cloud computing.pdf
2 เทคโนโลยี cloud computing.pdf 2 เทคโนโลยี cloud computing.pdf
 
1 devops คืออะไร.pdf 1 devops คืออะไร.pdf
1 devops คืออะไร.pdf 1 devops คืออะไร.pdf1 devops คืออะไร.pdf 1 devops คืออะไร.pdf
1 devops คืออะไร.pdf 1 devops คืออะไร.pdf
 
angular fundamentals.pdf angular fundamentals.pdf
angular fundamentals.pdf angular fundamentals.pdfangular fundamentals.pdf angular fundamentals.pdf
angular fundamentals.pdf angular fundamentals.pdf
 
mean stack mean stack mean stack mean stack
mean stack mean stack  mean stack  mean stackmean stack mean stack  mean stack  mean stack
mean stack mean stack mean stack mean stack
 
pinia.pdf
pinia.pdfpinia.pdf
pinia.pdf
 
nuxt-rendering-modes.pdf
nuxt-rendering-modes.pdfnuxt-rendering-modes.pdf
nuxt-rendering-modes.pdf
 
zustand.pdf
zustand.pdfzustand.pdf
zustand.pdf
 
tanstack-query.pdf
tanstack-query.pdftanstack-query.pdf
tanstack-query.pdf
 
nuxt-fundamentals.pdf
nuxt-fundamentals.pdfnuxt-fundamentals.pdf
nuxt-fundamentals.pdf
 
vue-components.pdf
vue-components.pdfvue-components.pdf
vue-components.pdf
 
vue-reactivity.pdf
vue-reactivity.pdfvue-reactivity.pdf
vue-reactivity.pdf
 

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 

javascript for modern application.pdf

  • 3. Babel Coder CSS HTML JavaScript THE WEB TECHNOLOGIES Structure — HTML Presentation — CSS Behavior — JavaScript
  • 4. Babel Coder JAVASCRIPT IN THE BROWSER Render HTTP Request
  • 5. Babel Coder JAVASCRIPT IN THE SERVER Render HTTP Request
  • 6. Babel Coder HOW COMPUTERS WORK 0 or 1 0 or 1 0 or 1 0 or 1 011001100111
  • 7. Babel Coder HOW PROGRAMS WORK Load Execute Display
  • 10. Babel Coder VARIABLES • A variable is a named value in your program. • Whenever you use the name in the program, it’s replaced with the value. var age The var keyword tells the computer to take the next word in the statement and turn it into a variable. Variable name age = 12 The assignment operator var age = 12 Declare a variable Assign a value
  • 11. Babel Coder VARIABLE NAMES var thisIsMyBook; var $whatMyName; var _withUnderscore; var StartWithCapital; var 123; var 456abc; var &special; var separate by space; var if Valid variables Invalid variables DYNAMIC TYPING Variables in JavaScript are not directly associated with any particular value type, and any variable can be assigned (and re- assigned) values of all types. var foo = 42 // foo is now a Number var foo = 'bar' // foo is now String var foo = true // foo is Now Boolean
  • 12. Babel Coder DATA TYPES Primitive • Boolean • Null • Unde fi ned • Number • String • Symbol Object • Array • TypedArray • Dates • Map • Set • WeakMap • WeakSet typeof(<VARIABLE>) Check data type of this variable
  • 13. Babel Coder BOOLEAN P / Q T F T T F F F F P / Q T F T T T F T F AND OR
  • 14. Babel Coder NUMBER Number 10 / 3 3 rem 1 10 % 3 Math.random() 0 <= number < 1 Math.PI // 3.14 Math.round(4.7) // 5 Math.round(4.4) // 4 Math.pow(8, 2) // 64 Math.sqrt(64) // 8 Math.abs(-4.7) // 4.7 Math.ceil(4.4) // 5 Math. fl oor(4.7) // 4
  • 15. Babel Coder OPERATORS 8 == “8” 8 === “8” Strict Equality Operator var num = 10 num = num + 10 num += 10 Shorthand 2 + 3 // Addition 3 * 4 // Multiply 5 / 2 // Divide 7 % 2 // Remainder
  • 16. Babel Coder STRING Template String Code Output n New line t Tab Backslash ’ Single quote ” Double quote var myStr1 = 'Hello World' var myStr2 = "Hello World" var myStr3 = "HellonWorld" var myStr4 = ` Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ` var myStr5 = `${myStr1} Krub`
  • 17. Babel Coder STRING var name = ‘BABELcoDER’ name B A B E L c o D E R [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] name.length name[3] name.endsWith(‘ER’) name.startsWith(‘BABEL’) name.includes(‘oDE’) name.indexOf(‘L’)
  • 18. Babel Coder STRING B A B E L c o D E R [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] B A B E L C O D E R b a b e l c o d e r name.toUpperCase() name.toLowerCase()
  • 19. Babel Coder STRING B A B E L C O D E R B A B B A B E L B A B E R name.replace(‘COD’, ‘BAB’)
  • 20. Babel Coder STRING B A B E L C O D E R name.substr(2, 3) name.slice(2, 5)
  • 21. Babel Coder SYMBOL Every symbol value returned from Symbol() is unique. A symbol value may be used as an identi fi er for object properties; this is the data type's only purpose. const str1 = 'Hello' const str2 = 'Hello' const sym1 = Symbol('hello') const sym2 = Symbol('hello') console.log(str1 === str2) // true console.log(sym1 === sym2) // false
  • 22. Babel Coder PRINTING var msg = 'Hello' console.log(msg) // Hello console.log('Hello') // Hello console.log(msg, 'World') // Hello World
  • 23. Babel Coder IF-ELSE STATEMENT num > 0.5 Yes No Y N var num = Math.random() if (num > 0.5) { console.log('Yes') } else { console.log('No') }
  • 24. Babel Coder COMPARISON OPERATORS Operator Name Example Evaluates to > Greather than 15 > 3 true >= Greather than or equal to 12 >= 12 true < Less than 7 < 3 true <= Less than or equal to 3 <= 5 false == equal to 3 == 5 false != not equal to 3 != 5 true === strictly equal to 3 === “3” true !== not strictly equal to 3 !== “3” true
  • 25. Babel Coder IF-ELSE-IF STATEMENT score >= 80 Grade A Y N score >= 70 Grade B Y N score >= 60 Grade C Y N score >= 50 Grade D Y N Grade F var score = 50 var grade if (score >= 80) { grade = 'A' } else if (score >= 70) { grade = 'B' } else if (score >= 60) { grade = 'C' } else if (score >= 50) { grade = 'D' } else { grade = 'F' }
  • 26. Babel Coder SWITCH STATEMENT Default Case switch(new Date().getDay()) { case 0: day = 'Sunday' break case 1: day = 'Monday' break case 2: day = 'Tuesday' break case 3: day = 'Wednesday' break case 4: day = 'Thursday' break case 5: day = 'Friday' break case 6: day = 'Saturday' break } var text switch (new Date().getDay()) { case 4: case 5: text = 'Soon it is Weekend' break case 0: case 6: text = 'It is Weekend' break default: text = 'Looking forward to the Weekend' }
  • 27. Babel Coder FOR LOOP var sum = 0 for (var i = 1; i <= 3; i++) { sum += i } Initial Condition Post Condition Loop i sum 1 1 0 2 2 1 3 3 3 6 i <= 3 sum += i Y N var sum = 0 sum += 1 sum += 2 sum += 3
  • 28. Babel Coder WHILE LOOP var sum = 0 var i = 1 while (i <= 3) { sum += i i++ } Initial Condition Post Condition var sum = 0 sum += 1 sum += 2 sum += 3
  • 29. Babel Coder TERNARY OPERATOR var i = 22 console.log(i % 2 === 0 ? 'Even' : 'Odd') true false
  • 30. Babel Coder EXPRESSIONS VS STATEMENTS • Expressions only contain identifiers, literals and operators, where operators include arithmetic and boolean operators, the function call operator () the subscription operator [] and similar, and can be reduced to some kind of "value", which can be any JavaScript object. • Statements, on the other hand, are everything that can make up a line (or several lines) of JavaScript code. Note that expressions are statements as well. Expressions Statements if (x % 2 === 0) { console.log('Even') } 3 + 5 "Hello".substr(1, 2)
  • 31. Babel Coder FUNCTIONS var sum = 0 for (var i = 1; i <= 3; i++) { sum += i } console.log(sum) sum = 0 for (var i = 10; i <= 20; i++) { sum += i } console.log(sum) sum = 0 for (var i = 9; i <= 100; i++) { sum += i } console.log(sum) sum of 1 to 3 sum of 10 to 20 sum of 9 to 100 “Sum” function
  • 32. Babel Coder FUNCTIONS function () { } keyword function Parentheses Code block between curly b for the function body function sayHello() { console.log(‘Hello') } sayHello() // Hello var sayHello = function() { console.log(‘Hello') } sayHello() // Hello
  • 33. Babel Coder FUNCTIONS function sum(start, end) { var sum = 0 for(var i = start; i <= end; i++) { sum += i } return sum } var result = sum(1, 3) console.log(result) result = sum(10, 20) console.log(result) console.log(sum(9, 100)) sum of start to end returns sum Parameters Arguments sum(1, 3) function sum(start, end) Parameters Arguments
  • 34. Babel Coder ARROW FUNCTION function foo(a) { return a + 1 } const foo = (a) => { return a + 1 } const foo = a => { return a + 1 } const foo = a => a + 1 const foo = a => let b = a + 1
  • 35. Babel Coder RECURSION 5! = 5 x 4 x 3 x 2 x 1 4! = 4 x 3 x 2 x 1 3! = 3 x 2 x 1 2! = 2 x 1 1! = 1 0! = 1 function factorial(n) { var result = 1 for(var i = 1; i <= n; i++) { result *= i } return result } console.log(factorial(5))
  • 36. Babel Coder RECURSION fac(5) 5 fac(4) 4 fac(3) 3 fac(2) 2 fac(1) 1 X X X X 2 6 24 120 120 function factorial(n) { if (n <= 1) return 1 return n * factorial(n - 1) }
  • 37. Babel Coder SCOPING var result = 0 function plus(a, b) { result = a + b return result } function sum(start, end) { for(var i = start; i <= end; i++) { result += i } return result } plus(100, 200) console.log(sum(1, 10)) // 355 function plus(a, b) { var result = a + b return result } function sum(start, end) { var result = 0 for(var i = start; i <= end; i++) { result += i } return result } plus(100, 200) console.log(sum(1, 10)) // 55
  • 38. Babel Coder HOISTING var a = 1 function foo() { var b = 2 if(b > a) { var c = 3 } console.log(c) // 3 } foo() var a = 1 function foo() { var b var c b = 2 if(b > a) { c = 3 } console.log(c) // 3 } foo()
  • 39. Babel Coder LET AND CONST function foo() { let x = 1 x = 2 } foo() function foo() { const x = 1 x = 2 } foo()
  • 40. Babel Coder OBJECTS function printDetails(gender, name, age) { console.log(`Gender: ${gender}`, `Name: ${name}`, `Age: ${age}`) } printDetails('male', 'Somchai', 24) var person = { gender: 'male', name: 'Somchai', age: 24 } function printDetails(person) { console.log( `Gender: ${person.gender}`, `Name: ${person.name}`, `Age: ${person.age}` ) } printDetails(person)
  • 41. Babel Coder KEYWORD THIS var person = { name: 'Somchai', age: 24, gender: 'male' } person.printDetails = function() { console.log( `Gender: ${this.gender}`, `Name: ${this.name}`, `Age: ${this.age}` ) } person.printDetails() Object Methods
  • 42. Babel Coder METHODS var person = { name: 'Somchai', age: 24, gender: 'male', printDetails: function() { console.log( `Gender: ${this.gender}`, `Name: ${this.name}`, `Age: ${this.age}` ) } } person.printDetails() Object Methods
  • 43. Babel Coder OBJECTS AND MEMORY var person = { name: 'Somchai', age: 24, gender: 'male' } person.printDetails = function() { console.log( `Gender: ${this.gender}`, `Name: ${this.name}`, `Age: ${this.age}` ) } person name: ‘Somchai’ age: 24 gender: ‘male’ printDetails fn person.printDetails person[‘printDetails’]
  • 44. Babel Coder ARRAYS var arr = [1, ‘Hello’, true, { a: 1, b: 2 }] 1 Hello true arr [0] [1] [2] [3] { a: 1, b: 2 } arr[1] arr[3].b arr[3][‘b’] false arr[2] = false arr.length
  • 45. Babel Coder ARRAYS var dayOfWeek = 1 var day switch(dayOfWeek) { case 1: day = 'Sunday' break case 2: day = 'Monday' break case 3: day = 'Tuesday' break case 4: day = 'Wednesday' break case 5: day = 'Thursday' break case 6: day = 'Friday' break case 7: day = 'Saturday' break } var dayOfWeek = 1 var daysOfWeek = { 1: 'Sunday', 2: 'Monday', 3: 'Tuesday', 4: 'Wednesday', 5: 'Thursday', 6: 'Friday', 7: 'Saturday' } var day = daysOfWeek[dayOfWeek] var dayOfWeek = 1 var daysOfWeek = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ] var day = daysOfWeek[dayOfWeek - 1]
  • 46. Babel Coder ARRAY METHODS 1 Hello true arr [0] [1] [2] arr.pop() 5 arr.push(5) [3] arr.join() 1Hellotrue arr.slice(1, 3) arr.includes(1)
  • 47. Babel Coder FOREACH const arr = [1, 'Hello', true] arr.forEach(i => console.log(i)) 1 2 3 1 Hello true console.log(1) console.log(‘Hello’) console.log(true)
  • 48. Babel Coder FOR-OF const arr = [1, 'Hello', true] for(let i of arr) { console.log(i) } 1 2 3 1 Hello true console.log(1) console.log(‘Hello’) console.log(true)
  • 49. Babel Coder FOR-IN const obj = { a: 1, b: 2, c: 3 } for(let i in obj) { console.log(i) } 1 2 3 a b c console.log(‘a’) console.log(‘b’) console.log(‘c’)
  • 50. Babel Coder OBJECTS AND ARRAY const person = { name: 'Somchai', age: 24 } const arr = ['A', 'B', 'C'] person.name person['name'] const arr = { 0: 'A', 1: 'B', 2: 'C', length: 3 } arr[0]
  • 51. Babel Coder DESTRUCTURING let person = { age: 24, gender: 'male', name: { fi rstName: ' fi rstName', lastName: 'lastName' } } let age = person.age let gender = person.gender let name = person.name let fi rstName = name. fi rstName let lastName = name.lastName let { age, gender, name } = person let { fi rstName, lastName } = name let { age, gender, name: { fi rstName, lastName } } = person
  • 52. Babel Coder SPREAD OPERATORS const obj1 = { a: 1, b: 2 } const obj2 = { c: 3, d: 4 } console.log({ ...obj1, ...obj2 }) const arr1 = [1, 2, 3] const arr2 = [4, 5, 6] console.log([...arr1, ...arr2])
  • 53. Babel Coder REST OPERATORS const somchai = { name: 'Somchai', age: 24, gender: 'male' } const { name, ...rest } = somchai console.log(name) console.log(rest) Somchai { age: 24, gender: ‘male’ }
  • 54. MAP const nums = [1, 2, 3] console.log(nums.map(num => num * 2)) // [2, 4, 6] const students = [ { id: 1, advisorId: 1 }, { id: 2, advisorId: 2 }, { id: 3, advisorId: 3 }, { id: 4, advisorId: 1 }, { id: 5, advisorId: 3 } ] console.log( students.map(student => student.advisorId === 1 ? { ...student, advisorId: 2 } : student ) ) // [{"id":1,"advisorId":2}, {"id":2,"advisorId":2}, {"id":3,"advisorId":3}, {"id":4,"advisorId":2}, {"id":5,"advisorId":3}]
  • 55. FILTER const students = [ { id: 1, advisorId: 1 }, { id: 2, advisorId: 2 }, { id: 3, advisorId: 3 }, { id: 4, advisorId: 1 }, { id: 5, advisorId: 3 } ] console.log( students.filter(student => student.advisorId === 1) ) // [{"id":1,"advisorId":1},{"id":4,"advisorId":1}]
  • 56. FIND / FIND INDEX const nums = [1, 2, 3, 4, 5] nums.find(num => num % 2 === 0) // 2 const nums = [1, 2, 3, 4, 5] nums.findIndex(num => num % 2 === 0) // 1
  • 57. REDUCE const nums = [1, 2, 3, 4, 5] nums.reduce((sum, num) => sum + num) nums.reduce((sum, num) => sum + num, 0) nums.reduceRight((sum, num) => sum + num)
  • 58. Babel Coder CLASSES const printDetails = function() { console.log( `Gender: ${this.gender}`, `Name: ${this.name}`, `Age: ${this.age}` ) } const somchai = { name: 'Somchai', age: 24, gender: 'male' } somchai.printDetails = printDetails somchai.printDetails() const somsree = { name: 'Somsree', age: 21, gender: 'female' } somsree.printDetails = printDetails somsree.printDetails() Behaviors Properties Properties
  • 59. Babel Coder CLASSES class Person { constructor(name, age, gender) { this.name = name this.age = age this.gender = gender } printDetails() { console.log( `Gender: ${this.gender}`, `Name: ${this.name}`, `Age: ${this.age}` ) } } const somchai = new Person('Somchai', 24, 'male') somchai.printDetails() const somsree = new Person('Somsree', 21, 'female') somsree.printDetails() Initialize Properties Behaviors Create an instance
  • 60. Babel Coder INHERITANCE class Woman extends Person { constructor(name, age, hasPregnent) { super(name, age, 'female') this.hasPregnent = hasPregnent } printDetails() { super.printDetails() console.log('Pregnent', this.hasPregnent) } } const somsree = new Woman('Somsree', 21, true) somsree.printDetails() Inherite
  • 61. Babel Coder STATIC PROPERTIES & METHODS class Circle { static PI = 3.14 static withRadius(radius) { return new Circle(radius) } constructor(radius) { this.radius = radius } getArea() { return this.constructor.PI * Math.pow(this.radius, 2) } } static properties static methods Circle.PI // 3.14 const circle = Circle.withRadius(10) circle.getArea() // 314 function Circle() {} Circle.PI = 3.14 Alternative
  • 62. Babel Coder EXCEPTION HANDLING const person = { name: 'Somchai', age: 24 } console.log(person.address.street) Uncaught TypeError: Cannot read property 'street' of unde fi ned try { console.log(person.address.street) } catch(ex) { console.log(ex.message) }
  • 64. Babel Coder TIMING console.log(1) setTimeout(() => console.log(2), 1000) console.log(3) 1 3 2 1,000 ms
  • 66. Babel Coder FETCHING fetch('/api/v1/articles/1', function(response) { fetch('/api/v1/users/' + response.authorId, function(response) { // ... }) }) fetch('/api/v1/articles/1') .then(function(response) { return fetch('/api/v1/users/' + response.authorId) }) .then(function() { })
  • 67. Babel Coder JSON RESPONSE Fetch Articles fetch('https://www.babelcoder.com/api/v1/articles') .then(res => res.json()) .then(json => console.log(json))
  • 68. Babel Coder AXIOS import axios from 'axios' axios.get('/articles') .then(res => console.log(res.data)) axios.post('/articles', { title: 'Title#1', content: 'Content#1' }) .then(res => console.log(res.data)) GET POST
  • 69. PROMISE var promise = new Promise(function(resolve, reject) { setTimeout(function() { resolve('Done') }, 1000) }) promise.then(function(result) { console.log(result) }).catch(function(error) { console.log(error) }) Pending Fulfilled var promise = new Promise(function(resolve, reject) { setTimeout(function() { reject('Fail') }, 1000) }) promise.then(function(result) { console.log(result) }).catch(function(error) { console.log(error) }) Pending Rejected
  • 70. ASYNC / AWAIT promise.then(function(result) { console.log(result) }).catch(function(error) { console.log(error) }) async function doAsync() { try { const result = await promise console.log(result) } catch(error) { console.log(error) } }
  • 71. EXAMPLE 1 Fetch content from URL: https://jsonplaceholder.typicode.com/todos import axios from 'axios' async function fetchPosts() { const res =await axios.get(URL) console.log(res.data) console.log(res.status) // 200 } fetchPosts() HTTP GET HTTP POST import axios from 'axios' async function createPost() { const res =await axios.post( URL, { title: 'Test', completed: true }) console.log(res.status) // 201 } createPost()
  • 72. ES MODULE - NAMED EXPORTS export const DEFAULT_COLOR = 'white' export function walk() { console.log('Walking...') } { DEFAULT_COLOR: 'white', walk() { console.log('Walking...') } } dog.js main.js syntax: 1 import * as lib from './dog.js' lib.DEFAULT_COLOR // white lib.walk() // Walking... main.js syntax: 2 import { DEFAULT_COLOR, walk } from './dog.js'
  • 73. ES MODULE - DEFAULT EXPORT circle.js main.js syntax export default class Circle { area() { } } import Circle from './circle.js'
  • 74. ES MODULE - BOTH circle.js export const PI = 3.14 export default class Circle { area() { } } main.js syntax import Circle, { PI } from './circle.js'