본문 바로가기

webdesign/JavaScript

javascript 101

JavaScript Full Course for Beginners

 

 

0:00:00 Introduction

0:01:24 Running JavaScript

0:04:23 Comment Your Code

0:05:56 Declare Variables

0:06:15 Storing Values with the Assignment Operator

0:11:31 Initializing Variables with the Assignment Operator

0:11:58 Uninitialized Variables

0:12:40 Case Sensitivity in Variables

0:14:05 Add Two Numbers

0:14:34 Subtract One Number from Another

0:14:52 Multiply Two Numbers

0:15:12 Dividing Numbers

0:15:30 Increment

0:15:58 Decrement

0:16:22 Decimal Numbers

0:16:48 Multiply Two Decimals

0:17:18 Divide Decimals

0:17:33 Finding a Remainder

0:18:22 Augmented Addition

0:19:22 Augmented Subtraction

0:20:18 Augmented Multiplication

0:20:51 Augmented Division

0:21:19 Declare String Variables

0:22:01 Escaping Literal Quotes

0:23:44 Quoting Strings with Single Quotes

0:25:18 Escape Sequences

0:26:46 Plus Operator

0:27:49 Plus Equals Operator

0:29:01 Constructing Strings with Variables

0:30:14 Appending Variables to Strings

0:31:11 Length of a String

0:32:01 Bracket Notation

0:33:27 Understand String Immutability

0:34:23 Find the Nth Character

0:34:51 Find the Last Character

0:35:48 Find the Nth-to-Last Character

0:36:28 Word Blanks

0:40:44 Arrays

0:41:43 Nest Arrays

0:42:33 Access Array Data

0:43:34 Modify Array Data

0:44:48 Access Multi-Dimensional Arrays

0:46:30 push()

0:47:29 pop()

0:48:33 shift()

0:49:23 unshift()

0:50:36 Shopping List

0:51:41 Write Reusable with Functions

0:53:41 Arguments

0:55:43 Global Scope

0:59:31 Local Scope

1:00:46 Global vs Local Scope in Functions

1:02:40 Return a Value from a Function

1:03:55 Undefined Value returned

1:04:52 Assignment with a Returned Value

1:05:52 Stand in Line

1:08:41 Boolean Values

1:09:24 If Statements

1:11:51 Equality Operator

1:13:18 Strict Equality Operator

1:14:43 Comparing different values

1:15:38 Inequality Operator

1:16:20 Strict Inequality Operator

1:17:05 Greater Than Operator

1:17:39 Greater Than Or Equal To Operator

1:18:09 Less Than Operator

1:18:44 Less Than Or Equal To Operator

1:19:17 And Operator

1:20:41 Or Operator

1:21:37 Else Statements

1:22:27 Else If Statements

1:23:30 Logical Order in If Else Statements

1:24:45 Chaining If Else Statements

1:27:45 Golf Code

1:32:15 Switch Statements

1:35:46 Default Option in Switch Statements

1:37:23 Identical Options in Switch Statements

1:39:20 Replacing If Else Chains with Switch

1:41:11 Returning Boolean Values from Functions

1:42:20 Return Early Pattern for Functions

1:43:38 Counting Cards

1:49:11 Build Objects

1:50:46 Dot Notation

1:51:33 Bracket Notation

1:52:47 Variables

1:53:34 Updating Object Properties

1:54:30 Add New Properties to Object

1:55:19 Delete Properties from Object

1:55:54 Objects for Lookups

1:57:43 Testing Objects for Properties

1:59:15 Manipulating Complex Objects

2:01:00 Nested Objects

2:01:53 Nested Arrays

2:03:06 Record Collection

2:10:15 While Loops

2:11:35 For Loops

2:13:56 Odd Numbers With a For Loop

2:15:28 Count Backwards With a For Loop

2:17:08 Iterate Through an Array with a For Loop

2:19:43 Nesting For Loops

2:22:45 Do...While Loops

2:24:12 Profile Lookup

2:28:18 Random Fractions

2:28:54 Random Whole Numbers

2:30:21 Random Whole Numbers within a Range

2:31:46 parseInt Function

2:32:36 parseInt Function with a Radix

2:33:29 Ternary Operator

2:34:57 Multiple Ternary Operators

2:36:57 var vs let

2:39:02 var vs let scopes

2:41:32 const Keyword

2:43:40 Mutate an Array Declared with const

2:44:52 Prevent Object Mutation

2:47:17 Arrow Functions

2:28:24 Arrow Functions with Parameters

2:49:27 Higher Order Arrow Functions

2:53:04 Default Parameters

2:54:00 Rest Operator

2:55:31 Spread Operator

2:57:18 Destructuring Assignment: Objects

3:00:18 Destructuring Assignment: Nested Objects

3:01:55 Destructuring Assignment: Arrays

3:03:40 Destructuring Assignment with Rest Operator to Reassign Array

3:05:05 Destructuring Assignment to Pass an Object

3:06:39 Template Literals

3:10:43 Simple Fields

3:12:24 Declarative Functions

3:12:56 class Syntax

3:15:11 getters and setters

3:20:25 import vs require

3:22:33 export

3:23:40 * to Import

3:24:50 export default

3:25:26 Import a Default Export

 

var myStr = "i am a \"double quoted\" string inside \"double quotes\""

var myStr = `'Link'`;

console.log(myStr);

var myStr = "FirstLine\n\t\\SecondLine\nThirdLine\n\basdfasdf";

console.log(myStr);

var ourStr = "I come first." + "I come second.";

console.log(ourStr);

var myStr = "This is the start. " + "this is the end."

console.log(myStr);

var myStr = "This is the first sentence. "

myStr += "This is the second sentence."

console.log(myStr);

var myName = "Yunsoo";

var myStr = "my name is " + myName + " and I am well."

console.log(myStr);

var anAdjective = "awesome";

var ourStr = "freeCodeCamp";

ourStr += anAdjective;

var someAdjective = "worthwhile.";

var myStr = "Learning to code is ";

myStr += someAdjective;

console.log(myStr)

 

var firstNameLength = 0;

var firstName = "Ada";

firstNameLength = firstName.length;

console.log(firstNameLength)

 

var firstLetterOfFirstName = "";

var firstName = "Ada";

 

firstLetterOfFirstName = firstName[2];

console.log(firstLetterOfFirstName)

 

var myStr = "Jello World";

myStr[0] = "H";

myStr = "Hellow World"

console.log(myStr);

 

var lastName = "Lovelace";

var thirdLetterOfLastName = lastName[2]

console.log(thirdLetterOfLastName)

 

var lastName = "Lovelace";

var lastLetterOfLastName = lastName[lastName.length - 1];

console.log(lastLetterOfLastName)

 

function worldBlanks(myNoun, myAdjective, myVerb, myAdverb) {

var result = "";

result += "the " + myAdjective + " " + myNoun + " " + myVerb + " to the store.";

return result;

}

console.log(worldBlanks("dog", "big", "ran", "quickly"));

console.log(worldBlanks("bike", "slow", "flew", "quickly"));

 

var ourArray = ["John", 23];

var myArray = ["Quincy", 1]

console.log(myArray)

 

var ourArray = [["the universe", 42], ["everything", 101010]];

var myArray = [["bulls", 23], ["white sox", 45]];

console.log(myArray)

 

var ourArray = [18, 64, 99];

ourArray[1] = 45;

console.log(ourArray)

var myArray = [18, 64, 99];

myArray[0] = 45;

console.log(myArray)

 

var myArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [[10, 11, 12], 13, 14]];

var myData = myArray[2][1];

console.log(myData)



var ourArray = ["Stimpson", "j", "cat"];

ourArray.push(["happy", "joy"]);

var addedFromOurArray = ourArray.push(["happy", "joy"]);

console.log(addedFromOurArray)

console.log(ourArray)

// ourArray now equals ["Stimpson", "j", "cat", ["happy", "joy"]]

 

var myArray = [["John", 23], ["cat", 2]];

myArray.push(["dog", 3])

console.log(myArray)

 

var ourArray = [1, 2, 3];

var removedFromOurArray = ourArray.pop();

//removedFromOurArray now equals 3, and ourArray now equals [1,2] ?????

console.log(removedFromOurArray)

console.log(ourArray)

 

var ourArray = [1, 2, 3];

ourArray.pop();

console.log(ourArray)

 

var ourArray = ["stimpson", "j", ["cat"]];

var removedFromOurArray = ourArray.shift();

//removedFromOurArray now equals "stimpson" and ourArray now equals ["j", ["cat"]]

 

var myArray = [["john", 23], ["dog", 3]];

var removedFromMyArray = myArray.shift();

 

console.log(removedFromMyArray);



var ourArray = ["stimpson", "j", ["cat"]];

var removedFromOurArray = ourArray.shift();

//removedFromOurArray now equals "stimpson" and ourArray now equals ["j", ["cat"]]

console.log(removedFromOurArray)

console.log(ourArray)

 

var myArray = [["john", 23], ["dog", 3]];

myArray.shift();

console.log(myArray);

 

var ourArray = ["stimpson", "j", "cat"];

ourArray.shift();

ourArray.unshift("happy");

// ourArray now equals ["happy", "j", "cat"]

 

var myArray = [["john", 23], ["dog", 3]];

myArray.shift();

myArray.unshift(["paul", 35]);

console.log(myArray);

 

var myList = [["cereal", 3], ["milk", 2], ["bananas", 3], ["juice", 2], ["eggs", 2]]

 

 

function ourReusableFunction() { // () you can pass information into the parenthesis.

console.log("heyya, world");

//this is the opening curly bracket. And then we have the closing curly bracket.

// everything inside the curly bracket is run anytime the function is called or invoked.

}

ourReusableFunction();

ourReusableFunction();

ourReusableFunction();

 

function reusableFunction() {

console.log("hi world");

}

 

reusableFunction()

 

function ourFunctionWithArgs(a, b) {

console.log(a - b);

}

ourFunctionWithArgs(10, 5);

//when the function runs, it can use the information that’s passed into the function.

 

function functionWithArgs(a, b) {

console.log(a + b);

}

functionWithArgs(10, 5)



// Scope refers to the visibility of variables.

//Variables which are defined outside of a function block have global scope.

//Global scope means they can be seen everywhere in your Javascript code.

 

var myGlobal = 10;

function fun1() {

//assign 5 to oopsGlobal here

oopsGlobal = 5;

}

 

//only change colde above this line

function fun2() {

var output = "";

if (typeof myGlobal != "undefined") {

output += " myGlobal: " + myGlobal;

}

if (typeof oopsGlobal != "undefined") {

output += " oopsGlobal: " + oopsGlobal;

}

console.log(output);

}

fun1();

fun2();

 

function myLocalScope() {

var myVar = 5; //this variable, myVar is only visible inside the function.

console.log(myVar);

}

myLocalScope();

 

// console.log(myVar) - there’s an error because it tried to access myVar outside of the function.

 

var outerWear = "t-shirt";

 

function myOutfit() {

var outerWear = "sweater";

return outerWear;

}

console.log(myOutfit()); //It’s because this local variable outerWear took precedence over the global variable.

console.log(outerWear); // first we console.log this function which is sweater – it returns sweater. And then we console.log the global variable which is T-Shirt.



// Return a Value from a Function with return

function minusSeven(num) {

return num - 7;

}

/*

And we’re passing a number into it – the num.

And then it’s going to return whatever is after the return keyword. In this case, num - 7.

*/

var returnvalue = minusSeven(10); // 찬수 첨삭

console.log(returnvalue); // 찬수 첨삭

console.log(minusSeven(10));

 

function timesFive(num) {

return num * 5;

}

console.log(timesFive(5));

 

// understanding undefined value returned from a function

/*

Functions can have return statements, but they don’t have to.

In this case, this function adds 3 to the sum variable which is a global variable because it’s defined before the function.

It does not return anything.

*/

var sum = 0;

function addThree() {

sum = sum + 3;

}

 

function addFive() {

sum += 5; //sum = sum + 5; // we can shorten this to use the +=.

}

/*

So now that’s going to add five to the sum also, but it’s not going to return anything.

So, if we log this out, it would be undefined.

*/

 

// assignment with a returned value

/*

It’s simple to assign a returned value to a variable.

See right here we have the function change.

And you pass in a number and it’s going to return the result of this mathematical expression.

So, when we call the function change and pass in the 10,

the value that is returned from this function is going to be stored in this variable here.

*/

var changed = 0;

 

function change(num) {

return (num + 5) / 3;

}

 

changed = change(10);

 

/*

 

We can do the same thing down here.

First we initialize the variable processed and processedArg.

It’s going to return the result of this mathematical expression.

So, I can set processed to equal what this function returns.

So, I can say processedArg.

And then I’ll just pass in the number 7 here.

And now processed equals the result of this mathematical expression.

*/

var processed = 0;

 

function processArg(num) {

return (num + 3) / 5;

}

 

processed = processArg(7);

 

// stand in line - queue

/*

In computer science a queue is an abstract data structure where items are kept in order.

New items can be added to the back of the queue and old items are taken off from the front of the queue.

We're going to simulate that right now, some of the functionality of a queue using this nextInLine function.

We're going to simulate that right now, some of the functionality of a queue using this nextInLine function.

So, the purpose of this is to show that in this nextInLine function

you can add an item to the array that’s passed in.

And then it’s going to return the first item on the list.

 

For instance, if we have this array right here,

exA

if we add an item to this array it should come after at the end. So, it should come after 5.

exB

And then it should return the first item on the list. In this case, it’s 1.

 

*/

 

function nextInLine(arr, item) {

arr.push(item); // exA : add an item to this array

//return item; // return the item that was passed in

return arr.shift(); // exB : return the first item on the list

}

 

var testArr = [1, 2, 3, 4, 5];

 

/*

we had some console.log set up.

it should show what the list looks like, the array looks like beforehand. And then show what it looks like afterwards.

This JSON.stringify is just a way to change an array into a string that can easily be printed out to the screen.

*/

console.log("befor: " + JSON.stringify(testArr));

/* exA:

So, the first thing is to add the item onto the list.

So, we see right here, nextInLine passed in the testArr and 6.

So, we're calling this function nextInLine.

We're passing in this testArr here. And the number 6.

We want the number 6 to be added to the end of the array. So, we'll just do arr.push(). And then I’ll put in (item).

we took this array that was passed in here which is in this case, testArr.

And we push the item that was passed in.

And in this case here, it’s item 6.

*/

/* exB :

Now we want to return the first item on the list.

We want to remove and return this item.

So, that we console.log here it should show the number 1.

So, instead of returning item, I’m going to return arr.shift().

That’s what shift does. Shift moves the first item and returns that first item.

So, let’s check this out.

*/

console.log(nextInLine(testArr, 6));

console.log("after: " + JSON.stringify(testArr));

 

 

// boolean value - true or false

/*

Booleans are another datatype in Javascript.

There are only two values, true or false.

They’re basically little on/off switches where true is on and false is off.

They don’t use quotation marks around the Boolean.

See, it just says return false.

It should be indented, where it’s going to return false when you call this function.

It could also be true. So, we could return true.

You can use true and false in more places than just function returns

*/

function welcomeToBooleans() {

return true;

}

 

// use conditional logic with if statements

/*

An if statement is used to make decisions in code.

The keyword If tells Javascript to execute the code in the curly braces

under certain conditions defined in the parenthesis.

parenthesis (말·글 속의) 삽입 어구, = bracket

*/



/*

here is a full if statement right here.

And there’s always parenthesis after the keyword if.

And here’s the condition.

So, if the stuff inside these parenthesis evaluates to true,

then the code within these curly braces will be evaluated or run.

in this case, it’s a variable. So, if the isItTrue variable is true, it will return “Yes, it’s true”.

Now if this is not true, then we'll get to the second return statement "No, it’s false”.

this whole function here takes in a variable. And we check if that’s true or not.

*/

function ourTrueOrFalse(isItTrue) {

if (isItTrue) {

return "yes, it's true";

}

return "no, it's false";

}

 

/*

We have another function that hasn’t been filled out yet, trueOrFalse.

And there’s a variable that’s passed in (wasThatTrue).

So, we'll say if – and then the parenthesis (wasThatTrue).

If that’s true, we're going to return something. It will be a string just like before And the string is "Yes, that was true”.

If it’s not true, then we'll get to the second return statement in the function. And we'll return a different string.

 

I’ll just add some semicolons, and then I can run this. And we'll see what happens.

Oh, return needs to be spelled correctly. So, let me spell return correctly.

So, before I run this, I’m going to add a console.log. So we can console.log the answer. ???

So, this is the function call here, 'true or false'. We’re passing in true.

And then we're going to log what is returned here.

Since we passed in true, this if statement evaluates to true and this code is run right here.

*/

function trueOrFalse(wasThatTrue) {

if (wasThatTrue) {

return "yes, that was true";

}

return "no, that was false";

}

 

console.log(trueOrFalse(true));

 

// comparison with the equality operator

/*

There are many comparison operators in Javascript that will return a Boolean of true or false.

The most common is the equality operator.

And it’s often used in an if statement.

*/

 

/*

here it just says if (val).

So, we have this whole if statement right here, if (val).

We're going to see if if (val) = 12.

Now, to check if it equals 12, we're going to have to use the ==.

That is the equality operator and we'll say if (val == 12).

The reason why we can’t just use a single equal sign is that a single equal sign is the assignment operator.

If we just had a single equal sign,

that would mean that we were setting the value of the val variable to equal 12.

We're not trying to set this to equal 12, we're trying to check if the value of this variable equals 12,

so we have to use the double equal sign.

So, now, this testEqual function is going to test to see if the number we pass in is equal to 12.

*/

function testEqual(val) {

if (val == 12) {

return "equal"

}

return "not equal";

}

/*

I can do a console.log here.

Console.log.

And then we can see what appears in the console here.

“Not Equal” because 10 does not equal 12.

*/

console.log(testEqual(12));

 

// comparison with the strict equality operator

/*

We learned about the equality operator which is the double equal == sign.

There’s also the strict equality operator, the triple equal sign ===.

3 === 3

3== '3'

So, here we're checking if 3 equals 3 with the strict equality operator.

So, the difference is that the equality operator,

the double equals sign attempts to convert both values being compared to a common type

while the strict equality operator does not do the type conversion.

So, this is going to evaluate to true, the 3 === 3.

But the 3 === ‘3’ with the string on the side is going to evaluate to false.

Both of these would be true if we were using the double equals sign ==

because the string would be converted to a number and it would be equal to true.

But with the === it does not get converted to a number, so it would be evaluated to false – this second one with the three equal signs.

*/

 

function testStrict(val) {

if (val === 7) {

return "strictly equal";

}

return "strictly not equal";

}

/*

testStrict(7);

testStrict('7;);

now we can pass in the number 7 and it’s going to evaluate to true.

But if we pass in a string 7, it will evaluate to false.

*/

console.log(testStrict(7));

console.log(testStrict('7'));

 

// practice comparing different values

/*

We will do one more review with the equality operator and the strict equality operator.

*/

 

/*

if I run this here, we'll see in the console it says "Equal”

because it’s checking if the number 10 and the string “10” are equal.

Since we're using the equality operator with two equal signs, it performs a type conversion. And it converts the string into a number.

 

But if we use the strict equality operator with three equal signs,

I’ll run that again, and you’ll see “Not Equal” in the console

because now it’s not converting the types and it’s just checking if a number is equal to a string,

*/

function compareEquality(a, b) {

if (a == b) {

return "equal";

}

return "not equal"

}

console.log(compareEquality(10, "10"));

 

// COMPARISON WITH THE INEQUALITY OPERATOR

/*

I’m going to do the inequality operator with an exclamation point and an equal sign.

In this case, I’m going to see if the value is not equal to 99.

*/

function testNotEqual(val) {

if (val != 99) {

return "not equal";

}

return "equal";

}

console.log(testNotEqual(10));

 

// COMPARISON WITH THE STRICT INEQUALITY OPERATOR

/*

(val !== 17) I’m going to do if (val) does not equal 17.

*/

function testStrictNotEqual(val) {

if (val !== 17) { // I’m going to do if (val) does not equal 17.

return "not equal";

}

return "equal";

}

console.log(testStrictNotEqual(10));

 

// COMPARISONS WITH THE LOGICAL AND OPERATOR - Greater Than Operator

/*

We can also use the greater than operator.

in this function we're checking if a value is over 100.

So, I’m going to put greater than 100.

 

if I run that function, you'll see “10 or Under” because we're not over 100.

because we passed in 10.

*/

function testGreaterThan(val) {

if (val > 100) { // So, I’m going to put greater than 100.

return "over 100";

}

if (val > 10) {

return "over 10";

}

return "10 or under";

}

/*

here we call the function. We pass in ?? than ?? 10.

*/

console.log(testGreaterThan(10)); // We pass in ?? than ?? 10.

 

// COMPARISON WITH THE GREATER THAN OR EQUAL TO OPERATOR

/*

We can also use the greater than or equal to operator.

we'll finish this function by using greater than or equal to. It’s just a greater than sign and the equal sign>=.

If I run that, we should see “10 or Over” because we're passing in 10

and it’s greater than or equal to 10.

*/

function testGreaterOrEqual(val) {

if (val > - 20) {

return "20 or over";

}

if (val >= 10) {

return "10 or over"

}

return "less than 10";

}

 

console.log(testGreaterOrEqual(10));

 

// COMPARISON WITH THE LESS THAN OPERATOR

function testLessThan(val) {

if (val < 25) {

return "under 25"

}

if (val < 55) {

return "under 55"

}

return "55 ore over"

}

 

console.log(testLessThan(10));

 

 

// COMPARISON WITH THE LESS THAN OR EQUAL TO OPERATOR

function testLessOrEqual(val) {

if (val <= 12) {

return "smaller than or equal to 12"

}

if (val <= 24) {

return "smaller than or equal to 24"

}

return "more than 24"

}

 

console.log(testLessOrEqual(10)); // if we run, we see “Small Than or Equal to 12”. The number 10 we passed in.

 

// COMPARISONS WITH THE LOGICAL AND OPERATOR

/*

Sometimes you want to check if 2 things are true at the same time.

*/

function testLogicalAnd(val) {

if (val <= 50) {

if (val >= 25) { // I’m going to delete this nested if statement.

return "yes";

}

}

return "no";

}

 

function testLogicalAnd(val) {

if (val <= 50 && val >= 25) { // if I put two ampersands, like this, that means and.

// both this statement and this statement have to be true to get inside this if statement here.

return "yes";

}

return "no";

}

 

testLogicalAnd(10);

 

// COMPARISONS WITH THE LOGICAL OR OPERATOR

/*

In this code here, we’re checking if the value is not between 10 and 20.

*/

 

function testLogicalOr(val) {

if (val < 10) {

return "outside";

}

 

if (val > 20) {

return "outside";

}

return "inside";

}

//I’m just going to delete this whole if statement here,

 

//So, now, we're checking if the value is less than 10 or if the value is more than 20. Either way, we're going to return “Outside”.

function testLogicalOr(val) {

if (val < 10 || val > 20) { // then I can add an or statement. Which is just two pipes.

return "outside";

}

return "inside";

}

testLogicalOr(15);



// ELSE STATEMENTS

/*

When an if statement is true, normally the block of code right after the if statement will be evaluated. And if it’s not true, nothing happens.

*/

function testElse(val) {

var result = "";

 

if (val > 5) {

result = "bigger than 5";

}

if (val <= 5) {

result = "5 or smaller";

}

}

 

/*

with an else statement, an alternate block of code can be executed when it’s not true.

So, this is a perfect use case.

*/

 

function testElse(val) {

var result = "";

 

if (val > 5) {

result = "bigger than 5";

} else {

result = "5 or smaller 111";

}

return result;

}

console.log(testElse(4));

 

// ELSE IF STATEMENTS

/*

If you have multiple conditions that need to be addressed, you can use else if statements.

It’s a way of chaining if statements together.

*/

function testElseIf(val) {

if (val > 10) {

return "greater than 10";

}

 

if (val < 5) {

return "smaller than 5 222";

}

 

return "between 5 and 10";

}

 

console.log(testElseIf(3));



function testElseIf1(val) {

if (val > 10) {

return "greater than 10";

} else if (val < 5) {

return "smaller than 5";

} else {

return "between 5 and 10 444 "; // final return

}

 

}

console.log(testElseIf1(7));




// LOGICAL ORDER IN IF ELSE STATEMENTS

/*

When you’re using else if statements order is very important.

*/

function orderMyLogic(val) {

if(val < 10) {

return "less than 10 111";

} else if (val < 5) {

return "less than 5";

} else {

return "greater than or equal to 10";

}

}

/*

if we put 3 it’s still just going to say “Less than 10”.

Really, we want this to say "Less than 5” because it is actually less than 5.

However, this is in the wrong order. So, what we need to do is change the order.

*/

console.log(orderMyLogic(3));

 

/*

once the first condition is met, it doesn’t even check for the rest of and conditions.

So, that’s why it’s important to think about the order.

*/

function orderMyLogic1(val) {

if(val < 5) {

return "less than 5 222";

} else if (val < 10) {

return "less than 10";

} else {

return "greater than or equal to 10";

}

}

console.log(orderMyLogic1(3));

 

// CHAINING IF ELSE STATEMENTS

/*

I’m going to complete the following challenge here. Write chained if/else if statements to fulfill the following conditions.

*/

function testSize(num) {

if (num < 5) {

return "Tiny";

} else if (num < 10) { // First of all, also I need to put the condition in these parenthesis.

return "Small !!!"; // we're going to return this “Small”. So, I’ll put that in the curly braces here

} else if (num < 15) {

return "medium";

} else if (num < 20) {

return "large";

} else { // We don’t even need an else if with this statement at the end. We don’t even need to put the condition.

return "huge";

}

}

 

console.log(testSize(21));

 

// Golf code

/*

In the game of golf each hole has a par

which means the average number of strokes you’re supposed to use to get the ball into the hole.

depending on how far above or below par your strokes are, there’s a different nickname.

*/

var names = ["hole in one", "eagle", "birdie", "par", "bogey", "double bogey", "go home!"]

function golfScore(par, strokes) {

if (strokes == 1) {

return names[0]

} else if (strokes <= par - 2) {

return names[1]

} else if (strokes <= par - 1) {

return names[2]

} else if (strokes <= par) {

return names[3]

} else if (strokes <= par + 1) {

return names[4]

} else if (strokes <= par + 2) {

return names[5]

} else if (strokes <= par + 4) {

return names[6]

}

}

 

console.log(golfScore(5,8));

 

 

// SWITCH STATEMENTS

/*

Instead of using chained else if statements you can use a switch statement.

A switch statement tests a value and can have many case statements which define various possible values.

*/

function caseInSwitch(val) {

var answer = "";

switch(val) { //we're testing the val that’s passed into this function. it starts off kind of like an if statement.

/*

we're going to compare the val to the different cases that we have.

it’s using the strict equality operator, so it’s like the ===,

it’s going to make sure that the type of the variable are the same.

*/

case 1:

// we're going to indent that so it’s easier to see the different cases.

// if the case is 1, then we're going to set answer to = “alpha”.

answer = "alpha";

/*

Break means that we're at the end of that case statement.

And once you break it, it just goes to the end of the switch statement

and doesn’t evaluate anything else in the switch statement

 

If you don’t have a break statement it will just run through to the next case statement automatically.

if the case was 1 and you did not have a break here, first it would set the answer to “alpha”.

And then it would set the answer to “beta”.

It would just skip over to the next case statement.

 

The break is here.

It’s going to go out of the switch statement completely.

So, it would go – start running the code after this last curly bracket.

*/

break;

case 2:

// case 2, the answer is going to equal to “beta”.

answer = "beta";

break;

case 3:

answer = "gamma";

break;

case 3:

answer = "delta";

break;

} // we know that the switch statement is over because we have this final curly bracket.

return answer; // And then we're just going to return answer.

}

 

console.log(caseInSwitch(2));



// DEFAULT OPTION IN SWITCH STATEMENTS

/*

The default option is kind of like else in an if else statement.

it’s inside this function where we pass in a value into the function.

And we're going to check if the value equals a.

If it equals a the answer is going to be sent to “apple”.

because that was one of the options.

 

what if we pass in something else?

If I pass in the number 2 here it’s going to return an empty string.

 

because the answer is set to an empty string - val answer = "";

and we never override the answer here so it just returns the empty string.

*/

function switchOfStuff(val) {

var answer = "oo";

switch (val) {

case "a":

answer = "apple";

break;

case "b":

answer = "bird";

break;

case "c":

answer = "cat";

break;

}

return answer;

}

console.log(switchOfStuff(3));

/*

What if we want to return something anytime a, b, or c is not passed through.

So, for anything else that’s passed into the function, we're going to do default.

This is like the else statement.

So, the default, we're going to do answer = “stuff”.

*/

function switchOfStuff1(val) {

var answer = "";

switch (val) {

case "a":

answer = "apple";

break;

case "b":

answer = "bird";

break;

case "c":

answer = "cat";

break;

default:

answer = "stuff";

break;

}

return answer;

}

 

console.log(switchOfStuff1(3));

 

// MULTIPLE IDENTICAL OPTIONS IN SWITCH STATEMENTS

/*

Sometimes you want a switch statement where multiple inputs give the same output.

Well, that’s easy enough by omitting the break statement.

*/

function sequentialSizes(val) {

var answer ="";

switch(val) {

case 1:

case 2:

case 3:

answer = "low";

break;

case 4:

case 5:

case 6:

answer = "mid";

break;

case 7:

case 8:

case 9:

answer = "high";

break;

}

return answer;

}

console.log(sequentialSizes(8));

 

// REPLACING IF ELSE CHAINS WITH SWITCH

/*

we're going to change this chain of else if statements to become a switch statement.

*/

function chainToSwitch(val) {

var answer = "";

if (val === "bob") {

answer = "Marley";

} else if (val === 42) {

answer = "the answer" ;

} else if (val === 1) {

answer = "there is no #1" ;

} else if (val === 99) {

answer = "missed me by this much!" ;

} else if (val === 7) {

answer = "ate nine" ;

}

return answer;

}

 

function chainToSwitch(val) {

var answer = "";

switch(val){

case "bob":

answer = "Marley";

break;

case 42:

answer = "the answer" ;

break;

case 1:

answer = "there is no #1" ;

break;

case 99:

answer = "missed me by this much!" ;

break;

case 7:

answer = "ate nine" ;

break;

}

return answer;

}

 

console.log(chainToSwitch(1));

 

// RETURNING BOOLEAN VALUES FROM FUNCTIONS

/*

Here’s a little trick when you want a function to return a Boolean, a true or false value.

 

You may remember from before the all comparison operators return a Boolean true or false value.

*/

function isLess(a,b) {

if (a < b) {

return true;

} else {

return false;

}

}

isLess(10,15);

/*

instead of using this if statement here we can just – we can actually delete all of this and just return the result of this

*/

 

function isLess(a,b) {

return a < b;

}

console.log(isLess(20,15));

 

// RETURNING EARLY PATTERN FROM FUNCTIONS

/*

We've already seen a few examples of this.

But you can return early from a function with the return statement. ?????

*/

function abTest(a, b) {

//if you see this function right here, we return at the very end of the function,

// it leaves the function and returns this value from the function.

// you can leave the function any time with a return statement.

return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));

}

 

console.log(abTest(2,2));

 

/*

we're going to modify this function so that if a or b are less than 0

the function will immediately exit with the value of “undefined”.

*/

function abTest(a, b) {

if (a < 0 || b < 0) { // return a < 0 || b < 0 가능 ??????

return undefined;

}

return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));

}

 

// Scrimba has a little quirk here where it just shows null. But in a browser it will show undefined.

console.log(abTest(-1,2));

 

function abTest1(a, b) {

return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));

}

 

// Scrimba has a little quirk here where it just shows null. But in a browser it will show undefined.

console.log(abTest1(-1,2));

// 브라우저 콘솔에 NaN ????



// COUNTING CARD

var count = 0; // 2) depending on what the card is, it’s going to increase this global count variable, or it’s going to decrease it, or it’s going to stay the same.

 

function cc(card) { // 1) cc and we pass in card.

switch(card){ // 4) we're going to check the card value that was passed in.

case 2:

case 3:

case 4:

case 5:

case 6:

// 5) if the case is 2, 3, 4, 5, 6, we are going to increment the count variable.

// if we just do ++, it increments it by 1.

count++;

break;

/*

if the case is 7, 8, 9 – so let’s paste in three of these.

We’ll do 7, 8, 9.

Actually, we're going to do nothing.

The count is not going to change at all.

So, we don’t even need case 7, 8, or 9.

 

So, instead of doing 7, 8, 9, we just need to check in the case that something is actually going to happen.

 

we are going to decrement the count variable if we have 10, Jack, Queen, King, or Ace.

*/

case 10:

case "J":

case "Q":

case "K":

case "A":

/*

In this case, we're going to decrement the count.

So, we're going to do count --.

So, that’s the same as count = count -1.

*/

count--;

break;

}

 

// We are going to set what that hold bet value is. First, we’ll create the holdbet variable. we’ll set it to ‘Hold’.

var holdbet = "Hold"

// if (count) is more than 0, then we can set holdbet to equal ‘Bet’.

if (count > 0) {

holdbet = 'Bet'

}

return count + " " + holdbet;

}

 

// 3) every time you call the cc function it’s going to change this count value and return the total count.

// - cc 펑션을 부를때마다 카운트 값을 바꾸고 최종 값을 리턴한다.

cc(2); cc('K'); cc(10); cc('K'); cc('A'); // ★ 값이 계속 축적 <- 3)

console.log(cc(4)); // ★ 앞에 축적된 값 + cc(4) 값 <- 3)

 

// BUILD JAVASCRIPT OBJECTS

/*

Objects are similar to arrays, except that instead of using indexes to access data, you use properties.

*/

var ourDog = { // here’s an object called ourDog.

/*

Objects are going to be defined with these curly braces at the beginning and the end.

the properties are everything before the colons.

the values are the things after the colons here.

you can see that the properties can be strings, numbers, arrays.

They can be any datatype in Javascript.

*/

"name" : "Camper",

"legs" : 4,

"tails": 1,

"friends": ["everything!"]

}

 

var myDog = {

"name": "quincy",

"legs": 3,

"tails": 2,

"friends": [] // it’s an empty array.

}

 

// ACCESSING OBJECT PROPERTIES WITH DOT NOTATION

/*

There are two main ways to access a property on an object.

The first I will talk about is dot notation.

*/

var testObj = {

"hat": "ballcap",

"shirt": "jersey",

"shoes": "cleats"

};

/*

right here the hatvalue we're going to set to testObj.

here’s where we use the dot notation.

We just put a dot or a period and then I put the name of the property, .hat.

*/

var hatValue = testObj.hat;

/*

for the shirt value, I will do .shirt. So, see this word right here is just a word here.

*/

var shirtValue = testObj.shirt;

 

// [Accessing Object Properties with Bracket Notation]

/*

Besides using dot notation you can also use bracket notation to access a property in an object.

You can use bracket notation anytime but it is required if the name has a space in it.

*/

var testObj = {

"an entree": "hamburger",

"my side": "veggies",

"the drink": "water"

}

var entreeValue = testObj["an entree"];

var drinkValue = testObj['the drink']; // I’ll use a single quote this time instead of a double quote to show that each of those will work.



// [Accessing Object Properties with Variables]

/*

Bracket notation can also be used to look up object properties using variables.

We have these different numbers associated with these names here.

*/

 

var testObj = {

12: "Namath",

16: "Montana",

19: "Unitas"

}

 

/*

we can look that up using the variable name instead of the number.

instead of putting 16, I’m going to put [playerNumber] in here.

And now player is set to the word, the string "Montana”.

And we use these variable to look up the object property.

*/

var playNumber = 16;

var player = testObj[playNumber];



// [Updating Object Properties]

/*

We can use dot notation to update object properties.

*/

var ourDog = {

"name": "Camper",

"legs": 4,

"tails": 1,

"friends": ["everything!"]

}

 

ourDog.name = "happy camper"; // we used dot notation ourDog.name. And use the assignment operator, the equals sign, to set the name to “Happy Camper”.

// if we do console.log on ourDog.name. it would no longer be “Camper” it would be “Happy Camper”.

var myDog = {

"name": "Coder",

"legs": 4,

"tails":1,

"friends": ["freeCodeCamp Campers"]

}

 

myDog.name = "happer Doggy";

console.log(myDog);

 

// [Add New Properties to an Object]

/*

 

*/

ourDog.bark = "bow-wow";

 

var myDog = {

"name": "happy coder",

"legs": 4,

"tails": 1,

"friends": ["freeCodeCamp campers"]

}

 

myDog['bark'] = "woof!"

 

console.log(myDog.bark)



// [Delete Properties From an Object]

/*

 

*/

var ourDog = {

"name": "camper",

"legs": 4,

"tails": 1,

"friends": ["everything!"],

"bark": "bow-wow"

}

 

delete ourDog.bark;

 

var myDog = {

"name": "happy coder",

"legs": 4,

"tails": 1,

"friends": ["freeCodeCamp campers"],

"bark": "boof"

}

 

delete myDog.tails;



// [Using Objects for Lookups]

/*

Objects can be thought of as a key value storage like a dictionary.

 

in this case we have a switch statement that returns certain values.

So, when you pass in “alpha” to the function it returns “Adams”.

*/

function phoneticLookup(val) {

var result = "";

 

switch(val) {

case "alpha":

result = "Adams";

break;

case "bravo":

result = "boston";

break;

case "charlie":

result = "chicago";

break;

case "delta":

result = "denver";

break;

case "echo":

result = "easy";

break;

}

return result;

}

 

console.log(phoneticLookup("alpha")); // ???????

 

/*

We can replace this switch statement with an object

and use the object for lookups instead of the switch statement.

*/

function phoneticLookup1(val) {

var result = "";

var lookup = {

"alpha":"adams1",

"bravo":"boston1",

"charlie":"chicag1",

"delta":"denver1",

"echo":"easy1"

};

result = lookup[val];

 

return result;

}

 

console.log(phoneticLookup1("charlie"));

 

 

// [Testing Objects for Properties]

/*

You can check if an object has a property with the "hasOwnProperty" method.

Let me show you how to use this method and finish making this function where we check if an object has a specific property.

*/

var myObj = {

gift: "pony",

pet: "kitten",

bed: "sleigh"

};

 

function checkObj(checkProp) {

if (myObj.hasOwnProperty(checkProp)) {

return myObj[checkProp];

} else {

return "not found" // If it doesn’t have the property we’ll return “Not found”.

}

}

 

console.log(checkObj("gift"));

console.log(checkObj("hello"));

 

// [Manipulating Complex Objects]

/*

A Javascript object is a way to store flexible data.

So, you can store strings, numbers, and arrays.

And even other objects.

 

in this example we have an array called myMusic.

 

We can see it’s an array because we have the open bracket and closed bracket.

inside the array are objects.

*/

var myMusic = [

{

"artist": "billy joel",

"title": "piano man",

"release_year": 1993,

"formats": [

"cd",

"8t",

"lp"

],

"gold": true

},

// I’m going to add another object. So, since this is an array, after each element in an array, you have to have a comma.

{

"artist": "beau carnes",

"title": "cereal man",

"release_year": 2003,

// for “formats” this is going to be an array, just like above.

"formats": [

"youtube video"

],

"gold": true

}

// now we've created a second object in our myMusic array.

// each object holds data and a property which is the key value format.

// This is very similar to JSON which we will talk more about later.

];

 

// [Accessing Nested Objects]

/*

Here we have an object with other objects nested inside that.

in order to access sub-properties of an object you can chain together the dot or bracket notation.

*/

var myStorage = {

"car": {

"inside": {

"glove box": "maps",

"passenger seat": "crumbs"

},

"outside": {

"trunk": "jack"

}

}

};

 

var gloveBoContents = myStorage.car.inside["glove box"]; // there’s a space here we have to use bracket notation.

console.log(gloveBoContents) // let’s see if we get the contents here.

 

// [Accessing Nested Arrays]

/*

Array bracket notation can be changed to access nested arrays.

*/

var myPlants = [ // You can see we have this array here.

{ // The first element in the array is this object.

type: "flowers",

//then inside the object we have a key value pair. The key is list and the value is another array here.

list: [

"rose",

"tulip",

"dandelion"

]

},

{ //The second element of the array is this object.

type: "trees",

list: [

"fir",

"pine",

"birch"

]

}

];

 

// we can combine dot notation and bracket notation to access the second tree.

var secondTree = myPlants[1].list[1];

console.log(secondTree);

 

// [Record Collection]

/*

This is a coding challenge we're going to do.

we are supposed to create this updateRecords function

where we can pass in the ID, the property, and the value.

And it’s going to update our record collection with the property and the value.

it’s going to update the collection and then return the collection.

If we have an empty string for the value, it should just completely delete that property.

if we have the property of tracks and then we have a value,

instead of updating the whole tracks here with what we put in,

it’s just going to add the track to the end of this array.

*/

var collection = {

"2548": {

"album": "slippery when wet",

"artist": "bon jovi",

"tracks": [

"let it rock",

"you give love a bad name"

]

},

"2468": {

"album": "1999",

"artist": "prince",

"tracks": [

"1999",

"little red corvette"

]

},

"1245": {

"artist": "robert palmer",

"tracks": [ ]

},

"5439": {

"album": "abba gold"

},

}

 

/*

if you look really here, the comment says "Keep a copy of the collection for tests”.

Keep a copy of the collection for tests

This JSON.parse and JSON.stringify and then collection, this is just a fancy way in Javascript to make a copy of the object.

we want to have a copy of the original object before anything was changed. that’s what that’s for.

*/

var collectionCopy = JSON.parse(JSON.stringify(collection));

 

function updateRecords(id, prop,value) {

if (value === "") {

// it would just delete that whole thing if our value is an empty string.

delete collection[id][prop];

} else if (prop === "tracks") {

/*

If the tracks property is empty, we need to create it. Here’s a fancy way to do that.

It’s going to equal itself. - (1) collection[id][prop]

Or – if the or operator is going to equal an empty array. - (2) || []

if this already exists we're going to set it to equal itself. (1) collection[id][prop]

But if itself doesn’t exist, we'll just set it to equal an empty array. - (2) || []

So, that’s just a way to create that property if it doesn’t already exist.

*/

collection[id][prop] = collection[id][prop] || [];

/*

now that we know it exists we can just push the value to the end of the array.

we'll just do the .push and then put in the parenthesis, the value.

So we're able to push the value that was passed in to the function onto the end of the array.

*/

collection[id][prop].push(value);

} else { // the default condition. "else"

/*

if the value isn’t blank and the property isn’t tracks,

then we just push the value onto the property.

Then we just set the property to equal the value

*/

collection[id][prop] = value;

}

 

return collection;

}

 

updateRecords(2468, "tracks", "test")

console.log(updateRecords(5439, "artist", "ABBA"));



// [Iterate with While Loops]

/*

Loops allow you to run the same code multiple times.

I’m going to talk to you about a while loop that runs while a specified condition is true

and stops once it’s no longer true.

So, we are going to push the digit 0 through 4 onto this array.

 

Every time it went through this five different times and pushed 0, 1, 2, 3 and 4 onto the loop.

*/

var myArray = [];

 

var i = 0;

while(i < 5) {

myArray.push(i);

i++; // I’ll have to do i++ which increments i.

}

 

console.log(myArray);

 

// [Iterate with For Loops]

/*

A for loop is the most common type of loop in Javascript.

*/

var ourArray = [];

 

/*

You start with the keyword for.

And then we have these parentheses with three different items and they’re separated by semicolons.

The first thing is the initialization. - i = 0

Then we have the condition. - i < 5

Then we have the final expression. - i++

So, the initialization happens before any of the code inside the loop runs.

 

once this evaluates to false we break out of the loop.

while i is less than 5 we'll continue to run through the loop over and over until this is false and we break out of the loop.

 

The final thing is what we do at the end of each iteration.

At the end of each iteration, we will increment i by 1.

we are filling our array with the numbers 0 through 4.

*/

for (var i = 0; i < 5; i++) {

ourArray.push(i);

}

 

var myArray = [];

 

/*

while i is less than 6 or until i is more than 6, we are going to run all the code in this loop.

at the end of each iteration, we are going to increment i.

Now I can just do what we have before.

 

We iterated five different times and each time we pushed a new digit onto the array.

And at the end of each iteration we incremented i so it pushed a larger number onto the array.

*/

for (var i = 1; i < 6; i++) {

myArray.push(i);

}

console.log(myArray);

 

// [Iterate Odd Numbers with a For Loop]

/*

Loops don’t just have to increment one at a time.

then we are going to run the loop until i is less than 10.

And finally, our increment, instead of incrementing i by 1, we're incrementing i by 2.

now this is going to push all the even numbers onto the array.

*/

var ourArray = [];

 

for (var i = 0; i < 10; i +=2) { // vs. for (var i = 0; i < 10; i ++)

ourArray.push(i);

}

 

console.log(ourArray);

 

/*

I’m going to write another loop right now that creates an array of odd numbers.

*/

var myArray = [];

 

for (var i = 1; i < 10; i += 2) {

myArray.push(i);

}

 

console.log(myArray);

 

// [Count Backwards with a For Loop]

/*

A for loop can also be used to count backwards.

we're going to iterate through this loop while i is more than 0.

We’re going to keep iterating.

We're starting at 10 and we're going back to 0.

at the end of each iteration we're going to decrement i instead of increment it.

 

We're going to go down by 2.

i -= 2 means i=i-2.

*/

var ourArray = [];

 

for (var i = 10; i > 0; i -=2) {

ourArray.push(i);

}

 

console.log(ourArray);

 

var myArray = [];

 

for ( var i = 9; i > 0; i -=2) {

myArray.push(i);

}

 

console.log(myArray);

 

 

// [Iterate Through an Array with a For Loop]

/*

It is common in Javascript to iterate through the contents of an array.

Before, we were always adding items to the array.

But this time the array already exists.

*/

var ourArr = [9, 10, 11, 12]; // the length is 4 here.

var ourTotal = 0;

 

/*

we are going to start at 0.

But now instead of going to a specific number of iterations, we are going to the OurArr.length.

the length is 4 here. : length - "배열의 갯수 - 1 = 4 - 1 = 3" i = 0,1,2,3

that means this loop would just go even longer until we went through every element of that array.

And then at the end we're going to increment i by one at the end of each iteration.

We're going doing ourTotal that starts off at 0 up here.

it starts at 0. And then it goes 1, 2, 3 until it gets to 4,

which is the length of the array and it doesn’t even run the iteration at 4.

this is just going to add up all those numbers.

If we run this we can see it adds up to 42.

*/

 

for (var i = 0; i < ourArr.length; i++) {

ourTotal += ourArr[i]; // ourArr[0] = 9

}

 

console.log(ourTotal); // 배열 각 수의 합 ( 9 + 10 + 11 + 12)

 

/*

that’s going to add up all the numbers in this array here.

*/

myArray = [2, 3, 4, 5, 6];

total = 0

 

for (var i = 0; i < myArray.length; i++) {

total += myArray[i];

}

 

console.log(total);

 

// [Nesting For Loops]

/*

If you have a multidimensional or nested array, you can use nested for loops to access all the array elements.

It’s defined up here, but we're calling it here and we're passing in this multidimensional array.

Which is basically an array with the arrays inside the array.

inside the first array there are three elements.

And you can see each of those elements are in array with their own set of elements.

we are going to use 'nested for loops' within this multiplyAll function to multiply every number in these nested arrays here.

*/

 

function multiplyAll(arr) {

var product = 1;

 

/*

We’re going to initialize i to 0.

And then we're going to say while i is less than arr.length.

And then we're just going to increment i at the end of each iteration.

 

Now, arr.length, that’s going to start off as 3 because we're passing in this array.

And the first level of the array, there’s just one, two, three elements.

*/

for (var i = 0; i < arr.length; i++) {

 

/*

But now, we're going to go inside this for loop and create another for loop.

Normally, it’s standard practice to call the variable that we're incrementing i,

but we already have an i within this scope.

So, we need to create another name and it’s pretty standard to call the next variable j because j is after i.

 

So, the first iteration of this outer for loop, we're looking at the length of this array.

so we're going to be going to each different array inside the nested array.

So, at this point, we just have to multiply all the numbers together.

 

we already have the product that we've defined above.

So, we're going to do product *= which is just going to multiply everything together.

 

the i references the outer array

and the j references the inner array within what we're passing in.

*/

for (var j=0; j < arr[i].length; j++) {

product *= arr[i][j]

}

}

 

return product;

}

var product = multiplyAll([[1,2],[3,4],[5,6,7]]);

 

console.log(product); // 1*2*3*4*5*6*7 = 5040



// [Iterate with Do…While Loops]

/*

we already talked about while loops and I’m going to review this while loop

and then I will tell you how a do while loop is different than a while loop.

*/

var myArray = []; // here we have this empty array.

var i = 10; // We have 'i equals 10'.

 

/*

this while loop first checks the condition before it runs any code within the loop.

A do while loop will always run at least one time and then it will check the condition.

So, here we have this empty array.

*/

while (i < 5) {

myArray.push(i);

i++;

}

 

console.log(i, myArray); // 결과는 10 [] - we see it logged out 10 and then an empty array

 

/*

And then at the beginning I’m going to put the keyword do.

In a do while loop, this is always run at least once before it checks the condition.

So, first it’s going to do these things (1) and then it’s going to check the condition. (2)

 

In this case, it’s going to find out the condition is false and it’s going to break out of the loop.

*/

do {

//So, first it’s going to do these things -- (1)

myArray.push(i);

i++;

} while (i < 5) // and then it’s going to check the condition. -- (2)

 

console.log(i, myArray); // 결과는 11 [10] - See, now i is 11 and the array has the 10 added to it.

 

// [Profile Lookup]

/*

these are key value pairs here.

 

what we want to do is create this lookUpProfile function where we pass in a name. This is a first name. And the property.

and it’s going to return the value of that property.

 

If the name that’s passed in does not correspond to any contacts, then our function should return “No such contact”.

 

And if there’s no property, it should return “No such property”.

*/

var contacts = [

{

"firstName": "akira",

"lastName": "laine",

"number": "0543245234",

"likes": ["pizza", "coding", "brownie points"]

},

{

"firstName": "harry",

"lastName": "potter",

"number": "1994353245325",

"likes": ["hogwarts", "magic", "hagrid"]

},

{

"firstName": "sherlock",

"lastName": "homes",

"number": "048873543523",

"likes": ["intriguing cases", "violin"]

},

{

"firstName": "kristian",

"lastName": "vos",

"number": "unknown",

"likes": ["javascript", "gaming", "foxes"]

}

];

 

function lookUpProfile(name, prop) {

/*

So, the first thing we're going to have to do is iterate through each element in the contacts list.

we'll do i++ to increment that.

*/

for (var i = 0; i < contacts.length; i++) {

if(contacts[i].firstName === name) {

return contacts[i][prop] || "no such property" // or if it doesn’t exist, we're going to return “No such property”.

/*

And just so you know, there would be a way to do this without using this or operator

as long as that your code passes the requirements, that’s all that’s important.

*/

}

}

return "no such contact"; // if the name that was passed in is not in the array,we're going to return “No such contact”.

}

 

var data = lookUpProfile("sherlock", "likes");

 

console.log(data);

 

// [Generate Random Fractions]

/*

There is a simple way to create a random decimal number in Javascript.

It’s with the math.random function.

But we're going to use the math.random function.

*/

function randomFraction() {

 

return 0; // And it’s returning 0 currently.

}

 

/*

But we're going to use the math.random function.

And you well see that when I run this we have 0,2003813741 and so on.

So, it’s always going to be a number between 0 and it could be 0.

Between 0 and 1, but it could not be 1.

*/

function randomFraction() {

 

return Math.random();

}

console.log(randomFraction());



// [Generate Random Whole Numbers]

/*

Often you want a random whole number instead of a random decimal number.

That can be accomplished with Math.floor.

This rounds down to the nearest whole number.

*/

 

/*

This is going to create a random whole number between 0 and 19.

Remember Math.random can never be 1. It can be 0, but it can ever be quite 1.

So, when we multiply it by 20 we’re going to get a number between 0 and 20, but not including 20.

And then we round down, which will end up being 0 to 19.

*/

var randomNumberBetween0and19 = Math.floor(Math.random() * 20);

 

/*

function randomWholeNum() {

 

return Math.random;

}

So, we're going to modify this function.

So, this Math.random we're going to pass that into Math.floor.

So, I have to put the parenthesis because we're passing that in to that function.

And it’s Math.random * 10.

And that’s going to give us a random number between 0 and 9.

*/

function randomWholeNum() {

 

return Math.floor(Math.random() * 10);

}

 

console.log(randomWholeNum());

 

// [Generate Random Whole Numbers within a Range]

/*

So, this is just a calculation to get a random number between the min and max.

*/

function ourRandomRange(ourMin, ourMax) {

 

return Math.floor(Math.random() * (ourMax - ourMin + 1)) + ourMin;

}

 

ourRandomRange(1,9);

 

function randomRange(myMin, myMax) {

 

return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;

}

 

var myRandom = randomRange(5, 15);

 

console.log(myRandom);

 

// [Use the parseInt Function]

/*

Another useful function is the parseInt function.

It takes a string and returns an integer.

A lot of times you want to make sure you’re dealing with integers and not strings

for different calculations and things like that.

If the string cannot be converted into an integer it returns in NaN for Not a Number.

So, let me show you how it works.

*/

function convertToInteger(str) {

return parseInt(str);

}

 

convertToInteger("56");

 

console.log(convertToInteger("5621qwdsfasdf"))

 

// [Use the parseInt Function with a Radix]

/*

The parseInt function can also be used with a radix.

The radix specifies the base of the number in the string.

Such as base 2 or base 7 or base 8.

A base 2 would be binary.

So, that’s one of the most common ones to use.

Now the default is base 10.

That’s what we use normally every day.

*/

function convertToInteger(str) {

return parseInt(str, 2)

}

 

/* https://blog.naver.com/ghks7475/222134750899

2의 0승 = 1 ????

101111 (이진수) = 47(십진수)

2-5승 *1 + 2의4승*0 + 2-3승*1 + 2의2승*1 + 2의1승*1 + 2의0승*1

= 32 + 0 + 8 + 4 + 2 + 1

*/

/*

2의 4승*1 + 0 + 0 + 2의1승*1 + 2의0승+1

= 16+0+0+2+1=19

*/

console.log(convertToInteger("10011"))



// [Use the Conditional (Ternary) Operator]

/*

It’s like a one line if else expression.

 

condition ? statement-if-true : statement-if-false;

(1) (2) (3) (4) (5)

(1) You have your condition just like in an if statement.

(2) And then you would have a question mark.

(3) After the question mark you have what’s going to happen if the condition is true.

(4) Then you have a colon.

(5) Then you have what’s going to happen if the condition is false.

*/

function checkEqual(a,b) {

if(a === b) {

return true;

}

else {

return false;

}

}



function checkEqual(a,b) {

return a === b ? true : false; // (a)

// You would never write a line like this in real life because you could just write return a === b.

return a=== b; // And this line is actually going to do the same thing as this (a) line.

}

checkEqual(1, 2);

 

// [Use Multiple Conditional (Ternary) Operators]

/*

I just want to give you a simple example of using the ternary operator.

One of the great things about conditional or ternary operators is that you can nest them within each other which gives them even more power.

*/

function checkSign(num) {

/*

return num > 0 ? "positive" : num < 0 ? "negative" : "zero"

(1) (2) (3)

So, if this(1) is true we just return “positive” (2).

If it’s (1) false, then we do everything here (3) which is another ternary operator where it checks if this is true.

And if that’s true, we return “negative”. And if it’s false, it would return “zero”.

*/

return num > 0 ? "positive" : num < 0 ? "negative" : "zero"

}

 

console.log(checkSign(2));

 

// [Differences Between the var and let Keywords]

/*

For a long time in Javascript if you were going to declare a variable you had to use the var keyword.

But starting with ES6 in 2015 we can now declare variables with let and const as well.

Over the next few lessons I will be talking about what let and const do that is different than var.

But one of the things is that let does not let you declare a variable twice.

*/

 

/*

You have var catName = “Quincy”. And then down here, var catName = “Beau”.

And if I just run this code you’ll see that nothing is happening.

var catName = "Quincy";

var quote;

var catName = "Beau";

function catTalk() {

"use strict";

catName = "oliver";

quote = catName + " says Meow!";

}

*/

 

/*

However, if we change this to let. We're going to change all the var to let.

And you’ll see that when we load it again, you’ll see an error, Duplicate declaration “catName”.

So, this is good that it’s creating this error because you usually don’t want to declare a variable two times in the same scope.

So, this allows your program to give you an error to tell you that you’ve done something wrong.

let catName = "Quincy";

let quote;

let catName = "Beau";

// - Uncaught SyntaxError: Identifier 'catName' has already been declared

function catTalk() {

"use strict";

catName = "oliver";

quote = catName + " says Meow!";

}

*/



/*

Now you can still reset it.

So if we don’t use the word let here we could just set the catName variable. - (1)

 

In this case, we're declaring the variable here to be “Quincy”

and we're setting the same variable to a new name here.

This is one of the few reasons that many people only use let and const

and never use var to declare variables.

*/

let catName = "Quincy";

let quote;

catName = "Beau"; // Now you can still reset it. (1)

function catTalk() {

/*

Another thing in this code you can see is “use strict”.

Now this enables strict mode which catches common coding mistakes and unsafe actions.

So, a lot of people will use “use strict” at the top of a full Javascript file

or maybe just in a function to catch coding mistakes.

Such as if you create a variable and don’t declare it with var, let, or const.

*/

"use strict";

catName = "oliver";

quote = catName + " says Meow!";

}

 

// [Compare Scopes of the var and let Keywords]

/*

Another major difference between the var and let keywords

is that when you declare a variable with var,

it is declared globally or locally if declared inside a function.

However, let – the scope of let is limited to the block statement or expression that it was declared in.

*/

 

/*

it’s setting i with a var here, the var keyword, to “function scope”.

Then we're setting it to “Block scope” in here.

And you can see it’s console.logging “Block scope i is: “.

And it says “Block scope”.

And when we get down here "Function scope” it’s still “Block scope”.

*/

function checkScope() {

"use strict";

var i= "function scope";

if (true ) {

i = "block scope";

console.log("block scope i is: ", i); // block scope i is: block scope

}

console.log("function scope i is: ", i); // function scope i is: block scope

return i;

}

 

checkScope();

 

/*

If we want this to be “function scope” down here (1), we're going to have to use let.

*/

function checkScope1() {

"use strict";

let i= "function scope";

if (true ) {

let i = "block scope";

console.log("block scope i is: ", i); // block scope i is: block scope

}

console.log("function scope i is: ", i); // (1) - function scope i is: function scope

return i;

}

 

checkScope1();

 

 

// when we're outside of this squiggly braces here, we can still access i here.

/*

that’s another reason why people use let instead of var is so that they can make sure the variable is only defined in the area they want it to be defined in.

*/

function checkScope2() {

"use strict";

if (true ) {

var i = "block scope";

console.log("block scope i is: ", i); // block scope i is: block scope

}

console.log("function scope i is: ", i); // function scope i is: block scope

return i;

}

 

checkScope2();

 

// [Declare a Read-Only Variable with the const Keyword]

/*

Const is another way to declare a variable.

It has all the features of let but it’s also read-only.

You cannot reassign a const.

*/

function printManyTimes(str) {

"use strict";

 

var sentence = str + " is cool!";

 

sentence = str + " is amazing!"

 

for(var i = 0; i < str.length; i+=2) {

console.log(sentence);

}

}

printManyTimes("freeCodeCamp");

 

/*

If you declare a variable with the const keyword you cannot reassign it afterwards.

This can be very helpful to prevent you from accidentally making mistakes later.

If you know for sure that you never want to reassign a variable,

always use const so you don’t accidentally reassign it when you don’t mean to.

function printManyTimes1(str) {

"use strict";

 

const sentence = str + " is cool!";

 

sentence = str + " is amazing!"

 

for(var i = 0; i < str.length; i+=2) {

console.log(sentence);

}

}

printManyTimes1("freeCodeCamp"); // error : “sentence” is read-only.

*/

 

/*

Another thing is when you’re using const it’s very common to use all capital letters.

while we're at it, we're going to change this to let

because for the most part you should only use const or let,

but there are certain circumstances where you would use var.

And also in some other videos in this course I’ll be using var.

But in your own code you should mainly use const and let.

*/

function printManyTimes2(str) {

"use strict";

 

const SENTENCE = str + " is cool!";

 

for(let i = 0; i < str.length; i+=2) {

console.log(SENTENCE);

}

}

printManyTimes2("freeCodeCamp");

 

// [Mutate an Array Declared with const]

/*

While you cannot reassign a variable declare with const you can mutate an array.

 

First we declare the variable s and we assign it to an array. We declare with const.

And now we're going to reassign the variable s here.

But if we do that we're going to get the error “s” is read-only.

 

const s = [5, 7, 2];

function editInPlace() {

"use strict";

 

s = [2, 5, 7];

}

editInPlace();

*/

 

/*

However, we can update the array using bracket notation.

I’ll do index [0]. I’ll assign to the 2. Index [1], I’ll assign that to 5. And then index [2] I’ll assign that to 7.

And just like that it is going to reassign the array.

*/

const s = [5, 7, 2];

function editInPlace() {

"use strict";

 

s[0] = 2;

s[1] = 5;

s[2] = 7;

}

editInPlace();

 

console.log(s);

 

// [Prevent Object Mutation]

/*

As seen previously, a const declaration alone doesn’t really protect your data from mutation.

If you have an object or an array, you can still mutate it even if it’s declared with const.

There is something called object.freeze that will prevent data mutation.

*/

 

/*

We're using this function to demonstrate object.freeze.

(1)

if we look down here, this is a try catch block.

We'll talk about try catch blocks in more detail later.

But for now, you just have to know that it’s going to try what’s in the first part of the block.

And if there’s an error, then it’s going to go into the catch part and it’s going to log it out.

*/

function freezeObj() {

"use strict";

const MATH_CONSTANTS = {

PI: 3.14

};

 

/*

(2) And in parenthesis I’ll put the object which is (MATH_CONSTANTS).

Now I’ve frozen MATH_CONSTANTS.

when it tries to change MATH_CONSTANTS.PI here it’s not going to work

and it’s going to go into this catch block and it’s going to log out the error or the exception.

 

whenever you have an object and you don’t want any of the items in the object to change,

use object.freeze.

*/

Object.freeze(MATH_CONSTANTS); // (2)

 

try { // (1)

MATH_CONSTANTS.PI = 99;

} catch( ex ) {

console.log(ex);

}

return MATH_CONSTANTS.PI;

}

 

const PI = freezeObj();

 

console.log(PI);



// [Use Arrow Functions to Write Concise Anonymous Functions]

/*

This function here is called an anonymous function.

It doesn’t have a name.

It is assigned to this variable 'magic'.

But there’s no word right before the function keyword to assign the name to the function.

Whenever you have an anonymous function you can convert it into an arrow function.

*/

var magic = function() {

return new Date();

};

 

/*

So, instead of the word function, I’m going to take that out completely. And then put an arrow here.

So, this is the same thing except it’s just a little quicker to write.

But we can shorten this even more.

*/

var magic1 = () => {

return new Date();

}

 

/*

But we can shorten this even more.

If we're just returning one value here we don’t even need the return keyword.

And we don’t need the curly braces.

And now this is the full function from before, but it’s just really shortened up.

And to make this even nicer, we're not going to use var.

I’m going to change this to const.

*/

const magic2 = () => new Date();

 

// [Write Arrow Functions with Parameters]

/*

Just like in a normal function, you can pass arguments to arrow functions.

*/

var myConcat = function(arr1, arr2) { // it has two arguments.

return arr1.concat(arr2); // then it’s going to concatenate the two arrays passed in.

 

};

 

console.log(myConcat([1, 2], [3, 4, 5]));

 

/*

So let me show you how to convert this function into an arrow function.

first we'll take off the function keyword.

We're going to leave these parenthesis with the parameters.

 

I just converted that function into an arrow function and it has these two parameters.

So, we just have the parameters in parenthesis.

We have the arrow.

And then we have what’s being returned right after the arrow.

So, if I run that you’ll see that we concatenate the two arrays that are passed in in this example.

And then for good measure we'll change this to const.

*/

const myConcat1 = (arr1, arr2) => arr1.concat(arr2);

 

console.log(myConcat1([1, 2], [3, 4, 5]));

 

// [Write Higher Order Arrow Functions]

/*

Arrow functions work really well with higher order functions such as map, filter, and reduce.

 

But the main thing to know is that they take functions as arguments for processing collections of data.

Whenever one function takes another function as an argument, that’s a good time for an arrow function.

*/

const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];

 

/*

So, what we're going to do here is we're going to update this function right here.

We want it to compute the square of only the positive integers in the array.

And we want to filter out everything that’s not a positive integer.

So, I’m going to use the filter and map functions to do that.

But the main thing I want you to look at is the arrow functions that I’m passing in to filter and map.

This line is going to be a lot more succinct because of the arrow functions.

*/

const squareList = (arr) => {

/*

Now before I showed you that you passed an arguments in parenthesis for an arrow function.

But if you only have a single argument like this, the number argument,

you don’t need parenthesis around the argument.

You can just put the argument and then the arrow.

*/

 

/*

First we want to filter this array so we only have numbers that are integers and numbers that are more than zero.

So, we'll do Number.isInteger.

Now the result of this filter command

will be an array with all the numbers that are more than 0 and also integers.

So, that will be 4, 42, and 6.

 

But after we get that new array we want to get t he square of each number in that array.

So, that’s where we’re going to use the map function.

 

Now the map function takes a function as its argument.

But instead of writing a full function out we can use an arrow function.

So, we're going to pass in x to the function.

And then there’s going to be an arrow function.

Now x just means every element from the array that’s being passed to it.

So, remember the map is getting the array for 42, 6.

x means for every element in the array this is what we're going to do to it.

x * x because it’s going to be squared.

*/

const squaredIntegers = arr.filter(num => Number.isInteger(num) && num > 0).map(x => x * x);

return squaredIntegers;

};

 

const squaredIntegers = squareList(realNumberArray);

console.log(squaredIntegers);



// [Default Parameters ]

/*

In order to create more flexible functions you can use default parameters.

The default parameter kicks in when the argument is not specified or is undefined.

*/

 

/*

So, you can pass in two arguments, the 5 and 2 to increment by 2.

Or you can just pass in the one argument, the 5 if you want to increment by 1.

So, here are the numbers we're passing in.

A number and a value.

So, we just have to put value = 1.

So now if a value isn’t passed in, it will be set to 1 automatically,

but if it is passed in, it will be set to whatever is passed in.

*/

const increment = (function() {

return function increment(number, value = 1) {

return number + value;

};

})();

console.log(increment(5, 2));

console.log(increment(5));

 

// [Use the Rest Operator with Function Parameters]

/*

The rest operator allows you to create a function that takes a variable number of arguments.

*/

const sum1 = (function() {

// The rest operator allows you to create a function that takes a variable number of arguments.

return function sum1(x, y, z) {

// So, at first it’s converting these x, y, z into an array called args.

const args = [x, y, z];

// And then it’s reducing them. So, it’s summing them all up here and then returning the results.

return args.reduce((a, b) => a + b, 0);

};

})();

console.log(sum1(1, 2, 3));

 

/*

But where it’s accepted here, where we have the arguments here, x, y, z, I’m just going to put .... That’s the rest operator.

we can also now add any number of numbers.

So, before we could only pass in three arguments. And now, we can have any number of arguments.

*/

const sum2 = (function() {

return function sum2(...args) {

return args.reduce((a, b) => a + b, 0);

};

})();

console.log(sum2(1, 2, 3, 4));

 

 

// [Use the Spread Operator to Evaluate Arrays In-Place]

/*

The spread operator looks just like the rest operator. Three dots.

But it expands an already existing array.

Or it spreads out an array.

So, it takes an array and spreads it out into its individual parts.

*/

 

const arr1 = ['jan', 'feb', 'mar', 'apr', 'may'];

let arr2;

(function() {

arr2 = arr1;

arr1[0] = 'potato'

})();

console.log(arr2);

 

/*

And the spread operator can spread this array,

this arr1 into the individual months instead of the actual array here.

You can only use it in an argument to a function or in an array literal.

 

But if we put this inside brackets, which is an array,

it will spread out the contents of arr1 into this new array.

So, we're not making arr2 equal to arr1.

We're making arr2 equal all of the contents of arr1 so they’ll be different.

*/

const arr1a = ['jan', 'feb', 'mar', 'apr', 'may'];

let arr2a;

(function() {

arr2a = [...arr1a];

arr1a[0] = 'potato'

})();

console.log(arr2a);



// [Use Destructuring Assignment to Assign Variables from Objects]

/*

This is a special syntax for neatly assigning values taken directly from an object to a variable.

*/

 

/*

We have this object with three elements.

We have the x, y, and z with their values.

And it’s all in the voxel variable.

*/

var voxel = {x: 3.6, y: 7.4, z:6.54};

 

/*

So, if we want to take each individual element in this object

and assign it to its own variable, this is the old way of doing it.

So, we can do vox with an x. This stores x.

*/

var x = voxel.x;

var y = voxel.y;

var z = voxel.z;

 

const voxel1 = {

x: "figure it out!", // field

y:3.7,

z:"how amazing!"

};

/*

Now with destructuring, there’s a simpler and quicker way to assign variables for each element in an object.

the destructuring syntax

This time, we are creating variables a, b, and c

and assigning them to a values from the object x, y, and z.

We can see we put it in curly braces here.

And we just say it equals the object.

You can read it like this, get the field of x from the object and copy into the value a.

this is just a quicker way of assigning things from an object into variables.

*/

const { x : a, y : b, z : c } = voxel1;

 

console.log(a);

console.log(b);

console.log(c);

 

/*

Now we're going to use destructuring to obtain the average temperature for tomorrow from the input object AVG_TEMPERATURES.

*/

const AVG_TEMPERATURES = {

today: 77.5,

tomorrow:79

};

/*

And then the average temperature is inputted into this function here. (1)

*/

function getTempOfTmrw(avgTemperatures) { // - (1)

"use strict";

 

const tempOfTomorrow = avgTemperatures.tomorrow;

 

return tempOfTomorrow;

}

 

console.log(getTempOfTmrw(AVG_TEMPERATURES));



const AVG_TEMPERATURES1 = {

today: 72.5,

tomorrow:72

};

function getTempOfTmrw1(avgTemperatures) {

"use strict";

 

/*

this is saying get the tomorrow field from the AVG_TEMPERATURES object

and assign it to the tempOfTomorrow variable.

*/

const { tomorrow : tempOfTomorrow1 } = avgTemperatures;

 

return tempOfTomorrow1;

}

 

console.log(getTempOfTmrw1(AVG_TEMPERATURES1));

 

// [Destructuring Assignment with Nested Objects]

/*

We can also use destructuring assignment to assign variables from nested objects.

*/

const LOCAL_FORECAST = {

today: { min: 72, max:83},

tomorrow: { min: 73.3, max: 84.6 }

};

 

/*

And so we’ve destructured two times.

And the variable is maxOfTomorrow.

So, we’ve set the max that was inside tomorrow to maxOfTomorrow.

*/

function getMaxOfTmrw(forecast) {

"use strict";

 

// const maxOfTomorrow = undefined;

const { tomorrow : { max : maxOfTomorrow}} = forecast;

 

return maxOfTomorrow;

}

 

console.log(getMaxOfTmrw(LOCAL_FORECAST));

 

// [Use Destructuring Assignment to Assign Variables from Arrays]

/*

You can use destructuring assignment to assign variables from arrays.

*/

 

/*

So, we have this array of [1, 2, 3, 4, 5, 6]

and we're assigning the variable z and x to the first two numbers of the array, 1 and 2.

The difference between destructuring from arrays and destructuring from objects

is that you cannot specify which element from the array to go into a variable.

It just goes in order.

 

We would just add some commas. So, we put a comma with nothing in it, like that. Two commas in a row.

*/

const [z1, x1, ,y1] = [1, 2, 3, 4, 5, 6];

console.log("here is " + z1, x1, y1);

 

/*

You can use destructuring of arrays to switch the places of variables.

 

Let me uncomment out these.

And what I’m going to do is use destructuring to switch the places of a and b.

So now it’s just taking this and switching the places.

*/

let a1 = 8, b1 = 6;

( () => {

"use strict";

[a1, b1] = [b1, a1]

 

})();

 

console.log("a is " + a1);

console.log("b is " + b1);

 

// [Use Destructuring assignment with the Rest Operator]

/*

We can use destructuring assignment with the rest operator to reassign array elements.

*/

 

// we have this array, the digits 1 through 10 in the array.

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

function removeFirstTwo(list) {

 

/*

But right now we just need to return the array with the first two elements missing.

*/

const [ , , ...arr] = list;

 

return arr;

}

 

const arr = removeFirstTwo(source);

console.log(arr);

console.log(source);

 

// [Use Destructuring Assignment to Pass an Object as a Function’s Parameters]

/*

You can use destructuring assignment to pass an object as a function’s parameter.

*/

const stats = {

max: 56.78,

standard_deviation: 4.34,

median: 34.54,

mode: 23.87,

min: -0.75,

average: 35.85

};

const half = (function() {

 

/*

return function half(stats) {

return (stats.max +stats.min) / 2.0;

we have this half function. And it’s getting the stats argument.

*/

 

/*

So, now when the stats get passed in, it’s destructured into just the max and min variables.

And the max and min from the function gets passed in.

So now instead of doing stats.max we can just do max.

Instead of stats.min we can do min.

*/

return function half({ max, min }) {

return (max + min) / 2.0

};

/*

This is commonly used with API calls.

When you are getting information from an Ajax request or an API request,

it will often have a lot more information than what you need.

And you can use destructuring to get it down to what we actually want to work with.

*/

 

})();

console.log(stats);

console.log(half(stats));



// [Create Strings using Template Literals]

/*

Template literals are a special type of string that makes creating complex strings easier.

You make them with this backtick.

*/

const person = {

name: "zodia hasbro",

age: 56

};

 

/*

We have the beginning backtick and we have the ending backtick.

This would be in place of using a quotation, a single or double quotation mark.

A few advantages of using these template literals,

these backticks instead of quotation marks, are one, you can make multiline strings.

You can see this has two lines.

Another thing is you can add single or double quotation marks right in the string and you don’t have to escape them.

The third thing is you can put variables right in the string.

So, if we see this, see the $.

And then we have these curly braces.

And so, anything in between these curly braces that start with the $ is Javascript.

So, right now we just have this variable, person.name which gets the name from up here.

So, it makes things easier that you can put variables right in the strings.

*/

const greeting = `hello, my name is ${person.name}!

I am ${person.age} years old.`;

 

console.log(greeting);

 

/*

we want it to create a list based on the array that’s passed in.

 

we want it to return an array that looks like this.

Each element in the array is a template literal that has some HTML in it

let’s use template literal to create that.

*/

const result = {

success: ["max-length", "no-amd", "prefer-arrow-function"],

failure: ["no-var", "var-on-top", "linebreak"],

skipped:["id-blacklist", "no-dup-keys"]

};

function makeList(arr) {

// const resultDisplayArray = null;

const resultDisplayArray = [];

for (let i = 0; i < arr.length; i++) {

/*

And then here is where I’m going to use the template literal.

Put a backtick.

And I’ll put this HTML code here.

*/

resultDisplayArray.push('<li class="text-warning">${arr[i]</li>')

}

 

return resultDisplayArray;

}

 

const resultDisplayArray = makeList(result.failure);

 

console.log(resultDisplayArray)

 

// [Write Concise Object Literal Declarations Using Simple Fields]

/*

ES6 added some nice support for easily defining object literals.

 

It takes in three variables, name, age, and gender.

And it’s going to return an object.

And the object is going to have a series of key value pairs where the key is the name, age, and gender.

And the values are the passed in variable names.

*/

const createPerson = (name, age, gender) => {

return{

// So, you can see there’s some repetition.

name: name,

age: age,

gender: gender

};

};

console.log(createPerson("zodiac hasbro", 56, "male"));

 

/*

If you know that you want to create an object where the key is the name of the variable and the value is the value of the variable, there’s an easier way to do it.

 

Javascript knows that it’s going to return this object and it’s going to have three key value pairs, the name, age and gender.

*/

const createPerson1 = (name, age, gender) => ( {name, age, gender});

console.log(createPerson1("zodiac1 hasbro", 56, "male1"));

 

 

// [Write Concise Declarative Functions]

/*

An object can contain a function.

This is the long way to put a function within an object.

But there is a simpler way.

We have the setGear function.

*/

const bicycle = {

gear: 2,

setGear: function(newGear) {

"use strict";

this.gear = newGear;

}

};

 

bicycle.setGear(3);

console.log(bicycle.gear);

 

/*

instead of using the function keyword and this colon, we can just delete all that.

And the now this is the new way.

If I load this again, you’ll see 3 in the console just like it was before.

Because we've been able to set the gear using that function.

*/

 

const bicycle1 = {

gear: 10, // gear: a, ???

setGear(newGear) {

"use strict";

this.gear = newGear;

}

};

 

bicycle1.setGear(21); // bicycle1.setGear(b); -> ??? 결과가 3.7이 됨

console.log(bicycle1.gear);

 

// [Use class Syntax to Define a Constructor Function]

/*

ES6 provides a syntax to create objects using the class keyword.

*/

 

/*

So, here’s the older way to create an object.

It’s with the new keyword.

We can instantiate an object using this new keyword.

And we're instantiating the SpaceShuttle object.

We have to have this constructor function up here.

So, we use this to construct the object.

Where we pass in the target planet, ‘Jupiter’.

And we set the targetPlanet to this.targetPlanet.

Once we create the new object like this, that allows us to do zeus.targetPlanet.

So, zeus.targetPlanet which we set to Jupiter.

*/

SpaceShuttle = function(targetPlanet){

this.targetPlanet = targetPlanet;

}

var zeus = new SpaceShuttle('jupiter');

console.log(zeus.targetPlanet);

 

/*

The class syntax replaces the constructor function creation.

And this works exactly the same as before. We’re using the class keyword and this constructor.

*/

 

class SpaceShuttle1 {

constructor(targetPlanet){

this.targetPlanet = targetPlanet;

}

}

 

var zeus = new SpaceShuttle1('mars');

console.log(zeus.targetPlanet);




function makeClass() {

return Vegetable;

}

const Vegetable = makeClass();

const carrot = new Vegetable('carrot');

console.log(carrot.name);

 

/*

(1) So, now that we have this, we can set this Vegetable to makeClass,

(2) which will return a Vegetable class.

(3) And then when we do new Vegetable and passing banana, this banana will go into here - (4).

(5) And it’ll get set as this.name.

*/

function makeClass() {

class Vegetable1 {

constructor(name){ // - (4)

this.name = name; // - (5)

}

}

return Vegetable1; // - (2)

}

const Vegetable1 = makeClass(); // - (1)

const banana = new Vegetable1('banana'); // -(3)

console.log(banana.name);

 

// [Use getters and setters to Control Access to an Object]

/*

_ : underscore

With the class object you often want to obtain values from the object and set a value of a property within an object.

This are often called getters and setters.

We also have a getter and setter to get and set the writer. So we can get the writer and we can set the writer.

Getter functions are meant to simply return or get the value of an object’s private variable to the user without the user directly accessing the private variable.

So, the private variable is this _author (1) that gets set when you construct the object (2).

And then when we do get writer, it’s going to return this ._author. (3)

So, you never actually interact directly with this variable, "._author", (3)

but it’s going to get the writer(4) which is the author (3) here.

 

And when you’re setting, it’s the same.

So, you’re never interacting with the _author, but you can set that with the writer setter.

 

This change could invoke calculations or even overriding the previous value completely. ??

So, you can have any number of code lines in this setter to ultimately maybe do different calculations before you set it or calculations before you get the property.

*/

class Book {

constructor(author) { // - (2)

this._author = author; // - (1)

}

// getter

get writer(){ // - (4)

return this._author; // - (3)

}

// setter

set writer(updatedAuthor){

this._author = updateAuthor;

}

}

 

/*

when we construct the class,

it’s going to accept Fahrenheit temperature,

but we're going to create a getter and setter in the class to obtain the temperature in Celsius.

*/

function makeClass() {

class Thermostat {

constructor(temp) { // - (1)

/*

this._temp :

Now within this constructor, we're going to set a private variable. this._temp.

So, the word this just means that this variable is only accessible within this class here.

And whenever you start a variable with an _, that’s going to generally signify that it’s a private variable.

That you’re not supposed to access it outside of that scope or outside of that class.

*/

/*

this._temp = temp; (X)

5/9 * (temp -32);

So, we're going to set the temp.

And we're not going to just put this._temp = temp because it’s passed in as a Fahrenheit

and we want to convert it to Celsius.

I just happen to have the equation for Celsius, so it’s 5/9 * (temp – 32).

*/

this._temp = 5/9 * (temp -32);

}

get temperature() {

/*

And we're just going to return this._temp.

Which now it’s in Celsius because we're storing the value in Celsius

even though the thermostat is created in Fahrenheit.

*/

return this._temp;

}

set temperature(updatedTemp) {

this._temp = updatedTemp;

}

}

return Thermostat;

}

 

const Thermostat = makeClass();

/*

So, when you’re instantiating an object you always use the new keyword.

new thermostat, that’s this. And we're passing in 76.

That goes into the constructor, the temp. - (1)

And so we do this calculation to convent that Fahrenheit to the Celsius in this local variable here.

*/

const thermos = new Thermostat(76);

/*

So, thermos.temperature is going to use the getter, get temperature, and it’s going to return this._temp.

So, a key thing to look at is that there are now parenthesis after this (thermos.).

So, generally, if something is a function, you would see parenthesis after the function name,

but if it’s a variable or a property name, it’s going to not have parenthesis.

So, getters and setters are accessed similar to properties.

*/

let temp = thermos.temperature;

thermos.temperature = 26;

temp = thermos.temperature;

console.log(temp);

 

// [Understand the Differences Between import and require]

/*



const cap = capitalizeString("hello!");

 

console.log(cap);

 

*/

 

//

/*

 

import { capitalizeString } from "./string_function"

const cap = capitalizeString("hello!");

 

console.log(cap);

 

*/