Web Unit 1 Sprint 1 Module 2

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

var a = 10; if (a === 10) { console.log("it's true"); } else { console.log("it's false"); } What will the output of the above input statement be?

"it's true"

How would one utilize the Math object for basic mathematical operations such as generating a random number or rounding?

.

What would the output of the following loop be? for(let i = 0; i < 10; i++){ console.log(i); }

0 1 2 3 4 5 6 7 8 9

What Is a While Loop?

A while loop has lower overhead between the two iteration structures. The loop consists of the keyword while followed by an expression and curly braces. The contents of the loop — what is between the curly braces — are executed as long as the expression evaluates to true. while(count < 10) { console.log(count); } Now, the example above is incomplete because a while loop needs a way to eventually exit the loop. Normally, this is done by modifying the variable in the expression. let count = 1; while(count < 10) { console.log(count); count++; }

let

Enter let. let is a new ES6 variable keyword. This will assign a variable much like var, but with a little bit different behavior. Most notably, it differs by creating "block level scope". For our purposes at the moment, let and var function almost exactly the same. When we get to writing functions and loops, we can start to use let to our advantage. let firstName = 'Alice'; firstName = 'Bob';

Truthiness

In these lessons, we have talked a lot about the Boolean values, true and false. When using an if statement or other statements that expect a Boolean value (such as the !, NOT), if the expression given is not a Boolean value, JavaScript will do something called type coercion and transform whatever is given into a Boolean value. This is known as "truthy" and "falsey" - yes, seriously. Every data type has some truthiness to it. Here are some examples: // items that are interpreted as true true 1 ' ' [] // an array, you'll learn more about this later {} // an object, you'll learn more about this later function() {} // items that are interpreted as false false 0 undefined null ''

Standard Math Operators

JavaScript can preform any standard operations - addition (+), subtraction (-), multiplication (*), and division (/) on integers and strings. There are dozens of practical applications of this, mathematical operations being just the beginning. 1 + 1; // returns 2 2 * 2; // returns 4 2 - 2; // returns 0 2 / 2; // returns 1 const num1 = 2 const num2 = 2 num1 + num2 // returns 4 const string1 = 'My name is' const string2 = 'Bob' string1 + string2 // returns 'My name is Bob'

JavaScript vs Java (and other languages)

Keep in mind; JavaScript is not the same as Java. Although they share similar names (this was, unfortunately, considered a good thing by JavaScript's early pioneers), that is where the similarities end. The creators of JavaScript wanted to borrow concepts from other programming languages, such as Scheme, Java, and C. Those with backgrounds in other languages may see things that look very familiar, mainly the use of classes and Object-Oriented Programming (OOP) architecture. However, remember that JavaScript is not a "true" OOP language, and many things you may be familiar with from another language won't work with JavaScript. JavaScript is considered a 'loosely' typed language, in which types do exist, but they are not enforced. You do not have to declare a type when creating a variable or an array, for instance.

Math.round, Math.floor, Math.ceil

Math also has methods that will round numbers for us. .round will round a number to the nearest whole number. .floor will always round a number down to the nearest whole number. .ceil will always round up to the nearest whole number. Math.round(6.5) // returns 7 Math.round(6.45) // returns 6 Math.floor(6.999) // returns 6 Math.ceil(6.0001) // returns 7

Primitive Data Types (String, Number, Boolean)

Primitive data types, also known as basic data types, are the most straightforward data types in JavaScript. They're sort of like primary colors in that all other data types (which we will learn about in later lessons) are made of these types.

%

Something you may not have seen before is the modulo operator (%). This math operator will divide two numbers (integers or floats) and return only the remainder. For example, 10 / 3 is 3 with a remainder of 1, so 10 % 3 (read as '10 mod 3') will return 1 . 21 % 5; // returns 1 21 % 6; // returns 3 21 % 7; // returns 0

Strings

Strings are blocks of text. They will always be defined with quotation marks around them, either single or double. Any text with quotes around it (even numbers) is strings. const dog = 'fido'; const string = '2';

What is the ideal scenario for if/Else Statements?

The if...else is a type of conditional statement that will execute a block of code when the condition in the if statement is truthy. If the condition is falsy, then the else block will be executed. Truthy and falsy values are converted to true or false in if statements. if (condition is true) { // code is executed } else { // code is executed }There will be times where you will want to write commands that handle different decisions in your code. For example, if you are coding a bot, you can have it respond with different messages based on a set of commands it receives. In this article, I will explain what an if...else statement is and provide code examples. We will also look at the conditional (ternary) operator which you can use as a shorthand for the if...else statement. What is an if...else statement in JavaScript? The if...else is a type of conditional statement that will execute a block of code when the condition in the if statement is truthy. If the condition is falsy, then the else block will be executed. Truthy and falsy values are converted to true or false in if statements. if (condition is true) { // code is executed } else { // code is executed } Any value that is not defined as falsy would be considered truthy in JavaScript. Here is a list of falsy values: false 0 (zero) -0 (negative zero) 0n (BigInt zero) "", '', `` (empty string) null undefined NaN (not a number) Examples of if...else statements in JavaScript In this example, the condition for the if statement is true so the message printed to the console would be "Nick is an adult." const age = 18; if (age >= 18) { console.log("Nick is an adult."); } else { console.log("Nick is a child."); } Screen-Shot-2021-08-09-at-3.18.12-AM But if I change the age variable to be less than 18, then the condition would be false and the code would execute the else block instead. const age = 12; if (age >= 18) { console.log("Nick is an adult."); } else { console.log("Nick is a child."); } Screen-Shot-2021-08-09-at-3.17.07-AM Examples of multiple conditions (if...else if...else statements) in JavaScript There will be times where you want to test multiple conditions. That is where the else if block comes in. if (condition 1 is true) { // code is executed } else if (condition 2 is true) { // code is executed } else { // code is executed } When the if statement is false, the computer will move onto the else if statement. If that is also false, then it will move onto the else block. In this example, the else if block would be executed because Alice is between the ages of 18 and 21. const age = 18; if (age < 18) { console.log("Alice is under 18 years old."); } else if (age >= 18 && age <= 21) { console.log("Alice is between the ages of 18 and 21."); } else { console.log("Alice is over 21 years old."); } Screen-Shot-2021-08-09-at-3.33.33-AM When to use switch statements over if...else statements? There are times in JavaScript where you might consider using a switch statement instead of an if else statement. switch statements can have a cleaner syntax over complicated if else statements. Take a look at the example below - instead of using this long if else statement, you might choose to go with an easier to read switch statement. const pet = "dog"; if (pet === "lizard") { console.log("I own a lizard"); } else if (pet === "dog") { console.log("I own a dog"); } else if (pet === "cat") { console.log("I own a cat"); } else if (pet === "snake") { console.log("I own a snake"); } else if (pet === "parrot") { console.log("I own a parrot"); } else { console.log("I don't own a pet"); } const pet = "dog"; switch (pet) { case "lizard": console.log("I own a lizard"); break; case "dog": console.log("I own a dog"); break; case "cat": console.log("I own a cat"); break; case "snake": console.log("I own a snake"); break; case "parrot": console.log("I own a parrot"); break; default: console.log("I don't own a pet"); break; } switch statements will not be appropriate to use in all situations. But if you feel like the if else statements are long and complicated, then a switch statement could be an alternative option. The logical AND (&&) operator and if...else statements in JavaScript In the logical AND (&&) operator, if both conditions are true, then the if block will be executed. If one or both of the conditions are false, then the else block will be executed. In this example, since age is greater than 16 and the ownsCar variable is true, the if block will run. The message printed to the console will be "Jerry is old enough to drive and has his own car." const age = 17; const ownsCar = true; if (age >= 16 && ownsCar) { console.log("Jerry is old enough to drive and has his own car."); } else { console.log("Jerry does not drive."); } Screen-Shot-2021-08-09-at-4.22.49-AM If I change the age variable to be less than 16, then both conditions are no longer true and the else block would be executed instead. const age = 13; const ownsCar = true; if (age >= 16 && ownsCar) { console.log("Jerry is old enough to drive and has his own car."); } else { console.log("Jerry does not drive."); } Screen-Shot-2021-08-09-at-4.20.19-AM The logical OR (||) operator and if...else statements in JavaScript In the logical OR (||) operator, if one or both of the conditions are true, then the code inside the if statement will execute. In this example, even though the isSale variable is set to false, the code inside the if block will still execute because the boyfriendIsPaying variable is set to true. const boyfriendIsPaying = true; const isSale = false; if (boyfriendIsPaying || isSale) { console.log("Jesse will go shopping."); } else { console.log("Jesse will not go shopping."); } Screen-Shot-2021-08-09-at-4.40.36-AM If I were to change the value of the boyfriendIsPaying variable to false, then the else block would execute because both conditions are false. const boyfriendIsPaying = false; const isSale = false; if (boyfriendIsPaying || isSale) { console.log("Jesse will go shopping."); } else { console.log("Jesse will not go shopping."); } Screen-Shot-2021-08-09-at-4.42.12-AM The logical NOT (!) operator and if...else statements in JavaScript The logical NOT (!) operator will take something that is true and make it false. It will also take something that is false and make it true. We can modify the example from earlier to use the ! operator to make the boyfriendIsPaying variable false. Since both conditions are false, the else block would be executed. const boyfriendIsPaying = true; const isSale = false; if (!boyfriendIsPaying || isSale) { console.log("Jesse will go shopping."); } else { console.log("Jesse will not go shopping."); } Screen-Shot-2021-08-09-at-5.02.04-AM Conditional (ternary) operator in JavaScript If you have a short if else statement, then you might choose to go with the ternary operator. The word ternary means something composed of three parts. This is the basic syntax for a ternary operator: condition ? if condition is true : if condition is false The condition goes before the ? mark and if it is true, then the code between the ? mark and : would execute. If the condition is false, then the code after the : would execute. In this example, since age is greater than 18, then the message to the console would be "Can vote". const age = 32; const citizen = age >= 18 ? "Can vote" : "Cannot vote"; console.log(citizen); Screen-Shot-2021-08-09-at-5.25.14-AM This is what the code would look like using an if else statement: const age = 32; let citizen; if (age >= 18) { citizen = "Can vote"; } else { citizen = "Cannot vote"; } console.log(citizen); Conclusion if else statements will execute a block of code when the condition in the if statement is truthy. If the condition is falsy, then the else block will be executed. There will be times where you want to test multiple conditions and you can use an if...else if...else statement. If you feel like the if else statement is long and complicated, then a switch statement could be an alternative option. Using logical operators to test multiple conditions can replace nested if else statements. The ternary operator can be used to write shorter code for a simple if else statement.

If a variable is declared with var, what happens when you attempt to reassign it?

The value will be updated

Undefined and Null

There are a couple of JavaScript objects that don't really fit into any type. Those are the values undefined and null. You will get undefined when you are looking for a variable that does not have a value yet. undefined simply means what you are asking for does not exist. console.log(unkownVar); // undefined null is an object that we, the developers, set when we want to tell other developers that the item they are looking for exists, but there is no value associated with it. While undefined is set by the JavaScript language, null is set by the developer. If you ever receive null, it means that another developer has set that value to null. let phoneNumber = '123-456-7890'; phoneNumber = null; phoneNumber; // null One last thing to note, neither undefined nor null are strings. They are written just as they are without quotes around them, like a Boolean.

When Not To Use Arrow Functions

There is a time and place for arrow functions. Here is a list of times you should not be using them: Event handlers (Unless they are inside a class constructor!) Object methods Prototype methods Anytime you need to use arguments Object

Follow Along

To allow our users to flip the coin a variable number of times, we can use a parameter, repeat. function flip(repeat){ // add parameter } We will reference repeat into our conditional expression which will cause the loop to run a variable number of times. function flip(repeat) { for (let i = 0; i < repeat; i++) { // use parameter as conditional expression } } When we run the function, we'll substitute the variable repeat for a number. For example, substituting repeat for 10, would flip the coin 10 times. flip(10); // <- will flip coin 10 times Our final product will look something like this. Play around with the repeat argument here until you can clearly explain how the argument changes the function's output.

Why use else-if?

You may be thinking to yourself, "Why not just use a bunch of different if statements? Why use else-if?" That is a valid question, and sometimes that is the right approach to take. It is up to you to decide which is the right approach. Remember, only one of the statements will be run when using a block of conditionals, even if multiple statements are true. The same can not be said for multiple if statements; they will run if true regardless of statements before and after. Take this example: const age = 21; if(age > 20) { console.log('older than 20!'); } else if (age > 15){ console.log('older than 15!'); } else { console.log('younger than 15!'); } In the above example only older than 20! will be logged even though both the if statement and else if statement were true. const age = 21; if(age > 20) { console.log('older than 20!'); } if (age > 15) { console.log('older than 15!'); } if (age <= 15) { console.log('younger than 15!'); } In the above example, the first and second if statements would be logged because both of them are true. As you can see, it will be up to you to decide if you want to have multiple actions based on your data or just one action.

function myFunction(){ alert('hello'); }; How would you invoke the function above?

myFunction();

To recap:

var can be re-assigned and changed. let can be re-assigned but not changed. const cannot be re-assigned nor changed. Because these three keywords achieve the same thing (storing data in memory and assigning that data a 'key' that can be used for access) but behave very differently, there are places in this world for all three. And of course, as with everything, there are some other intricacies to learn about the let const and var keywords that we didn't cover here today. BloomTech Rule of Thumb is when defining/declaring variables use const until you can't, then use let. We highly recommend researching the differences between var, let and const in terms of their scoping rules as well. We'll cover more on this later on when talking about function vs. block scoping. But for now, I'll point you towards the Dig Deeper section's link, How let and const are scoped in JavaScript, for some further understanding here.

module 2 guided project

// variables // use const until you can't, then use let; don't use var // global // redefine and redeclare // we don't really use var anymore // var dog1 = 'Lilly1'; // console.log(dog1); // dog1 = 'not Lilly1'; // console.log(dog1); // var dog1 = 'some other thing'; // console.log(dog1); // block-scoped {} // can't redefine // can't redeclare // const dog2 = 'Lilly2'; // dog2 = 'something else'; // const dog2 = 'something else'; // block-scoped {} // can redefine // can't redeclare // let dog3 = 'Lilly3'; // console.log(dog3); // dog3 = 'another dog'; // console.log(dog3); // let dog3 = 'another dog'; // global object // console.log(window); // math object // console.log(Math); // logical operators // && is 'AND' // || is 'OR' // ! bang operator, means 'NOT' // === is deep equality // == is non-type specific equality // = is the assignment operator; how you define variables // < > greater/less than // >= <= greater or equal to/less than or equal to // control flow - if/elseif/else statements or switch statements // pet grooming sorter; dogs under 10 lbs give a string 'pretty small dog haircut' // dogs bigger than 10 less than 50 give a string 'pretty medium dog haircut' // dogs bigger than 50 give a string 'pretty big dog haircut' // const dogWeight = 9; // '9' // const coatStyle = 'double'; // if(dogWeight < 10) { // if(coatStyle === 'short') { // console.log('Pretty small dog haircut for a short coat'); // } else if(coatStyle === 'double') { // console.log('Pretty small dog haircut for a double coat'); // } else { // console.log('Pretty small dog haircut'); // } // } else if(dogWeight >= 10 && dogWeight <= 50) { // console.log('Pretty medium dog haircut'); // } else if(dogWeight > 50) { // console.log('Pretty big dog haircut'); // } else { // console.log('Go see the manager, you have a weird dog.'); // } // for loop // first part is declaring your iterator variable; usually let i = 0; // second part is when you want the loop to stop // third part is how to handle the iterator variable after completion of a run through // let str = 0; // for (let i = 0; i < 9; i++) { // str = str + i; // console.log(str); // } // while loop // continues to run until the value in paren is false // let n = 0; // while (n < 3) { // n++; // console.log(n); // } // BREAKOUT ROOM CHALLENGE // console.log() the values in reverse order // how to access an array index: arrayValName[0] // const array = [1,2,3,4,5,6,7,8,9,10]; // for (let i = array.length - 1; i >= 0; i--) { // console.log(array[i]); // } // functions // parameters are like local variables; they only exist inside the function // arguments are how you associate a value to the parameter // you can only return one thing // you need to return something, otherwise it'll return undefined // function add(num1, num2, num3) { // // let num1 = somenumber; // console.log(num1); // console.log(num2); // console.log(num3); // return num1 + num2 + num3; // } // console.log(add(2, null, 1)); // BREAKOUT ROOM CHALLENGE // create a function that takes 2 params for dog weight and dog coat style // return unique strings for each case // dogCoatStyle can be short or long function groomer(dogWeight, dogCoatStyle) { if (dogWeight < 10 && dogCoatStyle === 'short') { return ("The small dog gets a bath and nails clipped!"); } else if(dogWeight < 10 && dogCoatStyle === 'long') { return("The small dog gets a bath and nails clipped plus haircut!"); } else if (dogWeight >= 10 && dogWeight <= 50 && dogCoatStyle === 'short') { return ("The medium dog gets a bath and nails clipped!"); } else if (dogWeight >= 10 && dogWeight <= 50 && dogCoatStyle === 'long') { return ("The medium dog gets a bath and nails clipped plus haircut!"); } else if (dogWeight > 50 && dogCoatStyle === 'short') { return ("The big dog gets a bath and nails clipped!"); } else if (dogWeight > 50 && dogCoatStyle === 'long') { return ("The big dog gets a bath and nails clipped plus haircut!"); } else { return ("Go see the manager, you have a weird dog."); } } console.log(groomer(59, 'long')); console.log(groomer(8, 'short')); console.log(groomer(24, 'short'));

let a = (2+3) * (4+5)What is the value of "a"

45

const

A const variable is a variable that cannot be changed later in the code. It's short for "constant." So in our example above, "Bob" could not be changed to "Alice" and would throw an error. const firstName = 'Alice' firstName = 'Bob' // <- this would cause an error This fixes the bug issue, but we know that sometimes variables do need to change - like the game's score. Is there a better solution?

Notes About Logical Operators

A couple things to note about logical operators. The expressions are evaluated in order, and the computer will skip any redundant expressions. In an && statement, if the first expression is false, the second expression will not be evaluated because BOTH expressions need to be true. Same for the || statement. If the first expression is true, the second will not be evaluated because there only needs to be one true statement to fulfill the requirements of the operator. Use parentheses. As we saw in the second ! operator example, we used parentheses to evaluate what was inside the parentheses FIRST, then applied the ! operator. We can wrap ANY expression in parentheses, and it will be evaluated before evaluating the expression as a whole.

What Is a For Loop?

A for loop is more structured than the while loop. The keyword for is used, followed by three statements: Initialization: Executed before the loop begins. Expression: Evaluated before each iteration, exits the loop when false. Increment: Executed at the end of each iteration. for(count=1; count < 10; count++) { console.log(count); } The increment does not have to be ++, but you'll see that the most often. So, in summary, the while loop has a looser syntax, and the for loop has a more rigid syntax. A while loop expects some sort of modification to the variable in the body, whereas everything is in the for loop's definition.

When would you use a For Loop versus a While Loop?

All for loops can be written as while loops, and vice-versa. Just use whichever loop seems more appropriate to the task at hand. In general, you should use a for loop when you know how many times the loop should run. If you want the loop to break based on a condition other than the number of times it runs, you should use a while loop For Loop: A for loop is an iteration method that is best used when you know the number of iterations ahead of time. It's always followed by the initialization, expression and increment statements. While Loop: A while loop is an iteration method that is best used when you don't know the number of iterations ahead of time. The contents of the loop are executed as long as the expression evaluates to true.

Arrow Function Expressions

Arrow functions are fancy looking function expressions with a major feature removed, the function keyword. We won't focus on why this is important right now, instead, we will start getting used to seeing the syntax of what an arrow function looks like: // function expression syntax // const add = function(a,b) { // console.log a + b; // } // arrow function expression syntax const add = (a,b) => { console.log(a + b); } add(2,4) // 6 You will notice that we removed the function keyword in front of our parameters and then added a => token behind the parameters. This is a pretty straightforward conversion! Syntactically, we didn't remove much, we lost a few characters in the word function and gained a =>. However, there are many sub-rules for syntax with arrow functions. Those sub-rules can create extremely streamlined syntax. This line of code is a good example. // streamlined arrow syntax const add = (a,b) => console.log(a + b); add(2,4); // 6 Wow, there are a lot of abstractions occurring there! We do not need our {} because they are redundant in the rules of arrow functions. You haven't seen return statements yet, but they, too, are not needed in arrow functions. It's fun to see how slim we can get, but a word of caution: stick with the simple conversion first and slowly step into using other syntactical sugar approaches as you progress. Often, developers will go too far with syntactical sugar, and the code becomes very hard to read. Arrow function expressions are great to use with array methods, for example, but may not be a great choice in many other places.

Parameters

As illustrated above, a function parameter will represent the data we pass into a function for use in the function. When we write a function, we assign the variable data names, even without knowing the data. We set these variables inside of the parentheses when we write the function. There is no limit to the number of parameters we can include in a function, but a comma must separate each variable name. We can then use these variables within our function just as we would any other variable. function myFunc( parameter1, parameter2) { // We can use parameter1 and parameter2 in this function just like a variable }

Infinite Loops

As mentioned, it is possible to write a loop such that it never ends. This is what we call an "Infinite Loop," and it will break your program. Take, for example, this loop: for (let i = 0; i >= 0; i++) { console.log(i); } Because our conditional expression will ALWAYS be true (i will never be less than 0) this loop will essentially run forever. This will break your program and may crash your web browser or computer.

Variables

At the heart of JavaScript are variables. A variable is a way to store, change and use data in code. To explain this concept, consider your favorite webpage: maybe it's Instagram, perhaps an online game. Although more than likely, there are many changing pieces on these pages - Instagram has likes and usernames, a video game has character selection, game score, and many more - every one of those changing bits of data is stored in a variable. The variable called score, for example, starts with 0 and changes every time you gather points in the game. Similarly, you might create a variable called greet and store the value "Hello World" to further simplify your program above to console.log(greet). The syntax to create a variable is first the keyword, a space, the name we are giving the variable, an equal sign, the value we are assigning the variable, and then a semicolon. (A note for those with previous programming knowledge: JavaScript is a loosely-typed language, meaning a variable can be set and reset to any type. Therefore, we do not need to declare its type when creating the variable.) There are three keywords used to declare variables -var, let, and const. Each keyword comes with slightly different use cases, mostly based on what happens when you change the variable's value. Some examples of syntax are below. var firstName = 'John'; let lastName = 'Smith'; const favoriteFood = 'Taco';

Booleans

Booleans are an important relic from the origins of computer science. It is a dichotomous concept that powers binary code, still the very core of computers. You may have seen binary code in the past (e.g., 0001 0110...). That is Boolean logic. The only booleans in JavaScript are true and false, traditionally written in lowercase letters. These variables are useful when you need to employ some kind of dichotomous (or "yes"/"no") logic in your code. const iLoveJavascript = true; const isThisaString = false; While Booleans look like strings, the lack of ' around the words indicates that the variable is a boolean and will work differently under the hood.

How to 'run' JavaScript

For this class, we will use a unique code sandbox program just like we did with the last lesson (CodePen), called repl.it (Links to an external site.) Links to an external site.This will allow us to write and edit our code and run it right in our browser window to see a real-time read-out. While this is one way to run your JavaScript, most JavaScript is run from a file with the extension of .js (e.g., fileName.js); and loaded into your browser via the script tag in your HTML. Being the de-facto language of the Internet, JavaScript can also be run directly within an Internet browser. So you can write all of the JavaScript you want and watch it run in real-time right in your browser by pressing F12 (for Windows) or Cmd+option+J (for Mac) (for Google Chrome). This will open up your console (we will learn more about the console later).

Introduction to Functions

Functions allow you, the developer, to repeat sections of code with just a single line. Consider, for a second, you want to "program" a robot to bake you cookies. A practical program, because you'd have cookies all the time! Code, without functions, might include steps like addFlour, addEggs, addChocolateChips, preheatOven, bake. A function could collect these steps into a container called bakeCookies(). Then, running bakeCookies() would produce the same, delicious result as the individual steps. We mentioned earlier that you never want to copy and paste code; this is true when you want to repeat one action and when you want to repeat a whole chunk of actions. In the case of the latter, we use functions. We can think of functions as small computer programs. Functions allow us to write code that will be used over and over again, keeping our code DRY ("Don't Repeat Yourself!"). Before we dive into syntax, study the following example and predict the output. function myFunc() { console.log('this is my function!') } myFunc() If you guessed that the output would be this is my function, congratulations - you are correct! Once you've declared a function, like myFunc it can be used over and over again to give the same, predictable result.

For Loops

Imagine you wanted to console.log() the phrase hello, world! 5 times. With your current knowledge, that would look something like this. This is just for illustration; please, never code like this. console.log("hello, world!"); console.log("hello, world!"); console.log("hello, world!"); console.log("hello, world!"); console.log("hello, world!"); In general, you should seldom have to copy and paste chunks of code. Not only is it a bad programming practice, but it is also time-consuming, and it leads to errors. Consider, for example, how much work it would be if you wanted to change "world" to someone's name. So how would you console.log() hello, world! five times? Using for loops! With a for loop, the above example could be reduced to the following. for (let i = 0; i < 5; i++) { // | declare a var | conditional expression | increment var| console.log("hello, world!"); } for loops are useful anytime you need to run the same block of code a certain number of times. Imagine you go to the store and want to buy 10 avocados. Instead of scanning each avocado one by one, the cashier will add the cost of one avocado to your total for each avocado you buy. In other words, for each avocado, add cost. This would result in adding cost 10 times. for loops have a unique syntax, similar to the if statement, but slightly more complex. First, we have the for keyword, followed by parentheses, and then open and close braces. Within the parentheses, we will need three things. First, we must declare a variable (usually i) as a starting point. Then, we will have a conditional expression. The loop will continue happening until this statement is false. Third, we will increment our variable, telling the loop a pattern to follow. Usually, the increment will be i++, meaning increase i by 1 every time the loop runs. All three of these statements are separated by a semicolon. for (let i = 0 ; i < 10 ; i++ ) { // | declare a var | conditional expression | increment var| console.log(i); } In this example, we see that we initially set our counter variable (i) to 0. After that, the loop will run, and each time it gets to the end, it will increase the counter by one. The for loop will then evaluate the conditional expression. If it is true, it will run again, but if it is false .it will stop running. Therefore, the return of the example above would be the following:

Comparison Operators

JavaScript has a number of comparison and logical operators, (> >= < <= === !==). These operators work just as they would in math: greater than, less than, greater than or equal to, and all the rest. We use these operators to evaluate two expressions. As the computer runs the code, the operator will return either a true (if the statement is true) or a false (if the statement is not true). 1 > 2; // false 2 < 3; // true 10 >= 10; // true 100 <= 1; // false The "triple equals" sign ( === ) must not be confused with a single equal sign (which indicates assigning a value to a variable). The triple equal will compare everything about the two items, including type, and return if they are precisely equal or not. (Something to note: there is also a "double equals" ( == ) sign which will compare two items, but it allows type coercion so a string and an integer can be considered equal (1 == '1' // true). Due to this, it is considered bad practice to use the double equal sign. We would like to see you always using the triple equal sign, and you will always see us using it.) 1 === 1; // true 1 === '1'; // false 'cat' === 'cat'; // true 'cat' === 'Cat'; // false The last comparison operator we would like to introduce you to has two parts: the "NOT" (!). When you see this, it will mean that we are asking the opposite of the expression (we will revisit the NOT operator later in this lesson). With that in mind, we can introduce the "not equals" ( !== ) sign. This will return true if the items are NOT equal to each other in any way. This, like the triple equal sign, takes type into account. 1 !== 1; // false 1 !== '1'; // true 'cat' !== 'cat'; // false 'cat' !== 'Cat'; // true

What is JavaScript and why do we use it?

JavaScript is a programming language that was first created in 1994 to add functionality and interactivity to a website. If we think back to our analogy of a web page as a house, we will remember that we said JavaScript is the electricity, plumbing, and gas. It is what makes the web page "run." JavaScript was originally designed to be used purely on the front end as a way for web developers to add functionality to their web pages, and in its early days, it did just that. Recently, the introduction of the "V8 engine" by Google has improved the speed and functionality of JS. That led to the development and release of exciting new front-end JavaScript frameworks and eventually Node.js, a way to run JavaScript on a server (back end). This new development has led to a resurgence of JavaScript. Now, JavaScript is one of the world's most widely-used programming languages. We can use JavaScript on the front end, back end, mobile, Internet of Things (IoT), game development, and anywhere a traditional programming language would be used. Though there are later versions, we will be focusing on and using JavaScript ES6 in this course because it is the most widely applicable.

Describe the difference between Javascript Parameters and Arguments?

JavaScript is one of the most popular programming languages out there for web development. The dynamic values passed in a JavaScript function can change when the function gets called in another location in the code. The keywords we use to name these data are parameters and arguments, but some developers confuse them. In this article, you will learn about parameters and arguments and what they are, along with where and when to use them. Table of Contents Introduction to JavaScript functions How to use Parameters and Arguments in a function The power of arguments Conclusion Introduction to JavaScript Functions One of the fundamental building blocks in JavaScript programming is a function. It's a block of code designed to perform a particular task. Functions are reusable code which you can use anywhere in your program. They eliminate the need to repeat the same code all the time. To use functions in a powerful way, you can pass values in a function to use them. Here is an example of a function: function add(){ return 2 + 3 } add() This is a function declaration, the name of the function is add, and it was called after the function with add() . The result of the function will be 5. Let's introduce parameters and arguments in the function. How to Use Parameters and Arguments in a Function Take a look at our function code now: function add(x, y){ return x + y } add(2, 3) We have introduced x and y here and changed the location of the 2 and 3. x and y are the parameters while 2 and 3 are the arguments here. A parameter is one of the variables in a function. And when a method is called, the arguments are the data you pass into the method's parameters. When the function is called with add(2, 3) the arguments 2 and 3 are assigned to x and y, respectively. This means that in the function, x will be replaced with 2 and y will be replaced with 3. If the function is called with a different argument, the same applies. Parameters are like placeholders for function arguments. The Power of Arguments We can use arguments more efficiently when we want to make functions more re-useable, or when we want to make calling functions inside another functions more powerful. Here is an example: function add(x, y){ return x + y } function multiply(a, b, c){ // a = 1, b = 2, c = 3 const num1 = add(a, b) // num1 = add(1, 2) = 3 const num2 = add(b, c) // num2 = add(2, 3) = 5 return num1 * num2 // 15 } multiply(1, 2, 3) // returns 15 The first function add() has two parameters, x and y. The function returns the addition of the two parameters. The second function multiply() has three parameters: inside the function, two variables are declared in it, num1 and num2. num1 will store the value of the result of add(a, b), and num2 will store the value of the result of add(b, c). At the end the multiply function will return the value of num1 multiplied by num2. multiply is called with three arguments which are 1, 2 and 3. add(a, b) will be add(1, 2) which will return 3. add(b, c) will be add(2, 3) which will return 5. num1 will have the value of 3 while num2 will be 5. num1 * num2 will return 15. Arguments are passed in the multiply function which are also used as arguments for the add function. Conclusion Using parameters and arguments can be confusing at times, especially if you are just learning them. But if you first properly learn what a function is and how it works, you will understand parameters and arguments easily. Thanks for reading this article. If you enjoyed it, consider sharing it to help other developers.

What is the purpose of a function in Javascript?

JavaScript provides functions similar to most of the scripting and programming languages. In JavaScript, a function allows you to define a block of code, give it a name and then execute it as many times as you want. A JavaScript function can be defined using function keyword. Syntax: //defining a function function <function-name>() { // code to be executed }; //calling a function <function-name>(); The following example shows how to define and call a function in JavaScript. Example: Define and Call a Function function ShowMessage() { alert("Hello World!"); } ShowMessage(); Try it In the above example, we have defined a function named ShowMessage that displays a popup message "Hello World!". This function can be execute using () operator e.g. ShowMessage(). Functions are one of the fundamental building blocks in JavaScript. A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output. To use a function, you must define it somewhere in the scope from which you wish to call it.Functions are one of the fundamental building blocks in JavaScript. A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output. To use a function, you must define it somewhere in the scope from which you wish to call it.Defining functions Function declarations A function definition (also called a function declaration, or function statement) consists of the function keyword, followed by: The name of the function. A list of parameters to the function, enclosed in parentheses and separated by commas. The JavaScript statements that define the function, enclosed in curly brackets, { /* ... */ }. For example, the following code defines a simple function named square: function square(number) { return number * number; } Copy to Clipboard The function square takes one parameter, called number. The function consists of one statement that says to return the parameter of the function (that is, number) multiplied by itself. The statement return specifies the value returned by the function: return number * number; Copy to Clipboard Parameters are essentially passed to functions by value — so if the code within the body of a function assigns a completely new value to a parameter that was passed to the function, the change is not reflected globally or in the code which called that function. When you pass an object as a parameter, if the function changes the object's properties, that change is visible outside the function, as shown in the following example: function myFunc(theObject) { theObject.make = 'Toyota'; } const mycar = { make: 'Honda', model: 'Accord', year: 1998, }; // x gets the value "Honda" const x = mycar.make; // the make property is changed by the function myFunc(mycar); // y gets the value "Toyota" const y = mycar.make; Copy to Clipboard When you pass an array as a parameter, if the function changes any of the array's values, that change is visible outside the function, as shown in the following example: function myFunc(theArr) { theArr[0] = 30; } const arr = [45]; console.log(arr[0]); // 45 myFunc(arr); console.log(arr[0]); // 30 Copy to Clipboard Function expressions While the function declaration above is syntactically a statement, functions can also be created by a function expression. Such a function can be anonymous; it does not have to have a name. For example, the function square could have been defined as: const square = function (number) { return number * number; } const x = square(4); // x gets the value 16 Copy to Clipboard However, a name can be provided with a function expression. Providing a name allows the function to refer to itself, and also makes it easier to identify the function in a debugger's stack traces: const factorial = function fac(n) { return n < 2 ? 1 : n * fac(n - 1); } console.log(factorial(3)) Copy to Clipboard Function expressions are convenient when passing a function as an argument to another function. The following example shows a map function that should receive a function as first argument and an array as second argument: function map(f, a) { const result = new Array(a.length); for (let i = 0; i < a.length; i++) { result[i] = f(a[i]); } return result; } Copy to Clipboard In the following code, the function receives a function defined by a function expression and executes it for every element of the array received as a second argument: function map(f, a) { const result = new Array(a.length); for (let i = 0; i < a.length; i++) { result[i] = f(a[i]); } return result; } const f = function (x) { return x * x * x; } const numbers = [0, 1, 2, 5, 10]; const cube = map(f, numbers); console.log(cube); Copy to Clipboard Function returns: [0, 1, 8, 125, 1000]. In JavaScript, a function can be defined based on a condition. For example, the following function definition defines myFunc only if num equals 0: let myFunc; if (num === 0) { myFunc = function (theObject) { theObject.make = 'Toyota'; } } Copy to Clipboard In addition to defining functions as described here, you can also use the Function constructor to create functions from a string at runtime, much like eval(). A method is a function that is a property of an object. Read more about objects and methods in Working with objects. Calling functions Defining a function does not execute it. Defining it names the function and specifies what to do when the function is called. Calling the function actually performs the specified actions with the indicated parameters. For example, if you define the function square, you could call it as follows: square(5); Copy to Clipboard The preceding statement calls the function with an argument of 5. The function executes its statements and returns the value 25. Functions must be in scope when they are called, but the function declaration can be hoisted (appear below the call in the code). The scope of a function declaration is the function in which it is declared (or the entire program, if it is declared at the top level). The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function. The showProps() function (defined in Working with objects) is an example of a function that takes an object as an argument. A function can call itself. For example, here is a function that computes factorials recursively: function factorial(n) { if (n === 0 || n === 1) { return 1; } else { return n * factorial(n - 1); } } Copy to Clipboard You could then compute the factorials of 1 through 5 as follows: const a = factorial(1); // a gets the value 1 const b = factorial(2); // b gets the value 2 const c = factorial(3); // c gets the value 6 const d = factorial(4); // d gets the value 24 const e = factorial(5); // e gets the value 120 Copy to Clipboard There are other ways to call functions. There are often cases where a function needs to be called dynamically, or the number of arguments to a function vary, or in which the context of the function call needs to be set to a specific object determined at runtime. It turns out that functions are themselves objects — and in turn, these objects have methods. (See the Function object.) The call() and apply() methods can be used to achieve this goal. Function hoisting Consider the example below: console.log(square(5)); // 25 function square(n) { return n * n; } Copy to Clipboard This code runs without any error, despite the square() function being called before it's declared. This is because the JavaScript interpreter hoists the entire function declaration to the top of the current scope, so the code above is equivalent to: // All function declarations are effectively at the top of the scope function square(n) { return n * n; } console.log(square(5)); // 25 Copy to Clipboard Function hoisting only works with function declarations — not with function expressions. The code below will not work. console.log(square); // ReferenceError: Cannot access 'square' before initialization const square = function (n) { return n * n; } Function scope Variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function. However, a function can access all variables and functions defined inside the scope in which it is defined. In other words, a function defined in the global scope can access all variables defined in the global scope. A function defined inside another function can also access all variables defined in its parent function, and any other variables to which the parent function has access. // The following variables are defined in the global scope const num1 = 20; const num2 = 3; const name = 'Chamakh'; // This function is defined in the global scope function multiply() { return num1 * num2; } multiply(); // Returns 60 // A nested function example function getScore() { const num1 = 2; const num2 = 3; function add() { return `${name} scored ${num1 + num2}`; } return add(); } getScore(); // Returns "Chamakh scored 5" Copy to Clipboard Scope and the function stack Recursion A function can refer to and call itself. There are three ways for a function to refer to itself: The function's name arguments.callee An in-scope variable that refers to the function For example, consider the following function definition: const foo = function bar() { // statements go here } Copy to Clipboard Within the function body, the following are all equivalent: bar() arguments.callee() foo() A function that calls itself is called a recursive function. In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case). For example, consider the following loop: let x = 0; while (x < 10) { // "x < 10" is the loop condition // do stuff x++; } Copy to Clipboard It can be converted into a recursive function declaration, followed by a call to that function: function loop(x) { // "x >= 10" is the exit condition (equivalent to "!(x < 10)") if (x >= 10) { return; } // do stuff loop(x + 1); // the recursive call } loop(0); Copy to Clipboard However, some algorithms cannot be simple iterative loops. For example, getting all the nodes of a tree structure (such as the DOM) is easier via recursion: function walkTree(node) { if (node === null) { return; } // do something with node for (let i = 0; i < node.childNodes.length; i++) { walkTree(node.childNodes[i]); } } Copy to Clipboard Compared to the function loop, each recursive call itself makes many recursive calls here. It is possible to convert any recursive algorithm to a non-recursive one, but the logic is often much more complex, and doing so requires the use of a stack. In fact, recursion itself uses a stack: the function stack. The stack-like behavior can be seen in the following example: function foo(i) { if (i < 0) { return; } console.log(`begin: ${i}`); foo(i - 1); console.log(`end: ${i}`); } foo(3); // Logs: // begin: 3 // begin: 2 // begin: 1 // begin: 0 // end: 0 // end: 1 // end: 2 // end: 3 Copy to Clipboard Nested functions and closures You may nest a function within another function. The nested (inner) function is private to its containing (outer) function. It also forms a closure. A closure is an expression (most commonly, a function) that can have free variables together with an environment that binds those variables (that "closes" the expression). Since a nested function is a closure, this means that a nested function can "inherit" the arguments and variables of its containing function. In other words, the inner function contains the scope of the outer function. To summarize: The inner function can be accessed only from statements in the outer function. The inner function forms a closure: the inner function can use the arguments and variables of the outer function, while the outer function cannot use the arguments and variables of the inner function. The following example shows nested functions: function addSquares(a, b) { function square(x) { return x * x; } return square(a) + square(b); } const a = addSquares(2, 3); // returns 13 const b = addSquares(3, 4); // returns 25 const c = addSquares(4, 5); // returns 41 Copy to Clipboard Since the inner function forms a closure, you can call the outer function and specify arguments for both the outer and inner function: function outside(x) { function inside(y) { return x + y; } return inside; } const fnInside = outside(3); // Think of it like: give me a function that adds 3 to whatever you give it const result = fnInside(5); // returns 8 const result1 = outside(3)(5); // returns 8 Copy to Clipboard Preservation of variables Notice how x is preserved when inside is returned. A closure must preserve the arguments and variables in all scopes it references. Since each call provides potentially different arguments, a new closure is created for each call to outside. The memory can be freed only when the returned inside is no longer accessible. This is not different from storing references in other objects, but is often less obvious because one does not set the references directly and cannot inspect them. Multiply-nested functions Functions can be multiply-nested. For example: A function (A) contains a function (B), which itself contains a function (C). Both functions B and C form closures here. So, B can access A, and C can access B. In addition, since C can access B which can access A, C can also access A. Thus, the closures can contain multiple scopes; they recursively contain the scope of the functions containing it. This is called scope chaining. (The reason it is called "chaining" is explained later.) Consider the following example: function A(x) { function B(y) { function C(z) { console.log(x + y + z); } C(3); } B(2); } A(1); // Logs 6 (which is 1 + 2 + 3) Copy to Clipboard In this example, C accesses B's y and A's x. This can be done because: B forms a closure including A (i.e., B can access A's arguments and variables). C forms a closure including B. Because C's closure includes B and B's closure includes A, then C's closure also includes A. This means C can access both B and A's arguments and variables. In other words, C chains the scopes of B and A, in that order. The reverse, however, is not true. A cannot access C, because A cannot access any argument or variable of B, which C is a variable of. Thus, C remains private to only B. Name conflicts When two arguments or variables in the scopes of a closure have the same name, there is a name conflict. More nested scopes take precedence. So, the innermost scope takes the highest precedence, while the outermost scope takes the lowest. This is the scope chain. The first on the chain is the innermost scope, and the last is the outermost scope. Consider the following: function outside() { const x = 5; function inside(x) { return x * 2; } return inside; } outside()(10); // returns 20 instead of 10 Copy to Clipboard The name conflict happens at the statement return x * 2 and is between inside's parameter x and outside's variable x. The scope chain here is {inside, outside, global object}. Therefore, inside's x takes precedences over outside's x, and 20 (inside's x) is returned instead of 10 (outside's x). Closures Closures are one of the most powerful features of JavaScript. JavaScript allows for the nesting of functions and grants the inner function full access to all the variables and functions defined inside the outer function (and all other variables and functions that the outer function has access to). However, the outer function does not have access to the variables and functions defined inside the inner function. This provides a sort of encapsulation for the variables of the inner function. Also, since the inner function has access to the scope of the outer function, the variables and functions defined in the outer function will live longer than the duration of the outer function execution, if the inner function manages to survive beyond the life of the outer function. A closure is created when the inner function is somehow made available to any scope outside the outer function. const pet = function (name) { // The outer function defines a variable called "name" const getName = function () { // The inner function has access to the "name" variable of the outer function return name; } return getName; // Return the inner function, thereby exposing it to outer scopes } const myPet = pet('Vivie'); myPet(); // Returns "Vivie" Copy to Clipboard It can be much more complex than the code above. An object containing methods for manipulating the inner variables of the outer function can be returned. const createPet = function (name) { let sex; const pet = { // setName(newName) is equivalent to setName: function (newName) // in this context setName(newName) { name = newName; }, getName() { return name; }, getSex() { return sex; }, setSex(newSex) { if (typeof newSex === 'string' && (newSex.toLowerCase() === 'male' || newSex.toLowerCase() === 'female')) { sex = newSex; } } }; return pet; } const pet = createPet('Vivie'); pet.getName(); // Vivie pet.setName('Oliver'); pet.setSex('male'); pet.getSex(); // male pet.getName(); // Oliver Copy to Clipboard In the code above, the name variable of the outer function is accessible to the inner functions, and there is no other way to access the inner variables except through the inner functions. The inner variables of the inner functions act as safe stores for the outer arguments and variables. They hold "persistent" and "encapsulated" data for the inner functions to work with. The functions do not even have to be assigned to a variable, or have a name. const getCode = (function () { const apiCode = '0]Eal(eh&2'; // A code we do not want outsiders to be able to modify... return function () { return apiCode; }; })(); getCode(); // Returns the apiCode Copy to Clipboard Note: There are a number of pitfalls to watch out for when using closures! If an enclosed function defines a variable with the same name as a variable in the outer scope, then there is no way to refer to the variable in the outer scope again. (The inner scope variable "overrides" the outer one, until the program exits the inner scope. It can be thought of as a name conflict.) const createPet = function (name) { // The outer function defines a variable called "name". return { setName(name) { // The enclosed function also defines a variable called "name". name = name; // How do we access the "name" defined by the outer function? } } } Using the arguments object The arguments of a function are maintained in an array-like object. Within a function, you can address the arguments passed to it as follows: arguments[i] Copy to Clipboard where i is the ordinal number of the argument, starting at 0. So, the first argument passed to a function would be arguments[0]. The total number of arguments is indicated by arguments.length. Using the arguments object, you can call a function with more arguments than it is formally declared to accept. This is often useful if you don't know in advance how many arguments will be passed to the function. You can use arguments.length to determine the number of arguments actually passed to the function, and then access each argument using the arguments object. For example, consider a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows: function myConcat(separator) { let result = ''; // initialize list // iterate through arguments for (let i = 1; i < arguments.length; i++) { result += arguments[i] + separator; } return result; } Copy to Clipboard You can pass any number of arguments to this function, and it concatenates each argument into a string "list": // returns "red, orange, blue, " myConcat(', ', 'red', 'orange', 'blue'); // returns "elephant; giraffe; lion; cheetah; " myConcat('; ', 'elephant', 'giraffe', 'lion', 'cheetah'); // returns "sage. basil. oregano. pepper. parsley. " myConcat('. ', 'sage', 'basil', 'oregano', 'pepper', 'parsley'); Copy to Clipboard Note: The arguments variable is "array-like", but not an array. It is array-like in that it has a numbered index and a length property. However, it does not possess all of the array-manipulation methods. See the Function object in the JavaScript reference for more information. Function parameters There are two special kinds of parameter syntax: default parameters and rest parameters. Default parameters In JavaScript, parameters of functions default to undefined. However, in some situations it might be useful to set a different default value. This is exactly what default parameters do. In the past, the general strategy for setting defaults was to test parameter values in the body of the function and assign a value if they are undefined. In the following example, if no value is provided for b, its value would be undefined when evaluating a*b, and a call to multiply would normally have returned NaN. However, this is prevented by the second line in this example: function multiply(a, b) { b = typeof b !== 'undefined' ? b : 1; return a * b; } multiply(5); // 5 Copy to Clipboard With default parameters, a manual check in the function body is no longer necessary. You can put 1 as the default value for b in the function head: function multiply(a, b = 1) { return a * b; } multiply(5); // 5 Copy to Clipboard For more details, see default parameters in the reference. Rest parameters The rest parameter syntax allows us to represent an indefinite number of arguments as an array. In the following example, the function multiply uses rest parameters to collect arguments from the second one to the end. The function then multiplies these by the first argument. function multiply(multiplier, ...theArgs) { return theArgs.map((x) => multiplier * x); } const arr = multiply(2, 1, 2, 3); console.log(arr); // [2, 4, 6] Copy to Clipboard Arrow functions An arrow function expression (also called a fat arrow to distinguish from a hypothetical -> syntax in future JavaScript) has a shorter syntax compared to function expressions and does not have its own this, arguments, super, or new.target. Arrow functions are always anonymous. Two factors influenced the introduction of arrow functions: shorter functions and non-binding of this. Shorter functions In some functional patterns, shorter functions are welcome. Compare: const a = [ 'Hydrogen', 'Helium', 'Lithium', 'Beryllium' ]; const a2 = a.map(function(s) { return s.length; }); console.log(a2); // [8, 6, 7, 9] const a3 = a.map((s) => s.length); console.log(a3); // [8, 6, 7, 9] Copy to Clipboard No separate this Until arrow functions, every new function defined its own this value (a new object in the case of a constructor, undefined in strict mode function calls, the base object if the function is called as an "object method", etc.). This proved to be less than ideal with an object-oriented style of programming. function Person() { // The Person() constructor defines `this` as itself. this.age = 0; setInterval(function growUp() { // In nonstrict mode, the growUp() function defines `this` // as the global object, which is different from the `this` // defined by the Person() constructor. this.age++; }, 1000); } const p = new Person(); Copy to Clipboard In ECMAScript 3/5, this issue was fixed by assigning the value in this to a variable that could be closed over. function Person() { const self = this; // Some choose `that` instead of `self`. // Choose one and be consistent. self.age = 0; setInterval(function growUp() { // The callback refers to the `self` variable of which // the value is the expected object. self.age++; }, 1000); } Copy to Clipboard Alternatively, a bound function could be created so that the proper this value would be passed to the growUp() function. An arrow function does not have its own this; the this value of the enclosing execution context is used. Thus, in the following code, the this within the function that is passed to setInterval has the same value as this in the enclosing function: function Person() { this.age = 0; setInterval(() => { this.age++; // `this` properly refers to the person object }, 1000); } const p = new Person(); Copy to Clipboard Predefined functions JavaScript has several top-level, built-in functions: eval() The eval() method evaluates JavaScript code represented as a string. isFinite() The global isFinite() function determines whether the passed value is a finite number. If needed, the parameter is first converted to a number. isNaN() The isNaN() function determines whether a value is NaN or not. Note: coercion inside the isNaN function has interesting rules; you may alternatively want to use Number.isNaN() to determine if the value is Not-A-Number. parseFloat() The parseFloat() function parses a string argument and returns a floating point number. parseInt() The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems). decodeURI() The decodeURI() function decodes a Uniform Resource Identifier (URI) previously created by encodeURI or by a similar routine. decodeURIComponent() The decodeURIComponent() method decodes a Uniform Resource Identifier (URI) component previously created by encodeURIComponent or by a similar routine. encodeURI() The encodeURI() method encodes a Uniform Resource Identifier (URI) by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters). encodeURIComponent() The encodeURIComponent() method encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters). escape() The deprecated escape() method computes a new string in which certain characters have been replaced by a hexadecimal escape sequence. Use encodeURI or encodeURIComponent instead. unescape() The deprecated unescape() method computes a new string in which hexadecimal escape sequences are replaced with the character that it represents. The escape sequences might be introduced by a function like escape. Because unescape() is deprecated, use decodeURI() or decodeURIComponent instead

Function Declaration Hoisting

JavaScript utilizes a two-pass compiler when executing lines of code that we write. This means that anytime we run JavaScript in the browser, the browser will take two passes over our code. The first pass builds up references to all of our code, declaring variables and functions and the like. The second pass applies values to the references that were found, thus actually running the code. Function declarations are defined in the first pass. The compiler is made aware of the function declaration and adds it to the top of the execution order for your code. This concept of putting a function higher in the execution order for later use is known as hoisting. What does this mean for you? It means that function declarations can be invoked before they are defined! Let's take a look at an example: // This code is valid above the definition! console.log(add(2,4)) // 6 function add(a,b){ console.log(a + b); } This is odd behavior to developers new to JavaScript. It can be used as a feature or introduce bugs if not understood properly. Be aware that hoisting applies to function declarations and not function expressions or arrow functions.

Function Syntax

Just like we used const, let, and var to declare variables, we use the keyword function to declare functions. function myFunc() { // tasks go here } The function keyword tells whatever is running your program that what follows is a function and treats it as such. After that comes the name - we like to give functions names that describe what they do, like logsHello. Then comes an open and a close parenthesis, (). And finally, open and close brackets. In between these brackets is where all of our function code will go. function logsHello() { console.log('hello'); } logsHello(); In this example, we declare a function logsHello and set it up to console.log 'hello'. In order to run this function, we need to write or invoke its name with the parentheses after it, logsHello(). This is the syntax to run (aka. call) a function. A function always needs parentheses to run.

Follow Along

Let's create an algorithm to flip a coin and console.log() "heads" or "tails." To do this, we'll generate a random 0 or 1 and write a conditional if statement to return the heads or tails reading. First lets set up a variable called coinFlip and give it a randomly assigned 0 or 1 value. To do this we need to use two methods of the Math object - Math.round() and Math.random(). Math.random() generates a random number between 0 and 1, and Math.round() rounds that decimal to the nearest whole number. In the syntax below, Javascript first reads Math.random() and generates a random number, for example, 0.56324. Then it reads Math.round() and applies it to the random number, giving an integer, in this example, a 1. var coinFlip = Math.round(Math.random()); Add this to your repl.it and console.log() coinFlip a few times to make sure you're getting a mix of 0s and 1s. Next up, we'll add our conditional logic. Since we already have a randomly generated 0 or 1, we can set up an if/else statement where 1 represents "Heads" and 0 represents "Tails". We'll write this statement using the syntax we learned above, such that if coinFlip is equal to 1, we will console.log "Heads". Otherwise (else), we can assume coinFlip must be 0 and console.log "Tails". if (coinFlip === 1){ console.log("Heads") } else{ console.log("Tails") } We now have a fully functional coin flipping algorithm! Congratulations. You can view and run the solution code in the pen below. We'll continue to add to this over the following few objectives.

Follow Along

Let's return to our coin flip game to create a function flip() that will run our code with a single line. Just like with loops, all we need to do is add another layer of functionality here, so we'll wrap a function declaration around all the code we already have. We need to declare the function with the keyword function, then name it with name + (), so here we can write function name() and wrap the whole function in curly brackets ({}) like so. function flip() { // coin flip algorithm goes here } A single line of code (flip()) will run our coin flip game when this process is completed! Then, as usual, view and run the solution code below.

Passing Data into Functions

Let's return to our cookie example. Pretend that you want your robot to bake different types of cookies. Do you need to write a new function for every cookie? Not at all. Instead, you could add a parameter, or variable, called recipe and call bakeCookies('pecan') or bakeCookies('chocolateChunk'). Parameters are how functions accept changing data. Consider the example below. function add(num1, num2) { return (num1 + num2); } add(2,2) // returns 4 add(4,5) // returns 9 We can declare variables called parameters (num1 and num2 in the example above) that represent data we will use when calling the function. This is similar to algebra. X + Y = Z would be a pretty meaningless equation, but once we substitute real numbers for X and Y, we can easily solve for Z. Here, X and Y are analogous to parameters, and the real numbers to arguments. We'll dive into details about both parameters and arguments in this section, but the differences can be summarized as follows. Function parameters are the names listed in the function's definition. Function arguments are the real values passed to the function. Parameters are initialized to the values of the arguments supplied.

Follow Along

Let's wrap our heads/tails program in a loop to allow users to play more than once. We'll start where we left off with the conditional. It's relatively simple to add loop functionality. We're going to wrap this whole chunk of code inside a for loop. To do so we'll utilize the same syntax from above, and for now we'll tell the loop to run five times. We'll start by declaring the for keyword, then setting our initial value to 0 (let i = 0). We want the loop to run until i is equal to 5, i < 5, and to add 1 to i every time the loop runs. for (let i = 0; i < 5; i++) { // start at 0 | loop until 5 | add one every time As you might imagine, we can now change the number of coinFlips to preform by changing the conditional expression above, so i < 5 could change to i < 10 and our coin would be flipped 10 times. Its important to note that the variable needs to go inside of the loop so that it is randomly generated each time the loop runs. Otherwise, coinFlip would be declared outside of the loop and our end result would be 5 heads or 5 tails. Go ahead and try moving the variable around to see what we mean. With this seemingly simple MVP, you could go on to add a lot of functionality to this program, including user interaction through window.prompt() or by integrating HTML. Again, you can view and run the solution code in the pen below.

Function Expressions

Now that we understand how basic function syntax works, we can push even further into another type of function, a function expression. Function expressions have unique differences when compared against function declarations: A variable is used to store the function for later use Anonymous functions are used Function expressions are not hoisted. They can only be invoked after a definition has been placed in the execution stack. Example of a function expression: const add = function(a,b) { console.log(a + b); } add(2,4) // 6 Notice the function doesn't actually have a name. This is what we refer to as an anonymous function. Because we are using a const named add we don't need to name our function anything. We can simply execute the function when add is referenced by invocation. Why do this and not use a function declaration? Because we have more control over our code now. We will discuss this in greater detail later on with scope and closure. For now, just know that arrow functions make code more concise.

Numbers

Numbers are just that, numbers. Numbers do NOT have quotes around them. They can be negative as well. JavaScript does have a limitation on the size of a number (+/- 9007199254740991), but only very rarely will that limitation come up. const answer = 42; const negative = -13;

Control Flow

Often times, as a computer is reading and executing our code, we want code to run only if something is true or not. For example, add one point to the variable score if the character touches a coin. This is known as control flow or conditional logic. Control flow means that not all code on the screen is executed in order or at all. We will learn to use some basic control flow today and dive deeper into it in our next lesson. Let's say you wanted to write a simple script to check whether someone is a legal driver. You could use conditional logic to print a true or false boolean. const age = 18 if (age > 15) { console.log(true); } else { console.log(false); } Here we are taking a number (age) and checking to see if the statement is true. The statement 16 > 15 is true, so our code will return true. If it is not, it will skip that chunk of code and return false. Check For Understanding: Change the value of age above so that the code will return false. We just learned about the if operator. We can use if to check and see if an expression is true. If it is, JavaScript will run some code. If it is not, JavaScript will skip the code and keep running the program. if (1 + 1 === 2) { console.log('The expression is true!'); } // since 1 + 1 does equal 2, JavaScript will console.log ("The expression is true!") if (1 + 1 === 3) { console.log('The expression is true!'); } // since 1 + 1 does NOT equal 2, JavaScript will NOT console.log ("The expression is true!") To add on to if, we can also use the else and else if statements. These statements must be used only after if has been used. These statements will be evaluated if the initial if returns false. We can think of the else if as another if statement that has been chained (we can have as many else if statements we want). Only one if or else if statement code block will be run. If at any time a statement evaluates to true, that code will be run and the rest will be skipped: if (1 + 1 === 3) { console.log('This will be skipped!'); // since 1 + 1 is NOT 3, this will be skipped } else if (1 + 1 === 2) { console.log('This code will be run.'); // since 1 + 1 is equal to 2, this will be run } else if (1 - 1 === 0) { // 1 - 1 IS 0, however, the previous if statement was already true, so this will be skipped c onsole.log('This code will NOT be run.'); } The else statement will always come at the end of an if-else if chain, and will act as a default. If none of the expressions returned true, the else code block will be run no matter what. If any of the previous if or else if expressions are true, the else statement code block will not be run. if (1 + 1 === 3) { console.log('This will be skipped!'); // since 1 + 1 is NOT 3, this will be skipped } else if (1 + 1 === 3) { console.log('This code will NOT be run'); // since 1 + 1 is NOT 3, this will be skipped } else { console.log('This code will be run'); // since the above were skipped, this will run }

Arguments

Once we have our parameters set up in our function, we can now pass data into the function. We will put each piece of data inside the parentheses we write when we call the function. We call these pieces of data arguments. arguments can be ANY data type (string, number, Boolean, Object, array, even other functions!). Unlike other languages, JavaScript does not require us to set the data type when we write the function. However, you should make an effort to understand what type of data will be coming into the function (and if you are using pre-built functions, you should know what data type that function expects). To use an argument, just put the data in the function call parentheses like so: function logsName(name){ console.log(name); } logsName('Dan'); // returns Dan logsName('Diandra'); // returns Diandra If you have more than one parameter, you will use more than one argument: function logsSchool( School, descriptor ){ console.log(`${School} ${descriptor}`); } logsSchool('Lambda', 'is Awesome!'); // logs Lambda is Awesome! Arguments will always line up with parameters so that the first argument will be the first parameter, and so on. If an argument is not given for a parameter, the parameter will be equal to undefined.

What are the three types of variables and the main rule for their usage?

Var, let and constant

Logical Operators

We can also combine two equality expressions and ask if either of them is true, both are true, or neither is true. To do this, we will use Logical Operators. && The first logical operator we will look at is the "AND" operator. It is written with two ampersands (&&). This will evaluate both expressions and will return true if BOTH expressions are true. If one (or both) of them is false, then this operator will return false.For example, (100 > 10 && 10 === 10) will return true because both statements are true, but (10 === 9 && 10 > 9) will return false because one statement is false. || Next up is the "OR" operator. It is written with two vertical bars (||). This operator will check two expressions and return true if either one is true. It will return false only if BOTH expressions are false. As you'd expect, a line where both parts are true would return true. Like so: (100 > 10 || 10 === 10) //true Similarly, this line where only one expression is accurate would return true. Like this: (10 === 9 || 10 > 9) //true If both expressions are false, like this, then the result will be false. (10 === 9 || 1 > 9) //false ! The last logical operator is the "NOT" operator. It is written as a single exclamation mark (!). We saw this operator earlier when determining equality (!==). As before, the NOT operator will return the opposite Boolean value of what is passed to it. In this first case, since the opposite of false is true, (!false) would return true. (!false) // true Similarly since 1 is equal to 1 and this statement is true, !(1===1) would return false thanks to the ! operator. (!(1 === 1)) // false

Math.pow

We can use the pow method on Math to return a number raised to an exponent. It will take two numbers. The first is the base and the second is the power. For example, Math.pow(5,2) calculates 5 squared, which is 25. See some more examples below: Math.pow(2,2) // returns 4 Math.pow(3,2) // returns 9 Math.pow(3,3) // returns 27

The ++ operator

We saw in the last two examples the ++ operator. This is JavaScript shorthand for "Set the variable's value to its current value plus one." There are a few more of these variable math/assignment shorthand expressions. We will visit them in upcoming lessons.

The return Statement

We will not always want to console.log() everything that comes out of a function. Most likely we will want to return something for use in other operations. The only way for us to use data that is local to a function is with the keyword return. return, essentially, lets data escape a function. Nothing other than what is returned can be accessed outside of the function. return is always the last thing in a function because when the function hits a return statement, the function immediately stops everything else that it is doing. We can also assign the value of a return statement to another variable, and we will now have access to the data returned from the function. function addTwoNumbers(num1, num2) { const sum = num1 + num2; return sum; console.log('This will never be reached'); } const newSum = addTwoNumbers( 1, 2 ); console.log(addTwoNumbers(1,2)); //returns 3 console.log(sum); // returns undefined - sum exists only inside the function console.log(newSum); // returns 3 - value is held in newSum Note: We will never be able to have access to the actual variable created in the function. We will only have access to the data that variable was assigned to.

While loops

While loops are similar to for loops in that they make it easy to repeat some action for a desired amount of time. Just like for loops, they will run so long as a condition is met. The key difference here is that you don't need to declare an incrementing variable when declaring a while loop. Syntactically, while loops look like this. Note that the example below is an "infinite loop" because the condition will never be false. while (i === true) { console.log("i is true"); } The most practical example of loops will use some "counter," an outside variable affected by what's inside the loop. A more practical example of a while loop, using a counter, might look like: let count = 1; while (count < 10) { console.log(count); count +=2; } The return of this loop would be 11 because the loop would add 2 every time it runs until the value is greater than 10.

JS MATH PRACTICE

const num1 = 1; const num2 = 2; const num3 = 10; const num4 = 13.56; // add together num1 and num2, log your results to the console. console.log(num1 + num2); // round num4 to the nearest whole number using a method of `Math`, log your results to the console. console.log(Math.ceil(num4)); // raise num3 to the 2nd power, log your results to the console. console.log(Math.pow(num3, 2)) // continue to practice with more complicated calculations here. See if you can, for example, write the quadratic formula.

var

var is the ES5 way of declaring a variable. This is a generic variable keyword. Variables created with var can be changed without causing errors. While that sounds like a good thing at first, using var too often might lead to buggy code. Note in the example below that once you declare the variable, you can change it without declaring it again. This is true with all variable keywords. var firstName = 'Alice'; firstName = 'Bob'; // <- this would be fine If var is commonly regarded as bad programming practice, what should we use?

for (let i = 0; i < sequence.length; i++);Why is "LET" used to create the variable in the for loop initialization above?

we need to declare i before incrementing the value


संबंधित स्टडी सेट्स

PEDs Sucess: Growth and Development

View Set

Psychosocial Theory of Human Development: Adult Development

View Set

Java 2 Final Inheritance and Classes

View Set

Nutrients and Recommended Intakes

View Set