frontend web development zg

chrome develop tool -> application -> storage -> cookies

1
2
3
4
5
6
7
8
9
10
11
12
const image = document.querySelector('img');
image.setAttribute('src', 'https://....jpg');

const htmlBody = document.querySelector('body');
const randomClickFunction = function(){
const colors = ['#002834', "#124567", "#123456", "red", "green", "yellow"];
const randomIndex = Math.floor(Math.random() * colors.length);
const randomColor = colors[randomIndex];
htmlBody.style.backgroundColor = randomColor;
}
randomClickFunction();
htmlBody.onclick = randomClickFunction;
1
2
3
4
5
6
function onClickEvent(){
const el = document.createElement('p');
el.innerText = 'Clicked the Button';
document.querySelector('.container').appendChild(el);
}
document.querySelector('button').onclick = onClickEvent;
1
2
3
4
5
6
clear();
console.log('Hello world!');
// comments here
/* asdf
asdf
*/

js

variable / data types

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const yourFirstVariable = "Learing to code";
const yourSecondVariable = 10;
const yourThirdVariable = {firstProperty: 'hello world'};
console.log(yourFirstVariable);
console.log(yourSecondVariable);
console.log(yourThirdVariable);

const variable5 = yourSecondVariable;
const variable6 = variable5 + yourSecondVariable;
const variable7 = (function (){
return "Hello, my name is ";
})();
console.log(variable7);

let anotherVariable;
anotherVariable = 20;
console.log(anotherVariable);

1
2
var myVariable = 10;
var myVariable = 20;
1
2
3
4
let counter = 0;
counter = counter + 1;
counter++;
console.log(counter);
1
const TAX_RATE = 0.08;

Use camelCase when naming objects, functions, and instances
Use PascalCase only when naming constructors or classes.


1
2
3
4
5
6
7
const variable1 = 10;
const variable2 = "some value";
const variable3 = false;

console.log(typeof variable1); //number
console.log(typeof variable2); //string
console.log(typeof variable3); //boolean
1
2
3
4
5
6
7
8
const number1 = '10';
const number2 = 20;
console.log(typeof number1);
console.log(typeof number2);
number3 = number1 + number2;
number4 = Number(number1) + number2;
console.log(number3); //1020
console.log(number4); //30

string

1
2
3
4
//perfered
const stringValue = 'hello world';
//not perfered
const anotherStringValue = "hello world";

array

1
2
3
4
5
const firstArray = [10, 20, 30];
const secondArray = [10, 'a string', {prop: 'asdfl'}, [1, 2]];
console.log(firstArray[0]);
console.log(secondArray[3][1]);

object

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const objectVariable = {
prop1: 20,
prop2: 50,
}
console.log(objectVariable.prop1);
console.log(objectVariable['prop1']);

const nestedObject = {
layer1: {
layer2: 30
}
}

console.log(nestedObject.layer1.layer2);
1
2
3
4
const functionContainerVariable = function(){
return 20;
}
functionContainerVariable();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
let myBoolean = true;
let myString = 'hello world';
let firstNumber = 20;
let secondNumber = 40;
secondNumber = 80;
let myArray = [myBoolean, myString];
let myObject = {
firstProperty: myArray,
sumProperty: firstNumber + secondNumber
}
console.log(myObject);
console.log(myObject.sumProperty); // 100
console.log(myObject.firstProperty[1]); // hello world


myBoolean = false;
myString = 'hello jack';
firstNumber = 30;
secondNumber = 50;
console.log(myObject);
console.log(myObject.sumProperty); // 100
console.log(myObject.firstProperty[1]); // hello world
myArray = [myBoolean, myString];
myObject = {
firstProperty: myArray,
sumProperty: firstNumber + secondNumber
}
console.log(myObject);
console.log(myObject.sumProperty); // 80
console.log(myObject.firstProperty[1]); // hello jack

operator

arithmetic

+ - * / % ** ++ --

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
20 + 50;
50 - 20;
50 / 20; // 2.5
2 * 3;
100 % 77; // remainder 23

let startingNumber = 0;
startingNumber++;
console.log(startingNumber); // 1
startingNumber--;
console.log(startingNumber); // 0

// assignment operators

// not prefered
let x = 10;
x = x - 5;
x -= 5;
console.log(x); // 0

const result2 = () => {
return 20;
}
const result3 = (() => {
return 20;
})();
console.log(result2);
console.log(result3);


// compare
// === == !== !=
// === !== type and value

const result = 20 > 18;
console.log(result); // true


const stringValue = '20';
const numberValue = 20;
stringValue == numberValue; // true
stringValue === numberValue; // false
Number(stringValue) === numberValue // true

"a string" === "a string"; // true

const myObj = {
property1: 'some value',
property2: 20
}
const anotherObj = {
property1: 'some value',
property2: 20
}
const myArray = [1, 2, 3, 4, 5];
const anotherArray = [1, 2, 3, 4, 5];
console.log(myObj === anotherObj); // false
console.log(myArray === anotherArray); // false

// ? :

const result0 = 20 === 20 ? "values match" : "values do not match";
console.log(result0); // "values match"

let resultVariable;
if(20 === 20){
resultVariable = "values match";
} else {
resultVariable = "values do not match";
}

// logical && || !

true && false; // false
true || false; // true
!true // false

const isUserLoggedIn = true;
const doesUserHavePermissions = false;
const canUserPerformAction = isUserLoggedIn && doesUserHavePermissions;

// combination

const result1 = !(((40 / 20) === 2 && true) || ('yes' === 'no')); // false

const step1 = 40 / 20; // 2
const step2 = step1 === 2; // true
const step3 = step2 && true;
const step4 = 'yes' === 'no'; // false
const step5 = step3 || step4;
const step6 = !step5;

console.log(step6); // false

function condition loops

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
if ('some string' === 'another string'){
console.log('the strings are equal');
} else {
console.log('the strings are not equal');
}

// 3 examples

const firstNumber = 20;
const secondNumber = 10;
const jsExpression = firstNumber < secondNumber; // false

if (jsExpression) {
console.log('this expression is true');
}

// this expression is false
if (jsExpression) {
console.log('this expression is true');
} else {
console.log('this expression is false');
}

// this expression is false and the firstNmumber is greater than 0
if (jsExpression) {
console.log('this expression is true');
} else if (firstNumber > 0) {
console.log('this expression is false and the firstNmumber is greater than 0');
} else {
console.log('this expression is false and the firstNmumber is 0 or less');
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

// switches

const colors = ['orange', 'green', 'yellow', 'purple', 'blue'];

const randomIndex = Math.floor(Math.random() * colors.length);

const randomColor = colors[randomIndex];

if (randomColor === 'orange') {
console.log('the color is orange');
} else if (randomColor === 'green') {
console.log('the color is green');
} else if (randomColor === 'yellow') {
console.log('the color is yellow');
} else if (randomColor === 'purple') {
console.log('the color is purple');
} else if (randomColor === 'blue') {
console.log('the color is blue');
} else {
console.log('the color is not found');
}

//swith case statement

switch (randomColor) {
case 'orange':
console.log('the color is orange');
break;
case 'green':
console.log('the color is green');
break;
case 'yellow':
console.log('the color is yellow');
break;
case 'purple':
console.log('the color is purple');
break;
case 'blue':
console.log('the color is blue');
break;
default:
console.log('the color is not found');
break;
}

loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// loop


const blogPosts = [
{
title: 'what is javascript?',
author: 'Zach Goll',
publishDate: 'Dec 20, 2020',
content: 'some post content here'
},
{
title: 'How do Array work?',
author: 'Zach Goll',
publishDate: 'Dec 18, 2021',
content: 'some post content here'
},
{
title: 'How long does it take to learn coding?',
author: 'Zach Goll',
publishDate: 'Dec 20, 2020',
content: 'some post content here'
}
];

for (let index = 0; index < blogPosts.length; index++) {
const postTitle = blogPosts[index].title;
const postAuthor = blogPosts[index].author;
const postPublishDate = blogPosts[index].publishDate;
const postContent = blogPosts[index].content;
console.log(postTitle);
console.log(postAuthor);
console.log(postPublishDate);
console.log(postContent);

}


for (let i = 0; i < 10; i++) {
console.log(i);
}

const arr = ['asdfqwef', 'asdfqwreo', 'asdfqwre', 20, 30, 40, 50];
for (let index = 0; index < arr.length; index++) {
if (typeof arr[index] === 'number') {
console.log(arr[index]);
}
}

function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
function myFunction(){
console.log('hello world, this is my first function');
}

myFunction();

(function anotherFunction(){
console.log('hello');
})();


//parmeters
function myFunction1(someNumber, someString, param3) {
console.log(someNumber);
console.log(someString);
console.log(param3);
}
//
myFunction1(20, 'a string', 'asdf');

//scope

// function variable
const anotherFunction1 = function () {
console.log('another thing');
}

// arrow function
// used in callback
const arrowFunction = () => {
console.log('i am an arrow function');
}
arrowFunction();

// function return
function returnFunction(){
console.log('some action');
return 20;
}
const result = returnFunction();
console.log(result);

// after return statement, the function finished
const myNumber = 20;
let myFunction2 = () => {
if(myNumber < 15){
return 'return early';
}
return 40;
}
myFunction2();

// object and function
function myFunction3(){
console.log('some function action');
return 20;
}
myFunction3();
const aliasVariable = myFunction3;
aliasVariable();
const myObj = {
prop1: 50,
prop2: myFunction3
}
myObj.prop2();

// buildin function

const myString = 'zach';
myString.replace('h', 'k');
console.log(myString);
const myName = myString.replace('h', 'k');
console.log(myName);

// string methods
let str = 'hello world';
const result1 = str.toUpperCase().split(' ');
result1.indexOf('WORLD'); // 1

practice

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195

// Complete the solution so that it reverses the string passed into it.
function solution(str){
return str.split('').reverse().join('');
}

//Return the number (count) of vowels in the given string.
//We will consider a, e, i, o, u as vowels
//The input string will only consist of lower case letters and/or spaces.

function getCount(str) {
let result = 0;
const vowels = ['a', 'e', 'i', 'o', 'u'];
for(let i =0; i < vowels.length; i++){
result += str.split(vowels[i]).length-1;
}
return result;
}

function getCount1(str) {
var vowelsCount = 0;
var vowels = ["a","e","i","o","u"];
for(var i = 0;i < str.length;i++){
for(var j=0;j<vowels.length;j++){
if(str[i] === vowels[j]){
vowelsCount++;
}
}
}

return vowelsCount;
}

// Given an array of integers your solution should find the smallest integer.the supplied array will not be empty.

class SmallestIntegerFinder {
findSmallestInt(args) {
let result = args[0];
for(let i = 1; i < args.length; i++){
if(result > args[i]){
result = args[i];
}
}
return result;
}
}

//Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0.
var summation = function (num) {
let sum = 0;
for(let i = num; i > 0; i--){
sum += i;
}
return sum;
}

//The Math.floor() method rounds a number DOWN to the nearest integer.


// Rock Paper Scissors
const rps = (p1, p2) => {
if (p1 === p2) {
return 'Draw!'
} else if((p1 === 'scissors' && p2 === 'paper') || (p1 === 'paper' && p2 === 'rock') || (p1 === 'rock' && p2 === 'scissors')) {
return "Player 1 won!";
} else {
return "Player 2 won!";
}
};

//create a function that removes the first and last characters of a string. You're given one parameter, the original string. You don't have to worry about strings with less than two characters.

function removeChar(str){
let result = '';
for (let index = 1; index < str.length - 1; index++) {
result += str[index];
}
return result;
};

function removeChar(str){
return str.substring(1, str.length-1);
};

function removeChar(str) {
return str.slice(1, -1);
}

//You get an array of numbers, return the sum of all of the positives ones.
//Example [1,-4,7,12] => 1 + 7 + 12 = 20
function positiveSum(arr) {
let sum = 0;
for (let num of arr) {
if(num >= 0) {
sum += num;
}
}
return sum;
}

//Your task is to create a function that does four basic mathematical operations.
//The function should take three arguments - operation(string/char), value1(number), value2(number).
//The function should return result of numbers after applying the chosen operation.

function basicOp(operation, value1, value2){
switch (operation) {
case '+':
return value1 + value2;
break;
case '-':
return value1 - value2;
break;
case '*':
return value1 * value2;
break;
case '/':
return value1 / value2;
break;
}
}

function basicOp(operation, value1, value2)
{
var cases = {
'+': value1 + value2,
'-': value1 - value2,
'*': value1 * value2,
'/': value1 / value2
};
return cases[operation]
}


eval(value1+operation+value2)
//Write a function to split a string and convert it into an array of words.
function stringToArray(string){
return string.split(' ');
}

//Write a function that removes the spaces from the string, then return the resultant string.
let removedSpacesText = originalText.split(" ").join("");

let originalText = "Geeks for Geeks Portal";

let removedSpacesText1 = originalText.replace(/ /g, "");

//

function maps(x){
return x.map(arrItem => arrItem * 2);
}

function maps(x){
//return x.map(el => el * 2);
let arr = [];
for(let i = 0; i < x.length; i++){
arr.push(x[i] * 2);
}
return arr;
}

//get the sum of two arrays... Actually the sum of all their elements.
function arrayPlusArray(arr1, arr2) {
let arr = [...arr1, ...arr2];
return arr.reduce((a, b) => a + b);
}

//The first century spans from the year 1 up to and including the year 100, the second century - from the year 101 up to and including the year 200, etc.
function century(year) {
return Math.ceil(year/100); //using ceiling method to round up to nearest century (100)
}

//I have a cat and a dog.

//I got them at the same time as kitten/puppy. That was humanYears years ago.

//Return their respective ages now as [humanYears,catYears,dogYears]
var humanYearsCatYearsDogYears = function(humanYears) {
let catYears = 0;
let dogYears = 0;
if(humanYears >= 1) {
catYears += 15;
dogYears += 15;
}
if(humanYears >= 2) {
catYears += 9;
dogYears += 9;
}
if(humanYears >= 3) {
catYears += (humanYears-2)*4
dogYears += (humanYears-2)*5
}

return [humanYears, catYears, dogYears];
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Our football team has finished the championship.

// Our team's match results are recorded in a collection of strings. Each match is represented by a string in the format "x:y", where x is our team's score and y is our opponents score.

// For example: ["3:1", "2:2", "0:1", ...]

// Points are awarded for each match as follows:

// if x > y: 3 points (win)
// if x < y: 0 points (loss)
// if x = y: 1 point (tie)
// We need to write a function that takes this collection and returns the number of points our team (x) got in the championship by the rules given above.


function points(games) {
function getPoints(x, y){
if (x === y) {
return 1;
}
else if (x > y) {
return 3;
}
else {
return 0;
}
}
let totalScores = 0;
for(let scores of games){
const arr = scores.split(':');
totalScores += getPoints(arr[0], arr[1]);

}
return totalScores;
}

points(["1:0","2:0","3:0","4:0","2:1","3:1","4:1","3:2","4:2","4:3"]);

buildin object

string methods

Some of the most-used operations on strings are to check their length, to build and concatenate them using the + and += string operators, checking for the existence or location of substrings with the indexOf() method, or extracting substrings with the substring() method.

replaceAll(pattern, replacement)

returns a new string with all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. The original string is left unchanged.

If pattern is a regex, then it must have the global (g) flag set, or a TypeError is thrown.

1
2
3
4
5
6
7
8
9
const paragraph = "I think Ruth's dog is cuter than your dog!";

console.log(paragraph.replaceAll('dog', 'monkey'));
// Expected output: "I think Ruth's monkey is cuter than your monkey!"

// Global flag required when calling replaceAll with regex
const regex = /Dog/gi;
console.log(paragraph.replaceAll(regex, 'ferret'));
// Expected output: "I think Ruth's ferret is cuter than your ferret!"

toUpperCase()

The toUpperCase() method of String values returns this string converted to uppercase.

trim()

The trim() method of String values removes whitespace from both ends of this string and returns a new string, without modifying the original string.

To return a new string with whitespace trimmed from just one end, use trimStart() or trimEnd().

1
2
3
4
5
6
7
const greeting = '   Hello world!   ';

console.log(greeting);
// Expected output: " Hello world! ";

console.log(greeting.trim());
// Expected output: "Hello world!";

substring(indexStart)
substring(indexStart, indexEnd)

returns the part of this string from the start index up to and excluding the end index, or to the end of the string if no end index is supplied.

1
2
3
4
5
6
7
const str = 'Mozilla';

console.log(str.substring(1, 3));
// Expected output: "oz"

console.log(str.substring(2));
// Expected output: "zilla"

match(regexp)

retrieves the result of matching this string against a regular expression.

1
2
3
4
5
6
const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
const regex = /[A-Z]/g;
const found = paragraph.match(regex);

console.log(found);
// Expected output: Array ["T", "I"]

array

push() pop() shift() unshift()

pop()
removes the last element from an array and returns that element. This method changes the length of the array.

1
2
3
4
5
6
7
const myFish = ["angel", "clown", "mandarin", "sturgeon"];

const popped = myFish.pop();

console.log(myFish); // ['angel', 'clown', 'mandarin' ]

console.log(popped); // 'sturgeon'

shift()

removes the first element from an array and returns that removed element. This method changes the length of the array.

1
2
3
4
push()
push(element1)
push(element1, element2)
push(element1, element2, /* …, */ elementN)

adds the specified elements to the end of an array and returns the new length of the array.

1
2
3
4
5
6
7
8
9
10
11
12
const animals = ['pigs', 'goats', 'sheep'];

const count = animals.push('cows');
console.log(count);
// Expected output: 4
console.log(animals);
// Expected output: Array ["pigs", "goats", "sheep", "cows"]

animals.push('chickens', 'cats', 'dogs');
console.log(animals);
// Expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]


unshift

adds the specified elements to the beginning of an array and returns the new length of the array.

1
2
3
4
5
6
7
const array1 = [1, 2, 3];

console.log(array1.unshift(4, 5));
// Expected output: 5

console.log(array1);
// Expected output: Array [4, 5, 1, 2, 3]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item1)
splice(start, deleteCount, item1, item2)
splice(start, deleteCount, item1, item2, /* …, */ itemN)```

changes the contents of an array by removing or replacing existing elements and/or adding new elements in place

```js
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// Inserts at index 1
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May');
// Replaces 1 element at index 4
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "May"]

slice()
slice(start)
slice(start, end)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// Expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// Expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// Expected output: Array ["bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// Expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// Expected output: Array ["camel", "duck"]

console.log(animals.slice());
// Expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

indexOf(searchElement)
indexOf(searchElement, fromIndex)

returns the first index at which a given element can be found in the array, or -1 if it is not present.

1
2
3
4
5
6
7
8
9
10
11
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// Expected output: 1

// Start from index 2
console.log(beasts.indexOf('bison', 2));
// Expected output: 4

console.log(beasts.indexOf('giraffe'));
// Expected output: -1

findIndex(callbackFn)

returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.

A function to execute for each element in the array. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:

element
The current element being processed in the array.

index
The index of the current element being processed in the array.

array
The array findIndex() was called upon.

1
2
3
4
5
6
const array1 = [5, 12, 8, 130, 44];

const isLargeNumber = (element) => element > 13;

console.log(array1.findIndex(isLargeNumber));
// Expected output: 3

includes(searchElement)

determines whether an array includes a certain value among its entries, returning true or false as appropriate.

1
2
3
4
5
6
7
8
9
10
11
12
const array1 = [1, 2, 3];

console.log(array1.includes(2));
// Expected output: true

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// Expected output: true

console.log(pets.includes('at'));
// Expected output: false

map(callbackFn)

creates a new array populated with the results of calling a provided function on every element in the calling array.

A function to execute for each element in the array. Its return value is added as a single element in the new array

1
2
3
4
5
6
7
const array1 = [1, 4, 9, 16];

// Pass a function to map
const map1 = array1.map((x) => x * 2);

console.log(map1);
// Expected output: Array [2, 8, 18, 32]

forEach(callbackFn)
executes a provided function once for each array element.
callback function Its return value is discarded.

1
2
3
4
5
6
7
const array1 = ['a', 'b', 'c'];

array1.forEach((element) => console.log(element));

// Expected output: "a"
// Expected output: "b"
// Expected output: "c"

filter(callbackFn)

creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.

callbackFn
A function to execute for each element in the array. It should return a truthy value to keep the element in the resulting array, and a falsy value otherwise.

1
2
3
4
5
6
const words = ['spray', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter((word) => word.length > 6);

console.log(result);
// Expected output: Array ["exuberant", "destruction", "present"]

reduce(callbackFn)
reduce(callbackFn, initialValue)

callbackFn
Its return value becomes the value of the accumulator parameter on the next invocation of callbackFn.
For the last invocation, the return value becomes the return value of reduce().

accumulator
The value resulting from the previous call to callbackFn. On the first call, its value is initialValue if the latter is specified; otherwise its value is array[0].

currentValue
The value of the current element. On the first call, its value is array[0] if initialValue is specified; otherwise its value is array[1].

currentIndex
The index position of currentValue in the array. On the first call, its value is 0 if initialValue is specified, otherwise 1.

1
2
3
4
5
6
7
8
9
10
11
const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => accumulator + currentValue,
initialValue,
);

console.log(sumWithInitial);
// Expected output: 10

join()
join(separator)

creates and returns a new string by concatenating all of the elements in this array, separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

1
2
3
4
5
6
7
8
9
10
const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// Expected output: "Fire,Air,Water"

console.log(elements.join(''));
// Expected output: "FireAirWater"

console.log(elements.join('-'));
// Expected output: "Fire-Air-Water"

includes(searchElement)
includes(searchElement, fromIndex)

determines whether an array includes a certain value among its entries, returning true or false as appropriate.

1
2
3
4
5
6
7
8
9
10
11
12
const array1 = [1, 2, 3];

console.log(array1.includes(2));
// Expected output: true

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// Expected output: true

console.log(pets.includes('at'));
// Expected output: false

callback functions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function myCallback(someNumber){
return someNumber*2;
}

function mainFunction(randomNumber, shouldCall, callback) {
let result = randomNumber;
if(shouldCall){
result = callback(randomNumber);
}
return result;
}

mainFunction(20, true, myCallback);
mainFunction(20, true, function (num) {
return num * 2;
})
mainFunction(20, true, (num) => {num * 2});
mainFunction(20, true, num => num * 2);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

const array1 = [1, 4, 9, 16];
// Pass a function to map
const map1 = array1.map((x) => x * 2);
console.log(map1);
// Expected output: Array [2, 8, 18, 32]

const myArray = [2, 4, 6, 8];
function myCustomMapOperationCallbak(itemFromArray) {
return itemFromArray * 2;
}
const newArray = myArray.map(myCustomMapOperationCallbak);

// example 3

const strArray = ['hello', 'world', 'my', 'name', 'is', 'zach'];
const strArray1 = strArray.map(itemFromArray => itemFromArray[0]);
console.log(strArray1);

primary

1
2
3
4
const string1 = new String('Hello, world!');
const string2 = 'Hello, world!';
console.log(string1 === string2); //false
console.log(string1 == string2); // true
1
2
3
4
5
6
7
8
9
const strPrim = "foo"; // A literal is a string primitive
const strPrim2 = String(1); // Coerced into the string primitive "1"
const strPrim3 = String(true); // Coerced into the string primitive "true"
const strObj = new String(strPrim); // String with new returns a string wrapper object.

console.log(typeof strPrim); // "string"
console.log(typeof strPrim2); // "string"
console.log(typeof strPrim3); // "string"
console.log(typeof strObj); // "object"

Date

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//A JavaScript date is fundamentally specified as the time in milliseconds that has elapsed since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC (equivalent to the UNIX epoch). This timestamp is timezone-agnostic and uniquely defines an instant in history.

const myDate = new Date();
// new Date()
// new Date(value)
// new Date(dateString)
// new Date(dateObject)

// new Date(year, monthIndex)

//monthIndex Integer value representing the month, beginning with 0 for January to 11 for December.
// new Date(year, monthIndex, day)
// new Date(year, monthIndex, day, hours)
// new Date(year, monthIndex, day, hours, minutes)
// new Date(year, monthIndex, day, hours, minutes, seconds)
// new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds)

// Date()

const today = new Date();
const birthday1 = new Date("December 17, 1995 03:24:00"); // DISCOURAGED: may not work in all runtimes
const birthday2 = new Date("1995-12-17T03:24:00"); // This is standardized and will work reliably
const birthday3 = new Date(1995, 11, 17); // the month is 0-indexed
const birthday4 = new Date(1995, 11, 17, 3, 24, 0);
const birthday5 = new Date(628021800000); // passing epoch timestamp

const event = new Date('05 October 2011 14:48 UTC');
console.log(event.toString());
// Expected output: "Wed Oct 05 2011 16:48:00 GMT+0200 (CEST)"
// Note: your timezone may vary

console.log(event.toISOString());
// Expected output: "2011-10-05T14:48:00.000Z"

regexp

1
2
3
4
5
const re = /ab+c/i; // literal notation
// OR
const re = new RegExp("ab+c", "i"); // constructor with string pattern as first argument
// OR
const re = new RegExp(/ab+c/, "i"); // constructor with regular expression literal as first argument

g flag

1
2
3
4
5
6
7
8
9
10
const regex = /foo/g;
console.log(regex.global); // true

const str = "fooexamplefoo";
const str1 = str.replace(regex, "");
console.log(str1); // example

const regex1 = /foo/;
const str2 = str.replace(regex1, "");
console.log(str2); // examplefoo

test()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const str = 'table football';

const regex = new RegExp('foo*');
const globalRegex = new RegExp('foo*', 'g');

console.log(regex.test(str));
// Expected output: true

console.log(globalRegex.lastIndex);
// Expected output: 0

console.log(globalRegex.test(str));
// Expected output: true

console.log(globalRegex.lastIndex);
// Expected output: 9

console.log(globalRegex.test(str));
// Expected output: false

regexp[Symbol.replace](str, replacement)

1
2
3
4
const re = /-/g;
const str = "2016-01-01";
const newstr = re[Symbol.replace](str, ".");
console.log(newstr); // 2016.01.01

Math

1
2
3
4
5
6
7
8
9
10
11
Math.PI;
Math.E;
Math.abs(-20);
Math.ceil(Math.PI);
Math.floor(Math.PI);
Math.round(Math.PI);
Math.min(1, 2, 3, 4); // 1
Math.max(1, 2, 3, 4); // 4
Math.random(); // 0 -- 1
const arr1 = [1, 2, 3, 4];
const randItem = arr1[Math.floor(Math.random() * arr1.length)];

exercise

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
//subtracts one list from another and returns the result.

function arrayDiff(a, b) {
return a.filter(aItem => {
let result = true;
b.forEach(bItem => {
if(bItem === aItem){
result = false;
}
});

return result;
});
}
arrayDiff([1, 2, 3], [1, 2]);


// best practices
function array_diff(a, b) {
return a.filter(e => !b.includes(e));
}

//You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens with a Walk Generating App on their phones -- everytime you press the button it sends you an array of one-letter strings representing directions to walk (eg. ['n', 's', 'w', 'e']). You always walk only a single block for each letter (direction) and you know it takes you one minute to traverse one city block, so create a function that will return true if the walk the app gives you will take you exactly ten minutes (you don't want to be early or late!) and will, of course, return you to your starting point. Return false otherwise.

function isValidWalk(walk) {
const directionArray = ['n', 's', 'w', 'e'];
const directionNumArray = directionArray.map(item => walk.filter((v) => (v === item)).length);
return (directionNumArray[0] === directionNumArray[1]) && (directionNumArray[2] === directionNumArray[3]) && (walk.length === 10);

}

function isValidWalk(walk) {
var dx = 0
var dy = 0
var dt = walk.length

for (var i = 0; i < walk.length; i++) {
switch (walk[i]) {
case 'n': dy--; break
case 's': dy++; break
case 'w': dx--; break
case 'e': dx++; break
}
}

return dt === 10 && dx === 0 && dy === 0
}

//Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.

//39 --> 3 (because 3*9 = 27, 2*7 = 14, 1*4 = 4 and 4 has only one digit)
//999 --> 4 (because 9*9*9 = 729, 7*2*9 = 126, 1*2*6 = 12, and finally 1*2 = 2)
//4 --> 0 (because 4 is already a one-digit number)


function multiplyDigits(num1){
if (num1 >= 10){
let firstDigits = Math.floor(num1 / 10); //98 9
return (num1 % 10) * multiplyDigits(firstDigits); // 1*7*8
} else {
return num1;
}
}

function count(num2, times=0) {
if(num2 < 10){
return times;
} else {
return count(multiplyDigits(num2), ++times); //987 7*8*9=504 0
}
}

function persistence(num) {
return count(num);

}

console.log(persistence(392));

//---

function persistence(num) {
var times = 0;

num = num.toString();

while (num.length > 1) {
times++;
num = num.split('').map(Number).reduce((a, b) => a * b).toString();
}

return times;
}

//count the total number of lowercase letters in a string.

function lowercaseCount(str){
return (str.match(/[a-z]/g) || []).length
}

//upcase some letter
function capitalize(s){
const str1 = s.split("").map((item, index) => {
if(index % 2 === 0){
return item.toUpperCase();
} else return item;
}).join('');
const str2 = s.split("").map((item, index) => {
if(index % 2 === 1){
return item.toUpperCase();
} else return item;
}).join('');
return [str1, str2];
};

// * url = "http://github.com/carbonfive/raygun" -> domain name = "github"
// * url = "http://www.zombie-bites.com" -> domain name = "zombie-bites"
// * url = "https://www.cnet.com" -> domain name = cnet"

function domainName(url){
url = url.replace("https://", '');
url = url.replace("http://", '');
url = url.replace("www.", '');
return url.split('.')[0];
};

domainName("http://google.com");