JavaScript Part 2
In this post, we continue JS Basic series
- Conditional statement
- If statement:
if(1 > 0) {
console.log('You win lottery ticket')
}- If … else statement:
let isChecked = true
if(isChecked) {
console.log ('You win lottery ticket')
} else {
console.log ('You lost')
}- If … else if statement:
let point = 6
if (point < 5) {
console.log('Bad')
} else if(point < 7) {
console.log ('Medium')
} else if(point < 9) {
console.log('Good')
} else {
console.log('Exellent')
}- Switch case
let choose = 1
switch (choose) {
case 1:
console.log('Start')
break
case 2:
console.log('Option')
break
case 3:
console.log('Information')
break
default:
console.log('Exit')
}2. Loops
- While
The while loop checks condition before executing the code inside
let a = 1
let sum = 0
while (a <= 10) {
sum += a
a++
}
console.log(sum) // 55- do…while
The do-while loop executes the code first at least once and then checks the condition for the next time
let b = 2
let total = 0
do {
total += b
b++
} while (b <= 10)
console.log(total) // 54- For
for (i=0; i < 10; i++) {
console.log(i)
}- For … in
The for-in loop iterates over the keys of an object
let dog = {name:'Husky', skill: 'Good eat'}
let text = ''
for (let x in dog) {
text += dog[x] + ' '
}
console.log(text)- For … of
The for-of loop uses value pairs of typical iterable objects like arrays or strings
let Dog= ['Husky', 'eat', 'sleep' ]
let name = ''
for (let value of Dog) {
name += value + ' '
}
console.log(name)3. Function
A function in JavaScript is a piece of code designed to do a particular task. Javascript function is executed when calling it.
Classify
- Function declaration: With this option, the function will be hoisted and JS allows us to call the function before the function is declared.
hoisted();
function hoisted(){
console.log('This function is hoisted!!');
};Function Expression Declaring a function in option below will not be hoisted and will give an error
exception();
var exception = function(){
console.log('You will get error')
};
//Exception is not a functionThe variable var expression is still hoisted and pushed to the top of the scope but is just declared without being assigned to the function. So there should be a TypeError
Anonymus function
An anonymous function is an unnamed function. If we notice, the right hand side of a function expression is an anonymous function. In addition, anonymous functions appear in the callback.
Get Nguyễn Tấn Phát’s stories in your inbox
Join Medium for free to get updates from this writer.
Function in setTimeout() is an Anonymus Function
setTimeout(function() {
console.log('After 2 seconds print this line!')
},2000)Arrow Function
The reduced function is shorter than the function expression and does not depend on this. Works well for anonymous functions but can be used as constructors.
const handleClick = () => {
console.log('You clicked')
}Notice with Arrow function
- Not this
- Not called with new
- No super when inheriting class
Parameter & Argument
Parameter acts as a placeholder for the value to be passed into the function when creating the function
Argument serves as the value to pass into the function when calling the function Concrete
Example
function sum (a, b) { // a, b is Parameter
return a + b
}
sum(4,5) // 4,5 is Argument- Default parameter
function def(x, y = x) {
console.log(x, y)
}
def(3) // 3 3
def(3, 5) // 3 5Callback
Callback is a function, that is passed to another function as an argument
const num = ['John', 'Anna', 'Linda', 'Piter']
num.forEach((item, index) => {
console.log('ID: ', index, 'is ', item)
})
const result = num.map((item, index) => `STT: ${index} is ${item}` )Cloresure
How a parent function returns a child function within it. Inside that child function can access and execute the parent function’s variables. These two conditions must be met to be called a closure function
const increase = () => {
let x = 0
const increaseInner = () => ++x
return increaseInner
}
const myFunction = increase()
console.log(increase()())
console.log(increase()())
console.log(myFunction())
console.log(myFunction())
console.log(myFunction())Currying
Allows to convert a function with many parameters into consecutive functions with one parameter
const findNumber = (num) => (func) => {
const result = []
for (let i = 0; i < num; i++) {
if(func(i)){
result.push(i)
}
}
return result
}
findNumber(10) ((number) => number % 2 === 1)
findNumber(20) ((number) => number % 2 === 0)
findNumber(30) ((number) => number % 3 === 2)4. Call, Apply & Bind
Call
Allows you to pass an object and comma-separated arguments
Apply
Same as Call. Call the function, passing an object and then the arguments through the array
Bind
Returns a new function. Allows to pass an object and comma-separated arguments
When we use 3 functions, ‘this’ is refers to the object being pass in
let dog = {name: 'Alaska', skill: "love sleeping"}
function animal (text1, text2) {
console.log(text1 + ' ' + text2 + ' ' + this.name + ' ' + this.skill )
}
animal.call(dog, 'Hi', 'call')
animal.apply(dog,['Hi', 'apply'])
const newAnimal = animal.bind(dog,'Hi','bind')
newAnimal()Above is overview of basic JavaScript usage, I hope it helped you
“Thanks for reading. See you in the next post. “
“Happy coding!!!”.
Reference:






