JavaScript Fundamentals - Part 2

Last Updated on: August 10, 2021 pm

JavaScript Fundamentals - Part 2

Activate Strict Mode

Strict mode creates visible errors in developer console, where in other situations without strict mode the code will fail silently.

Function Declaration vs. Expression

Declaration

1
2
3
function f1 (birthYear){
return 2021 - birthYear;
}

Can call the function before the it is defined.

Expression

1
2
3
const f2 = function (birthYear){
return 2021 - birthYear;
}

Cannot access the function before it is defined.

Arrow Function

For simple one-line function:

1
const f3 = birthYear => 2021 - birthYear;

For multi-line function:

1
2
3
4
5
const yearRetire = (birthYear, firstName) => {
const age = 2021 - birthYear;
const retire = 65 - age;
return `${firstName} retires on ${retire} years`;
}

Anatomy of A Function

Array Operations

Unshift

['Micheal', 'Steven'] —> ['John', 'Micheal', 'Steven']

1
friends.unshift('John')

push

['Micheal', 'Steven'] —> [ 'Micheal', 'Steven', 'John']

1
const newLength = friends.push('John')

Returns the length of the new Array.

pop & shift

pop - pop the last one
shift - pop the first one

indexOf

If exist - return the index
If not exist - return -1

includes

Strict Mode!!

return a boolean value whether the element exists in the array

Objects

1
console.log(`jonas has ${jonas.friends.length} and his best friend is ${jonas.friends[0]}`)

Object Methods

1
2
3
4
5
6
7
8
9
10
const jonas = {
birthYear: 1991,
friends: ['Micheal', 'Peter', 'Steven'],
calcAge: function () {
return 2021 - this.birthYear;
}
};

console.log(jonas.calcAge());
// this refers to the object that is calling the method