backup - mikehov/Dating-app GitHub Wiki

Learning Javascript

Mike Hovenier | Tech-4

Data types

There are 7 types of Data:

  • Undefined: Its not been defined, the variable doesn't exist
  • Null: Its nothing, its declared but has no value yet.
  • Boolean: True or false
  • String: Text
  • Symbol: An immutable primitive value that is unique.
  • Number: Is a number
  • Object: Can store key value pairs

Variables

Variable allow you to store and manipulate data, its like a box with a label that you can fill with anything. There is var, let and const.

  • Var: Can be used in your whole program, Globalscope.
  • Let: Can only be used in the scope of where you declare that.
  • Let: Can only be used in the scope of where you declare that, but you can't change it value.

Example:

let myName; // Declaring
myName = 'Mike'; // Assignment

Assignment operators

There are different assign operators you can asign to a variable:

  • '+' Addition
  • '-' Subtraction
  • '*' Multiplication
  • '/' Division
  • '++' Increment
  • '--' Decrement
  • '%' Modulus (Division Remainder)
  • +=
  • == Is equal as.
  • != Isn't equal as.
  • && And
  • || Or

This how all of these operators work (there are more operators).

let a = 10 + 5;
console.log(a); // 15

let b = 10 - 5;
console.log(b); // 5

let c = 10 * 5;
console.log(c); // 50

let d = 10 / 5;
console.log(d); // 2

let e = 10;
e++;
console.log(e); // 11

let f = 10;
f--;
console.log(f); // 9

let g = 10;
g % 3; // How many times does 3 fit in 10, what's left over is the answer.
console.log(g); // 1

let h = 10;
h = h + 5; is the same as h += 5;
console.log(h); // 15

let i = 10;
i = i - 5; is the same as h -= 5;
console.log(i); // 5

let j = 10;
j = j * 5; is the same as j *= 5;
console.log(j); // 50

let k = 10;
k = k / 5; is the same as k /= 5;
console.log(k); // 2

Strings

You can write a string in multiple ways:

let myString = 'I dominate with throwing dwarves';

But if I wan't to quote the word "throwing" inside my string, you can use backslashes to ignore the next quote.

let myString = 'I dominate with \"throwing\" dwarves';

You can also put two strings together:

let middle = 'middle'
let myString = 'Im the start ' + middle + ' Im the end.';

console.log('myString')

or like this

let firstName = 'Mike ';
let lastName = 'Hovenier';
fullName = firstName + lastName;
console.log(fullName);

You can also see the length of the string by doing the following:

let firstName = 'Mike';
let firstNameLength;

firstNameLength = firstName.length;
console.log(firstNameLength); // 3

If you want the first letter of a string you use this:

let firstName = 'Mike';
let firstLetterName;

firstLetterName = firstName[0];
console.log(firstLetterName); // M

If you want the last letter of a string you use this:

let firstName = 'Mike';
let lastLetterName;

lastLetterName = firstName[firstName.length - 1];
console.log(lastLetterName); // e

Array

You can give a variable multiple values, that's called a array. The elements can be any data type, so a string, number or boolean for example.

let whoAmI = ["Mike", "Hovenier", 21];
console.log(whoAmI); // ["Mike", "Hovenier", 21];

You can also put arrays inside a array, thats called a "nested" array. So you can make like multiple array's in array's.

let whoAmI = ["Mike", "Hovenier", 21], ["David", "Storm", 24](/mikehov/Dating-app/wiki/"Mike",-"Hovenier",-21],-["David",-"Storm",-24);
console.log(whoAmI); // ["Mike", "Hovenier", 21], ["David", "Storm", 24]];

Array's also have indexs, so that means they count from 0. You can also change the value of that array like this.

let fullInfo = ["Mike", "Hovenier", 21]
let age = fullInfo[2] = 0;
console.log(fullInfo); // ["Mike", "Hovenier", 0];

But let's say you want to change the value of array inside a array, you can do that by the following:

let allNames = ["Mike", "Hovenier", 21], ["Melanie", "Brinkhaltes", 24], ["Rico", "Koerala", 22](/mikehov/Dating-app/wiki/"Mike",-"Hovenier",-21],-["Melanie",-"Brinkhaltes",-24],-["Rico",-"Koerala",-22);
let ageFromMelanie = allNames[1][2] = 25;
console.log(allNames); // ["Mike", "Hovenier", 21], ["Melanie", "Brinkhaltes", 25], ["Rico", "Koerala", 22](/mikehov/Dating-app/wiki/"Mike",-"Hovenier",-21],-["Melanie",-"Brinkhaltes",-25],-["Rico",-"Koerala",-22)
console.log(ageFromMelanie); // 25

You have a few different type of methods you can use:

  • Push: Adds a item to the array at the end of the array.
  • Pop: Removes the last item of the array.
  • Shift: Removes the first item of the array.
  • Unshift: Adds a item to the array at the start of the array.

Push item:

let allNames = ["Mike", "Melanie", "Rico"];
allNames.push("Slang");
console.log(allNames);

Pop item:

let allNames = ["Mike", "Melanie", "Rico", "Slang"];
allNames.pop();
console.log(allNames); // ["Mike", "Melanie", "Rico"]

Shift item:

let allNames = ["Mike", "Melanie", "Rico", "Slang"];
allNames.shift();
console.log(allNames); // ["Melanie", "Rico", ["Slang"]]

Unshift:

let allNames = ["Mike", "Melanie", "Rico", "Slang"];
allNames.unshift("Grat");
console.log(allNames); // ["Grat", "Mike", "Melanie", "Rico", "Slang"]

Functions

This is the basics of how a function works:

function thisIsAFunction() {
  console.log('Hello'); // Hello
}

thisIsAFunction(); // Calling the function

A function contains paramaters, () these things. Those parameters can act as placeholders if you put something inside them. Those parameters can lead to values. a and b are called the arguments.

function maths(a, b) {
  console.log(a - b);
}

maths(10, 5); // 5

You can store information in to the parameter of the function. So the first

function world(planet, country, city) {
  let answer = ""
  answer += "The planet " + planet + " the country " + country + " and the city " + city;
  return answer;
}
console.log(world("earth", "Netherlands", "Haarlem"));

Global scope:

Global scope means its acces almost anywhere in that document.

let myGlobal = 10;

function sam() {
 myGlobal = 20;
}

sam();
console.log(myGlobal); // 20

But because of there is no let given in the function by myGlobal the answer is 20. If you would give the myGlobal a let the answer will be 10.

Local scope

Local scope means its accessable only locally (for example inside a function).

function sam() {
 let myLocal = 10;
 myLocal = 20;
}

sam();
console.log(myLocal); // Error

It gives a error cause the var is locally placed, if you set the console inside the function, you will get 20 back.

The variable song gets returned by the function.

let song = "Just Like You";

function music() {
  let song = "Someone you loved"
  return song;
}

let song = "Just Like You";

console.log(music());  // Someone you loved

It will return "Someone you loved" cause the functions gets its value for the last time inside the function itself. return returns the final answer to the function.

But then see this example:

let number = 0;

function calculator() {
  number += 5;
}

console.log(calculator()); // undefined

The answer is undefined, because you are not returning the value to the function, so the function has no value.

Let's say we want to know how much water we need to drink if we are a wake each hour.

function waterADay() {
  let water = 2000;
  let hours = 24;
  let sleephours = 8;
  let daysAwake = hours - sleephours;
  drinkADay = water / daysAwake;
  return drinkADay;
}

console.log(waterADay() + 'ml'); // 125ml

You can also shorten this by doing this:

function waterADay(water, hours, sleephours) {
  return drinkADay = water / (hours - sleephours);
}

console.log(waterADay(2000, 24, 8) + 'ml'); // 125ml

If and Else inside functions

Functions can contain if, else if and else. See it as levels, if this condition is true, do this. If not (Else if) go to the next condition, if that one ain't true, go to the next condition and so on. If all of the conditions aren't true, then do else. But lately u only use if.

Example:

function amITrue(iDontKnowYet) {
  if (iDontKnowYet) {
    return 'Yes this is true';
  }
  return 'No its false';
}

console.log(amITrue(true)); // Yes this is true

Because inside the parameter of the parameter is true, the if statement will be true aswell. You could have done the same things with values, if you changed console.log(amITrue(true)); to console.log(amITrue(20));, you will also get the result true.

You can also make your if statement more intresting by more complex conditions.

function pointsCounter(place) {
  if (place == 1) {
    return 'You earned 10 points';
  }
  if (place == 2) {
    return 'You earned 5 points';
}
  return 'You earned no points';
}

console.log(pointsCounter(3)); // You earned no points

or

function pointsCounter(number) {
  if (number > 10) {
    return 'Greater than 10';
  }
  if (number > 5) {
    return 'Greater than 5';
}
  return 'Less or equal to 5';
}

console.log(pointsCounter(8)); // Greater than 5

You can also use double if statements, so you are checking with two conditions one conditions.

function pointsCounter(number) {
  if (number <= 20) {
     if (number >= 10)
       
    return 'Between 10 and 20';
  }
  if (number <= 10) {
     if (number >= 5)
       
    return 'Between 5 and 10';
  }
  return 'Less then 5';
}

console.log(pointsCounter(14)); // Between 10 and 20

But there is a shorter way to write this:

function pointsCounter(number) {
  if (number <= 20 && number >= 10 ) {
       
    return 'Between 10 and 20';
  }
  if (number <= 10 && number >= 5) {
       
    return 'Between 5 and 10';
  }
  return 'Less then 5';
}

console.log(pointsCounter(14)); // Between 10 and 20

You can also use ||, this symbol means or. So see the example.

function pointsCounter(number) {
  if (number >= 20 || number <= 10 ) {
       
    return 'You missed';
  }
  return 'You hit the middle';
}

console.log(pointsCounter(8)); // You missed

You can also write all this code with if else statements:

function pointsCounter(number) {
  if (number >= 20) {
    return '20 or more';
  } else if (number >= 10) {
  return '10 or more';
  } else {
    return 'Less then 10'
  }
}

console.log(pointsCounter(12)); // 10 or more

Instead typing all the values your own, you can also use a array that you have madet to pick from there.

let flagPositions = ['Alpha', 'Bravo', 'Charlie', 'Delta'];
function coordinates(x, y) {
  if (x * y >= 200) {
    return flagPositions[0];
  } else if (x * y >= 150) {
    return flagPositions[1];
  } else if (x * y >= 100) {
    return flagPositions[2];
  } else if (x * y >= 50) {
    return flagPositions[3];
  } else {
    return 'Your out of the map';
  }
}

console.log(coordinates(22, 4)); // Delta

Switch statement

You can also use a switch statement, this test the value. It looks like a if statement.

function position(x) {
  let answer = '';
  switch(x) {
    case 1:
      answer = 'Alpha';
      break;
    case 2:
      answer = 'Bravo';
      break;
    case 3:
      answer = 'Charlie';
      break;
  } 
  return answer;
}

console.log(position(2)); // Bravo

The break breaks the case so it can go to the next. You can also work with letters. If you change case 1: to case 'a': you can use "a" as a answer in the parameter. If the answer does not match with any of them. It returns an empty string, cause let answer = ''; has no value than. You can fix that by adding the line:

function position(x) {
  let answer = '';
  switch(x) {
    case 1:
      answer = 'Alpha';
      break;
    case 2:
      answer = 'Bravo';
      break;
    case 3:
      answer = 'Charlie';
      break;
    default:
      answer = 'Nothing';
      break;
  } 
  return answer;
}

console.log(position(12)); // Nothing

default is now the default, you can compare it to else. You can also combine multiple cases together, so they will give you the same answer.

function position(x) {
  let answer = '';
  switch(x) {
    case 1:
    case 2:
    case 3:
      answer = 'Alpha';
      break;
    case 4:
    case 5:
    case 6:
      answer = 'Bravo';
      break;
    case 7:
      answer = 'Charlie';
      break;
    default:
      answer = 'Nothing';
      break;
  } 
  return answer;
}

console.log(position(8)); // Nothing

Objects

Object is like a pile of information, an object has a property and a column. You can make from an variable a object like so:

  let animals = {
  'name': 'Sam',
  'legs': 6,
  'tails': 2,
  'friends': ['Kim', 'Doodle', 'Spencer']
}

let animalFriends = animals.friends;
console.log(animalFriends);

By using the dotnotation you can go inside a object. But let's say now your property is name of the animal, you need to type it differently cause of the spaces. So instead of let animalFriends = animals.name; use 'let animalFriends = animals[name of the animal];'. You can always still change the object value to whatever you want, by doing this animals.name = 'George';.

You can add properties to your object, by doing this:

let animals = {
  "name": "Sam",
  "legs": 6,
  "tails": 2,
  "friends": ["Kim", "Doodle", "Spencer"]
}

animals['bark'] = 'woof';

console.log(animals); // The whole object array off animals

If you can add, you also can delete, by deleting type following line delete animals.tails;.

You can put more objects inside a object by making the object an array.

let animals = [
  {
  'name': 'Sam',
  'legs': 6,
  'tails': 2,
  'friends': ['Kim', 'Doodle', 'Spencer']
  },
  {
  'name': 'Doodle',
  'legs': 4,
  'tails': 4,
  'friends': ['Sam']
  }
];

console.log(animals);

But lets say we want something from the second object, we can type the following let secondObject = animals[1].name;.

Loops

You have different kind of loops:

  • For loop
  • For-in loop
  • For-off loop (ES6 only)
  • While loop
  • Do-while loop

While loop

This loop will keep looping till its equal to 5, if not, it keeps looping.

let myArray = [];

let counter = 0;
while(counter < 5) {
  myArray.push(counter);
  counter++;
}

console.log(myArray); // [0, 1, 2, 3, 4];

Do While loop

Difference between a Do While loop and an While loop is that a while loop first checks the condition, if the conditions is true, it runs the rest of the code. A Do While loop will first run the code, then the condition. What's the difference? Let's the conditions is false, the While loop will do nothing, but the do while loop will run the code atleast once.

let whileArray = [];
let x = 10;

while (x < 10) {
  whileArray.push(x);
  x++;
}

console.log(x, whileArray); // 10 []

let doWhileArray = [];
let y = 10;

do {
  doWhileArray.push(y);
  y++;
} while (y < 10);

console.log(y, doWhileArray); // 11 [10]

For loop

A for loop you will probably use the most, you have three parts of a for loop, every ; kinda seperates them.

  • Initializing: let counter = 0;
  • Condition: counter < 5;
  • Expression: counter++;
let myArray = [];

for (let counter = 0; counter < 5; counter++) {
  myArray.push(counter);
}

console.log(myArray); // [0, 1, 2, 3, 4];

The myArray.push(counter); will push the answer to the array. If you want to plus two everytime you can do this:

let myArray = [];

for (let counter = 0; counter <= 10; counter += 2) {
  myArray.push(counter);
}

console.log(myArray); // [0, 2, 4, 6, 8, 10]

But if you want the length of the array.

let ourArray = [94, 43, 48, 20];
let totalValue = 0;

for (let x = 0; x < ourArray.length; x++) {
  totalValue += ourArray[x] * 2;
}

console.log(totalValue);

Tough

This is a tough exercise, lets say you want to fill in a name and a property, and you want the answer of the property. You a notification if the property or name does not exist.

let profiles = [
  {
  'firstName': 'Quinten',
  'lastname': 'Vlap',
  'age': '29'
  },
  {
  'firstName': 'Matt',
  'lastname': 'Malen',
  'age': '22'
  },
  {
  'firstName': 'Remco',
  'lastname': 'Bergwijn',
  'age': '23'
  }
];

function lookUpProfile(name, prop) {
  for (let x = 0; 0 < profiles.length; x++) {
    if(profiles[x].firstName === name) {
      return profiles[x][prop] || 'No such property';
    }
      
  }
  return 'Name not found'
}

let data = lookUpProfile('Quinten', 'age')
console.log(data);

Random

With Math.random() you get a random number between 0 and 1 but it can't be one.

function randomNumber() {
  
  return Math.random();
}

console.log(randomNumber()); // 0.489328239

But if you cant a number thats atleast between 0 and 100 with out decimals.

function randomNumber() {
  return Math.floor(Math.random() * 100 + 1);
}

console.log(randomNumber()); // 83

The + 1 at the end is for that the answer otherwise never can be 100, but now it never can be 0 either. floor means rounded down to beneath.

Weird If else statement

There is a weird way to write a if else statement.

function checkSign(number) {
  return number > 0 ? 'Positive' : number < 0 ? 'Negative' : 'Zero';
}

console.log(checkSign(0));

What this code does, its like a if statment. Only now the : are the statements, ? is adding the return to it.

Source

HTTP and Forms :: Eloquent JavaScript. (n.d.). Retrieved May 19, 2020, from https://eloquentjavascript.net/18_http.html