# Codecademy - JavaScript

Started with Codecademy Full stack engineer course to help understand web apps and dev better

{% hint style="info" %}
Useful Links

* Array methods

[https://www.digitalocean.com/community/tutorials/how-to-use-array-methods-in-javascript-iteration-methods](https://www.digitalocean.com/community/tutorials/how-to-use-array-methods-in-javascript-iteration-methods)

[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
{% endhint %}

## 1. JavaScript Syntaxes I

#### Voting Rights Validator by age

The most common minimum age to vote is 18. Write a function `canIVote()` that takes in a number, representing the person’s age, and returns the boolean `true` if they are 18 years old or older, and the boolean `false` if they are not.

```javascript
// Write your function here:
const canIVote = (number) => {
  if (number >= 18) {
    return true;
  } else {
    return false;
  }
}
console.log(canIVote(19)) // Should print true

```

### While loop

Return factorial of number

```javascript
function factorial (num){
  var result = num;
  if (num===1){
    return 1
  } else {
while(num>1){
    num--;
    result = result*num 
    } 
return result
  }
}

console.log(factorial(5))
```

### If else statements

Categorising People by age

```javascript
// Write your function here:
const lifePhase = ( age ) => {
  if (age>=0 && age<=3){
    return 'baby';
  } else if (age>3 && age < 13 ){
    return 'child';
  } else if (age>12 && age < 20 ){
    return 'teen';
  } else if (age>19 && age < 65 ){
    return 'adult';
  } else if (age>64 && age < 141 ){
    return 'senior citizen';
  } else {
    return 'This is not a valid age'
  }
}
console.log(lifePhase(5))
```

#### Task2:

Categorising student's grades by average grades

```javascript
const finalGrade = (midterm, final, homework) => {
    if ((midterm < 0 || midterm > 100) || (final < 0 || final > 100) || (homework < 0 || homework > 100)) {
        return 'You have entered an invalid grade.'
    }
    let average = (midterm + final + homework) / 3
    if (average < 60) {
        return 'F'
    }
    else if (average < 70) {
        return 'D'
    }
    else if (average < 80) {
        return 'C'
    }
    else if (average < 90) {
        return 'B'
    } else {
        return 'A'
    }
}
ja
```

### Taking inputs

Write a function, `reportingForDuty()`, that has two string parameters, `rank` and `lastName`, and returns a string in the following format: ‘rank lastName reporting for duty!’

```javascript
const reportingForDuty = (rank, lastName) => {
  return `${rank} ${lastName} reporting for duty!`;
}

console.log(reportingForDuty('Private', 'Fido')) 
```

### Arithmetic if else

Though an object’s mass remains consistent throughout the universe, weight is determined by the force of gravity on an object. Since different planets have different gravity, the same object would weigh different amounts on each of those planets! Cool, huh?

Write a function, `calculateWeight()`. It should:

* have two parameters: `earthWeight` and `planet`
* expect `earthWeight` to be a number
* expect `planet` to be a string
* return a number representing what that Earth-weight would equate to on the `planet` passed in.

{% hint style="success" %}
Use parseInt( ...) to convert to integer

String(...) to convert to string
{% endhint %}

Handle the following cases:\
`'Mercury'` weight = `earthWeight` \* 0.378\
`'Venus'` weight = `earthWeight` \* 0.907\
`'Mars'` weight = `earthWeight` \* 0.377\
`'Jupiter'` weight = `earthWeight` \* 2.36\
`'Saturn'` weight = `earthWeight` \* 0.916\
For all other inputs, return `'Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.'`

```javascript
const calculateWeight=(earthWeight, planet)=>{
  earthWeight = parseInt(earthWeight);
  planet = String(planet);
  if(planet == 'Mercury'){
    return earthWeight*0.378;
  } else if (planet == 'Venus'){
    return earthWeight*0.907;
  } else if (planet == 'Mars'){
    return earthWeight*0.377;
  }else if (planet =='Jupiter'){
    return earthWeight*2.36;
  } else if(planet =='Saturn'){
    return earthWeight*0.916;
  } else {
    return 'Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.';
  }
}

console.log(calculateWeight(100, 'Jupiter')) // Should print 236

```

### howold()

if else loops again

```javascript
/* 
Our solution is written as a function expression and uses string interpolation, but it would be equally acceptable to use a function declaration and/or string concatenation
*/

const howOld = (age, year) => {
// The following two lines make it so that our function always knows the current year.
    let dateToday = new Date();
    let thisYear = dateToday.getFullYear();
// It is totally ok if your function used the current year directly!
  
    const yearDifference = year - thisYear
    const newAge = age + yearDifference
    if (newAge > age) {
        return `You will be ${newAge} in the year ${year}`
    } else if (newAge < 0) {
        return `The year ${year} was ${-newAge} years before you were born`
    } else {
        return `You were ${newAge} in the year ${year}`
    }
}
```

emoticon practice

```javascript
const toEmoticon = (x) =>{
  switch (x){
    case 'shrug' :
    return '|_{"}_|';
    case 'smiley face' :
    return ':)';
    case 'frowny face' :
    return ':(';
    case 'winky face' :
    return ';)';
    case 'heart' :
    return '<3';
    default:
    return '|_(* ~ *)_|';
  }
}


// Uncomment the line below when you're ready to try out your function
console.log(toEmoticon("shrug")) 
```

### Project 1 : Number Guesser

\
Create a `compareGuesses()` function. This function will be called each round to determine which guess is closest to the target number.

This function:

* Has three parameters representing the user (human) guess, a computer guess, and the secret target number to be guessed.
* Determines which player (human or computer) wins based on which guess is closest to the target. If both players are tied, the human user should win.
* Return `true` if the human player wins, and `false` if the computer player wins.

```javascript
let humanScore = 0;
let computerScore = 0;
let currentRoundNumber = 1;

// Write your code below:
const generateTarget = () =>{
  return Math.floor(Math.random()*10);
}


const compareGuesses = (human,com,secretnum) =>{
let diffhuman = Math.abs(human - secretnum);
let diffcom = Math.abs(com - secretnum);
  if(diffhuman < diffcom ){
    return true;
  } else if (diffhuman == diffcom) {
    return true;
  } else {
    return false;
  }}

const updateScore = (i) =>{
  if (i == 'human'){
    humanScore +=1;
  } else if(i =='computer'){
    computerScore +=1;
  }
}

const advanceRound = () =>{
  currentRoundNumber +=1
}

```

![With HTML and CSS done](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2FG9sTIKMKgTqHH9mJ2x0I%2Fimage.png?alt=media\&token=c8b6ffc1-e492-414b-bdef-e1ddb7c63371)

### Capitalize Words in String

```javascript
function capitalizeASingleWord(word) {
  //console.log(word)
  if (word.match(' ')) {
    //console.log('Word value inside of if statement: ' + word);
    return null;
  }
  
  let firstLetter = word.charAt(0);
  const restOfWord = word.slice(1);
  
  firstLetter = firstLetter.toUpperCase();
  
  return firstLetter + restOfWord;
}

// Should return "Hey"
console.log("capitalizeASingleWord('hey') returns: " + capitalizeASingleWord('hey')); 

// Should return null
console.log("capitalizeASingleWord('hey ho') returns: " + capitalizeASingleWord('hey ho'));
```

## 2. JavaScript Syntaxes II

### Advanced Objects

* using built in object methods [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Object#Methods\_of\_the\_Object\_constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#Methods_of_the_Object_constructor)

[https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects)

{% hint style="info" %}
Object.assign() - takes original object + your additions

&#x20;Object.keys() - takes the keys&#x20;

Object.entries() -will also return an array, but the array will contain more arrays that have both the key and value of the properties in an object
{% endhint %}

```javascript
const robot = {
	model: 'SAL-1000',
  mobile: true,
  sentient: false,
  armor: 'Steel-plated',
  energyLevel: 75
};

// .keys takes the keys of the object, argument must be object name
const robotKeys = Object.keys(robot);

console.log(robotKeys);

//entries create an array with the keys and values of the objects, argument same as object name
const robotEntries = Object.entries(robot)

console.log(robotEntries);

// Declare newRobot below this line:
const newRobot = Object.assign({laserBlaster: true, voiceRecognition: true}, robot)

console.log(newRobot);
```

### Arrays Review:

* Arrays are lists that store data in JavaScript.
* Arrays are created with brackets `[]`.
* Each item inside of an array is at a numbered position, or index, starting at `0`.
* We can access one item in an array using its index, with syntax like: `myArray[0]`.
* We can also change an item in an array using its index, with syntax like `myArray[0] = 'new string'`;
* Arrays have a `length` property, which allows you to see how many items are in an array.
* Arrays have their own methods, including `.push()` and `.pop()`, which add and remove items from an array, respectively.
* Arrays have many methods that perform different tasks, such as `.slice()` and `.shift()`, you can find documentation at the [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) website.
* Some built-in methods are mutating, meaning the method will change the array, while others are not mutating. You can always check the documentation.
* Variables that contain arrays can be declared with `let` or `const`. Even when declared with `const`, arrays are still mutable. However, a variable declared with `const` cannot be reassigned.
* Arrays mutated inside of a function will keep that change even outside the function.
* Arrays can be nested inside other arrays.
* To access elements in nested arrays chain indices using bracket notation.

### Using JavaScript on the Console ( CTRL + SHIFT + J)

![Changing elements of a page](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2FFB9Y3FZk8UHy0cupQnVv%2Fimage.png?alt=media\&token=b438d5f7-b2ea-4886-b879-41066075ae4b)

{% embed url="https://developer.chrome.com/docs/devtools/console/javascript" %}

* Rather than typing `document.querySelector()` to select an element, you can type `$()`. This syntax is inspired by jQuery, but it's not actually jQuery. It's just an alias for `document.querySelector()`.
* `debug(function)` effectively sets a breakpoint on the first line of that function.
* `keys(object)` returns an array containing the keys of the specified object.

## 3. Node.js & its Global Objects

* &#x20;for writing server side JS code that runs in a computer itself instead of a browser
* is written in C, C++ and JavaScript, built on open-source V8 JS engine which powers chrome (JS browser)

#### Node Global Objects

Node provides access to several important global objects for use with Node program files. When writing a file that will run in a Node environment, these **variables** will be accessible in the global scope of your file.

* `module` is an object referring to the functionality that will be exported from a file. In Node, each file is treated as a module, including:
  1. [HTTP](https://nodejs.org/dist/latest/docs/api/http.html) and [HTTPS](https://nodejs.org/dist/latest/docs/api/https.html) for creating web servers.
  2. [File System](https://nodejs.org/dist/latest/docs/api/fs.html), [OS](https://nodejs.org/dist/latest/docs/api/os.html), and [Path](https://nodejs.org/dist/latest/docs/api/path.html) for interacting with the file system, operating system, and file/directory paths.
* `require()` is a function used to import modules from other files or Node packages.
* `process` is an object referencing to the actual computer [process](https://en.wikipedia.org/wiki/Process_\(computing\)) running a Node program and allows for access to command-line arguments and much more.

```javascript
const fs = require('fs');
 
fs.readFile('./script.js', function(error, data) {
  // error is null if no error occurred, but an Error object if it did
  if (error) {
   throw error;
  }
  // the file data will be passed into the callback if no error was thrown
  console.log(data);
});
```

In this example, we are using Node’s built-in `fs` module to read a _script.js_ file. The callback function is called after the file-reading operation is completed. If an error occurred, it will be passed in as `error` and thrown. If it doesn’t exist, the retrieved data from the file reading operation is logged to the console.

#### Running Node in Computer

Must be in same folder as the js script

```
node <name of file: for example scipt.js>
```

Node as a REPL (Read Eval Print Loop)

* run REPL by typing node and press enter
* interactive JavaScript environment

![](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2FglQB8ftLKhVlACbXrLTR%2Fimage.png?alt=media\&token=96bf5ace-f561-4b51-9b31-0fdac636ae1f)

#### Use .load to load JS files (existing) into the REPL

```
$ node
> .load ./script.js
var a = 'Node REPL is fun!';
 
> a
'Node REPL is fun!'
```

This ensures the variables are accessible in the REPL

* npm/yarn = package manager for Node
* replit = inbrowser IDE for projects
