If it has functions, it's a functional langugage
// for each x, y will be returned (f(x)=x^2)
function square(x) {
return x*x
}
square(2) // 4
square(3) // 9
function higherOrder(secondFunction) {
return secondFunction
}
function f() {
return "f-function"
}
higherOrder(f) // [Function: f]
higherOrder(f)() // f-function
const greet = (time, title, lastname) => {
console.log(
`Good ${time}, ${title} ${lastname}`
)
}
greet("Morning", "Mr.", "Mozart")
// Good Morning, Mr. Mozart
const greet = time =>
title =>
lastname =>
`Good ${time}, ${title} ${lastname}`
greet("Morning")("Mr.")("Mozart")
add = (a) => (b) => a + b
// no "let" or "const needed
add(2)(3) // 5
// is the same as:
function add(a) {
return function(b) {
return a + b
}
}
const data = [
{name: "Max", age: 24},
{name: "Tom", age: 21},
{name: "Anna", age: 24},
{name: "Carl", age: 29}
]
const names = data.map((obj) => {
return obj.name
})
names // [ 'Max', 'Tom', 'Anna', 'Carl' ]
// using data from the previous Map example
const names = data.map((obj) => obj.name).map(
name => "Person: " + name
)
names /* [ 'Person: Max',
'Person: Tom', 'Person: Anna',
'Person: Carl' ] */
let arr = [1, 2, 3, 4]
// update the array with doubled values
arr = arr.map(item => {
return item * 2
})
// alternative, shorthand syntax
arr = arr.map(item => item * 2)
let nums = [1, 2, 3]
nums.reduce((prev, current) => {
return prev + current
})
// 6
let nums = [1, 2, 3, 4]
nums.filter((num) => {
return num % 2 === 0
})
// [2, 4]
let nums = [1, 2, 3, 4]
function evenFilter(num) {
return num % 2 === 0
}
nums.filter(evenFilter)
const number = 42
number = 24
// Error! Number is immutable.
const person = {
name: 'Max',
}
person.name = 'Carl'
// will work
const person = {
name: 'Max',
}
let person2 = person
person2.name = 'Carl'
console.log(person.name) // Carl
const person = {
name: 'Max',
}
Object.freeze(person)
let person2 = person
person2.name = 'Carl'
console.log(person.name) // Max
const person = {
name: 'Max',
}
Object.freeze(person)
person.name = 'Carl'