rbi-learning / Today-I-Learned

1 stars 0 forks source link

10/19 Week 2 Day 1: Intro to JavaScript #182

Open ajlee12 opened 3 years ago

ajlee12 commented 3 years ago

Review

RPS WITH VBA

VBA Function

We wrote the Get_Computer_Move() function so that we can reuse functionalities within somewhere else.

Subprocedure DisplayResults

Once we find values for HumanMove, ComputerMove, and Outcome, this procedure knows how to display the result.

MORNING EXERCISE (TimBits with JS)

Parameters

Anything inside the parentheses after the function is called a parameter.

Pseudo Code

Get into the habit of pseudo-coding!

Arrays in JavaScript

For loop:

.push():

== vs. ===

== means "loosely equal to".

Intro to Programming

It's the process of creating a set of instructions that tell a computer how to do things.

You already learned some programming when learning VBA!

Why learn programming?

Some Info about JavaScript

JavaScript can run on the frontend (e.g. browsers) and the backend (e.g. servers).

It's flexible, non-blocking, and great for I/O applications.

How to be an effective programmer?

Approach to Problem Solving

  1. Define success conditions
    • What is the working state of this?
  2. Define / explore key phrases
    • The prompt probably contains all the info you need.
  3. Create action items for key phrases
  4. Reevaluate success conditions
  5. Create strategy from actions

Strategy Cheatsheet

strat cheatsheet

"Greed" Dice Game Exercise

// Outside the function: console.log(greed([2, 3, 2, 6, 4]));

// We should see: { '2': 2, '3': 1, '6': 1, '4': 1 }


- Iterate over the `dieCountTracker` object and get the scores.
  - Check [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) for what `Object.keys()` does.
```JS
Object.keys(dieCountTracker).forEach((die) => {
  // If we have more than 3 of a number, we need to score the triplet value and any remaining single value.
  if (dieCountTracker[die] > 3) {
    // Add the triplet scores.
    total += possiblePoints[`${die}${die}${die}`];

    // After "using up" the triplet, check for the single scores and add them. 
    if (possiblePoints[die]) {
      // Note that we subtract 3 to get the remaining number of appearances.
      total += possiblePoints[die] * dieCountTracker[die] - 3;
    }
  } 
  // If a number appeared exactly 3 times, we only need to add the triplet score.
  else if (dieCountTracker[die] === 3) {
    total += possiblePoints[`${die}${die}${die}`];
  } 
  // Check for single scores.
  else if (possiblePoints[die]) {
    total += possiblePoints[die] * dieCountTracker[die];
  }
});

Afternoon Code-Along

Declaring variables/constants

Most of the time you'll use const to declare arrays and objects.

Note that when you use const, you can modify the contents of the array/object, but you cannot reassign a different array/object to it.

const myArray = [1, 2, 3];

myArray[2] = 10; // Ok. We're just changing the 3rd element from 3 to 10.

myArray = [4, 5, 6]; // Not ok! We can't reassign a completely different array to myArray. But if you used `let` to declare myArray, reassignment would be ok.

Don't declare a variable without the let or const keyword.

// Don't:
topSkill = 'javascript';

// Do:
let topSkill = 'javascript';

Note that you can declare a variable without a value using let:

let skillAchievement; // Ok

const someSkills; // Not OK with `const`

Adding a property to an object

Let's say we start with an empty object:

const aboutMe = {};

We can add a new property to aboutMe with the dot notation:

aboutMe.name = 'Samantha';

Now, if you print the aboutMe object, you'll see:

{ name: 'Samantha' }
// No longer empty!

Note that a property (aka. a key) needs to be accompanied by a value (in this case, the string 'Samantha').

Accessing an element in an array

Let's say we have this array with 5 string elements:

allSkills = ['Excel', 'VBA', 'JavaScript', 'SQL', 'Tableau'];

We can grab a value from it and make it a new property in the aboutMe object:

aboutMe.topSkill = allSkills[2];

Note that allSkills[2] evaluates to the string 'JavaScript'.

aboutMe will now be:

{ name: 'Samantha', topSkill: 'JavaScript' }

Using conditional statements

We want a descriptive skill achievement depending on what the top skill is.

// Declare a variable to hold the description.
let skillAchievement;

// Check what the top skill is within the aboutMe object.
if (aboutMe.topSkill === 'Excel' || aboutMe.topSkill === 'VBA') {
  skillAchievement = `You're a spreadsheet ninja!`;
} else if (aboutMe.topSkill === 'JavaScript') {
  skillAchievement = `You're a programming wizard!`;
} else {
  skillAchievement = `You're a data guru!`;
}

Now, given what we have in aboutMe, if you print skillAchievement to the console, you should get You're a programming wizard!.

For loop

*If you'd like to review the basics of a for loop, read this nice and brief tutorial.

Three steps in setting up a for loop:

  1. Initialization: declare a variable with an initial value. Only runs once.
  2. Conditional check: loop only runs if condition evaluates to true
  3. Step up: repeated after every iteration. Changes the variable's value.

Let's iterate over the allSkills array and print each element to the console.

for (let i = 0; i < allSkills.length; i += 1) {
  const currentSkill = allSkills[i];
  console.log(currentSkill);
}

IMPORTANT NOTE: length is not zero-based, but arrays are.

const allSkills = ['Excel', 'VBA', 'JavaScript', 'SQL', 'Tableau'];

allSkills.length; // 5
allSkills[5]; // undefined, because the last element resides at index = 4.
allSkills[4]; // 'Tableau'

Using bracket notations

The bracket notation allows us to use a variable's value---instead of a literal string, in the case of the dot notation---as a key for an object.

Let's say we want to use a value of an old object as the key of a new object.

// Old object:
const aboutMe = {
  name: 'Samantha',
  topSkill: 'JavaScript',
};

// Now we want to make a new object with a key that's the topSkill of the old object.
const newAboutMe = {};
newAboutMe[aboutMe.topSkill] = 'Skill level: 5';

// We'll see that the newAboutMe = { JavaScript: 'Skill level: 5' }
// Note that aboutMe.topSkill = 'JavaScript'.

Using Array.forEach method

The method works like a for loop but for arrays only. We can use it to iterate over all the elements of an array.

The .forEach method takes in a callback function as an argument.

const testArray = [1, 2, 3, 4];

// Note that we're supplying .forEach with an arrow function. 
// And the arrow function has an `element` parameter.
testArray.forEach((element) => {
  console.log(element);
});

Run the code above, and you should see the following printed to the console:

1
2
3
4