JavaScript
Jagged arrays
- you could put arrays inside arrays inside arrays for even more dimensions -Sometimes you want arrays that aren't as nice and even as your 3 x 3 two-dimensional array: you may have three elements in the first row, one element in the second row, and two elements in the third row. JavaScript allows those, and they're called jagged arrays. ex. var jagged = [[1,2,3],[4,5]];
Function
-A function definition is just a regular variable definition where the value given to the variable happens to be a function. var square = function(x) { return x * x; }; console.log(square(12)); // --> 144 -A function is created by an expression that starts with the keyword function. Functions have a set of parameters (in this case, only x) and a body, which contains the statements that are to be executed when the function is called. The function body must ALWAYS be wrapped in braces. -you need to put a semi-colon at the end of each line of code in the reusable block
hasOwnProperty
-Allows you to see if the object holds a specific property example: var suitcase = { shirt: "Hawaiian" }; if (suitcase.hasOwnProperty('shorts')) { console.log('shorts') } else { suitcase.shorts = "Hakim"; console.log('shorts') }; or var myObj = { // finish myObj name: "Reece" }; console.log( myObj.hasOwnProperty('name') ); // should print true console.log( myObj.hasOwnProperty('nickname') ); // should print false
Nested scope
-Formula contains two functions in it var landscape = function() { var result = ""; var flat = function(size) { for (var count = 0; count < size; count++) result += "_"; }; var mountain = function(size) { result += "/"; for (var count = 0; count < size; count++) result += "'"; result += "\\"; }; flat(3); mountain(4); flat(6); mountain(1); (1); return result; }; console.log(landscape()); // → ___/ ' ' ' '\______/'\_ -each local scope can also see all the local scopes that contain it. The set of variables visible inside a function is determined by the place of that function in the program text. All variables from blocks around a function's definition are visible—meaning both those in function bodies that enclose it and those at the top level of the program. This approach to variable visibility is called lexical scoping
how does for loops work?
-It starts off with i = 2 -It then asks: Is i currently less than 13? Because i = 2, this is true and we continue. -We do NOT increment now. Instead, if the condition is met, we run the code block. -Here, the code block prints out the value of i. It is currently 2 so 2 will be printed out. -Once the code block is finished, the for loop then increments / decrements. Here, we add 1. -Now i = 3. We check if it is less than 13. If it is true, we run the code block. -The code block runs, and then we increment. -We repeat these steps until the condition i < 13 is no longer true.
The "this" Keyword for methods
-It turns out we can make a method work for many objects using a new keyword, this. The keyword this acts as a placeholder, and will refer to whichever object called that method when the method is actually used. Let's look at the method setAge (line 2) to see how this works. By using the keyword this, setAge will change the age property of any object that calls it. Previously, we had a specific object bob instead of the keyword this. But that limited the use of the method to just bob. Then when we say bob.setAge = setAge; (line 9), it means whenever we type bob.setAge( ), this.age in the setAge method will refer to bob.age. example: // here we define our method using "this", before we even introduce bob var setAge = function (newAge) { this.age = newAge; }; // now we make bob var bob = new Object(); bob.age = 30; // and down here we just use the method we already made bob.setAge = setAge; // change bob's age to 50 here bob.setAge(50);
Methods in object oriented programming
-Methods are similar to functions. var bob = new Object(); bob.name = "Bob Smith"; bob.age = 30; // this time we have added a method, setAge bob.setAge = function (newAge){ bob.age = newAge; }; Methods serve several important purposes when it comes to objects. They can be used to change object property values. The method setAge on line 4 allows us to update bob.age. They can be used to make calculations based on object properties. Functions can only use parameters as an input, but methods can make calculations with object properties. For example, we can calculate the year bob was born based on his age with our getYearOfBirth method (line 8). example- var bob = new Object(); bob.age = 17; // this time we have added a method, setAge bob.setAge = function (newAge){ bob.age = newAge; }; bob.getYearOfBirth = function () { return 2014 - bob.age; }; console.log(bob.getYearOfBirth());
Function declaration
-Shorter way than saying var square = ....function -The function keyword can be used at the start of the statement ex. function square(x) { return x * x; }
Switch
-a more efficient way for else if statements switch (prompt ("What is the weather like?")) { case "rainy": console.log ("Remember to bring an umbrella.") ; break; case "sunny": console.log ("Dress lightly.") ; case "cloudy": console.log ("Go outside.") ; break ; default : console.log ("Unknown weather type!") ; break ; } You may put any number of case labels inside the block opened by switch. The program will jump to the label that corresponds to the value that switch was given or to default if no matching value is found. It starts executing statements there, even if they're under another label, until it reaches a break statement. In some cases, such as the "sunny" case in the example, this can be used to share some code between cases (it recommends going outside for both sunny and cloudy weather). But beware: it is easy to forget such a break, which will cause the program to execute code you do not want executed.
Object-oriented programming(Inheritance)
-allows one class to see and use the methods and properties of another class. You can think of it as a child being able to use his or her parent's money because the child inherits the money.
To print out all elements of an object
-by using a for-in loop and console.log var nyc = { fullName: "New York City", mayor: "Bill de Blasio", population: 8000000, boroughs: 5 }; for(var property in nyc) { console.log(property); }
Constructors With Methods
-constructors can also define methods. This way, as soon as the object is created it will have its own methods as well. ex. function Rectangle(height, width) { this.height = height; this.width = width; this.calcArea = function() { return this.height * this.width; }; this.calcPerimeter = function() { return (this.height * 2) + (this.width * 2); }; } var rex = new Rectangle(7,3); var area = rex.calcArea(); var perimeter = rex.calcPerimeter();
For loop
-first, a "counter" variable is created to track the progress of the look. Then comes a while loop, whose test expression usually checks wether the country has reached some boundary yet. At the end of the loop body, the counter is updated to track progress. -the parentheses after a keyword must contain two semicolons. The part before the first semicolon initializes the loop, usually by defining a variable. The second part is the expression that checks wether the loop must continue. The final part updated the state of the loop after every iteration. Usually this is shorter and clearer than a while construct. Ex. for (var number = 0; number <= 12; number = number + 2) console.log (number);
when to use while loops and when to use for loops
-for loops are great for doing the same task over and over when you know ahead of time how many times you'll have to repeat the loop. -while loops are ideal when you have to loop, but you don't know ahead of time how many times you'll need to loop.
Switch statements
-if you have a lot of choices you want to cover in a program, it might be annoying to type else if () ten times. That's why JavaScript has the switch statement -switch allows you to preset a number of options (called cases), then check an expression to see if it matches any of them. If there's a match, the program will perform the action for the matching case; if there's no match, it can execute a default option. ex. var lunch = prompt("What do you want for lunch?","Type your lunch choice here"); switch(lunch){ case 'sandwich': console.log("Sure thing! One sandwich, coming up."); break; case 'soup': console.log("Got it! Tomato's my favorite."); break; case 'salad': console.log("Sounds good! How about a caesar salad?"); break; case 'pie': console.log("Pie's not a meal!"); break; default: console.log("Huh! I'm not sure what " + lunch + " is. How does a sandwich sound?"); } another ex. var color = prompt("What's your favorite primary color?","Type your favorite color here"); switch(color) { case 'red': console.log("Red's a good color!"); break; case 'blue': console.log("That's my favorite color, too!"); break; //Add your case here! case 'yellow': console.log("I ****in hate yellow"); break; default: console.log("I don't think that's a primary color!"); }
for/in loop
-it will print out all the entries we have in our object. syntax: for (var key in object) { // Access that key's value // with object[key] } -The "key" bit can be any placeholder name you like. It's sort of like when you put a placeholder parameter name in a function that takes arguments. example: //list will print out all the entries we have in our friends object var list = function(friends) { for(var key in friends) { console.log(key); } };
Arrays of Objects
-just as we can make arrays of numbers and strings, we can also make arrays of objects. ex. // Our person constructor function Person (name, age) { this.name = name; this.age = age; } // Now we can make an array of people var family = new Array(); family[0] = new Person("alice", 40); family[1] = new Person("bob", 42); family[2] = new Person("michelle", 8);
Arrays of arrays
-not only can you put a mixture of types in an array, you can even put other arrays inside arrays. You can make a two-dimensional array by nesting arrays one layer deep, like so: var twoDimensional = [[1, 1], [1, 1]]; This array is two-dimensional because it has two rows that each contain two items. If you were to put a new line between the two rows, you could log a 2D object—a square—to the console, like so: [1, 1] [1, 1]
do loop
-similar to the while loop A do loop always executes its body at least once, and it starts testing wether it should stop only after the first execution. Ex. do { var yourName = prompt ("Who are you?"); } while ( !yourName); console.log(yourName);
Substrings
-sometimes you don't want to display the entire string, just part of it. This is a preview and is the substring of the original string. Ex "some word".substring(x,y) -where x is where you start chopping and y is where you finish chopping.
Accessing properties on objects through bracket notation
-we can also access properties using bracket notation. In this case we use ObjectName["PropertyName"] to access the desired property. Note, we need " " around the property's name.
Six variable naming rules
1. A variable name cannot contain spaces. 2. Can only contain letters, numbers, dollar signs and underscores 3. A variable name can't be any JavaScript keywords but it can contain keywords 4. Vnames are case sensitive 5. Use camelCase naming convention 6. Make names descriptive for future readability
Loop
A way to repeat some code. Looping control flow allows us to go back to some point in the program where we were before and repeat it with our current program state. Ex. var number = 0; while (number <= 12) { console.log (number) ; number = number + 2; }
Concatenates
Adding text strings together Ex. Alert ("Thanks" + userName + "!") ;
JavaScript supports three logical operators that can be used to "reason" about Booleans
And,or and not
Arrays
Arrays: a. store lists of data b. can store different data types at the same time c. are ordered so the position of each piece of data is fixed Example: var names = ["Mao","Gandhi","Mandela"]; var sizes = [4, 6, 3, 2, 1, 9]; var mixed = [34, "candy", "blue", 11]; Syntax: var arrayName = [data, data, data]; Any time you see data surrounded by [ ], it is an array.
Prompt box
Asks the user for some information and provides a response field for the answer Ex. var spec = prompt("Your species?, "human") ;
A sequence of statements wrapped in braces is called ____
Block
Always add a _____ at the end of every loop.
Break If you were to leave out that break statement or accidentally wrote a condition that always produces true, your program would get stuck in an infinite loop. Ex. for (var current = 20; ; current++) { If (current % 7 == 0) break; } console.log(current) ;
while statement
Creates a loop. The word while is followed by an expression in parentheses and then a statement, much like if. *the loop executes that statements as long as the expression produces a value that is true when converted to Boolean type
Modulus operator (%)
Doesn't give you the result of dividing one number by another. It gives you the remainder when the division is executed. -So why learn modulo? For one thing, it's good at testing divisibility. Consider 30 % 10. What does it return? There is nothing left over, so 0. How about 9 % 3? Also 0. We can use modulos in comparisons, like this: 10 % 2 === 0 evaluates to true 7 % 3 === 0 evaluates to false because there is 1 left over.
Properties in objects
Each piece of information we include in an object is known as a property. Think of a property like a category label that belongs to some object. When creating an object, each property has a name, followed by : and then the value of that property. For example, if we want Bob's object to show he is 34, we'd type in age: 34. age is the property, and 34 is the value of this property. When we have more than one property, they are separated by commas. The last property does not end with a comma.
==
Equal to
Looping object arrays
Ex. // Our Person constructor function Person(name, age) { this.name = name; this.age = age; } // Now we can make an array of people family[0] = new Person("alice", 40); family[1] = new Person("bob", 42); family[2] = new Person("michelle", 8); family[3] = new Person("timmy", 6); // loop through our new array for(var i = 0; i < family.length; i++) { console.log(family[i].name); }
If an _____ corresponds to a sentence fragment, a JavaScript _______ corresponds to a full sentence in a human language.
Expression; statement An expression can be content to just produce a value, which can then be used by the enclosing expression. A statement stands on its own and amounts to something only if it affects the world.
Heterogeneous arrays
First, it's not necessary for you to put the same type of data in an array! For instance, you don't have to have var pronouns = ["I", "you", "we"]; var numbers = [1, 2, 3]; You can have a heterogeneous array, which means a mixture of data types, like so: var mix = [42, true, "towel"];
>=
Greater than or equal to
Conditional execution (if/else)
If - just want some code to be executed if, and only if, a certain condition holds. If the answer to the condition is yes, the code inside the curly braces will run. ex. if( "myName".length >= 7 ) { console.log("You have a long name!"); } Else- you often won't just have code that executes when a condition holds true, but also code that handles the other case, if its false. ex. if( "myName".length >= 7 ) { console.log("You have a long name!"); } else { console.log("You have a short name!"); } *the else keyword can be used, together with if, to create two separate, alternative execution paths. *multiple if/else pairs can be "chained" together Ex. var theNumber = Number(prompt("pick a number", "0")); if (num < 10); alert("Small"); else if (num < 100) alert("Mediun"); else alert("Large"); another ex. var isEven = function(number) { if(number % 2 === 0) { return true; } else if(isNaN(number)) { return "Not a number!"; } else { return false; } };
isNaN
If you call isNaN on something, it checks to see if that thing is not a number. So: isNaN('berry'); // => true isNaN(NaN); // => true isNaN(undefined); // => true isNaN(42); // => false Be careful: if you call isNaN on a string that looks like a number, like '42', JavaScript will try to help by automatically converting the string '42' to the number 42 and return false (since 42 is a number).
Public
In JavaScript all properties of an object are automatically public. Public means that they can be accessed outside the class. Think of these properties as the information a class is willing to share.
I.D.'ing Objects, Strings or Numbers
In order to figure out if something is an object, string or number we can id it with typeOf syntax: var someObject = {someProperty: someValue}; console.log( typeof someObject );
Boolean values
Is two values, true and false
Var (variable)
It takes on a particular value when you assign the value to it. -It is useful to think that any time you type the variable's name, you are asking the computer to swap out the variable name and swap in the value of the variable. ex. - var myName = "Steve Jobs"; myName.substring(0,5)
Private Variables
Just as functions can have local variables which can only be accessed from within that function, objects can have private variables. Private variables are pieces of information you do not want to publicly share, and they can only be directly accessed from within the class. Notice that it looks just like a normal variable, but it is defined inside the constructor for Person without using this, but instead using var. This makes bankBalance a private variable. ex. function Person(first,last,age) { this.firstname = first; this.lastname = last; this.age = age; var bankBalance = 7500; }
<=
Less than or equal to
Objects definition and example
Let's go back to the analogy of computer languages being like regular spoken languages. In English, you have nouns (which you can think of as "things") and verbs (which you can think of as "actions"). Until now, our nouns (data, such as numbers, strings, or variables) and verbs (functions) have been separate. No longer! Using objects, we can put our information and the functions that use that information in the same place. You can also think of objects as combinations of key-value pairs (like arrays), only their keys don't have to be numbers like 0, 1, or 2: they can be strings and variables. ex. var phonebookEntry = {}; phonebookEntry.name = 'Oxnard Montalvo'; phonebookEntry.number = '(555) 555-5555'; phonebookEntry.phone = function() { console.log('Calling ' + this.name + ' at ' + this.number + '...'); }; phonebookEntry.phone(); -In that example, we gave the key name the value 'Oxnard Montalvo' and the key number the value '(555) 555-5555'. An object is like an array in this way, except its keys can be variables and strings, not just numbers. Objects are just collections of information (keys and values) between curly braces, like this: var myObject = { key: value, key: value, key: value };
Local and global
Local means the result variable will be newly created EVERY time the function is called, and these separate incarnations do not interfere with each other. This "localness" of variables applies only to the parameters and to variables declared with the var keyword inside the function body. -Variables declared outside of any function are called global, because they are visible throughout the program. Local example: var x = "outside"; var f1 = function() { var x = "inside f1"; }; f1(); console.log(x); // --> outside global example: var f2 = function() { x = "inside f2"; }; f2(); console.log(x); // --> inside f2
Can you start a variable name with a number?
No. But you can include numbers in variable names, as long as none of them come first.
NaN
Not a number - NaN is supposed to denote the result of a nonsensical computation, and as such, it isn't equal to the result of any other nonsensical computations
!=
Not equal to
Ternary operator
Operating on three values Console.log (true ? 1 : 2) ;
Unary operater
Operators that use only one value
If you enclose a number in quotation marks, its a _____
Script. JavaScript can't do addition on it. It can do addition only on numbers not enclosed in quotes.
Num++ Num--
Short way of writing: Num = num + 1 Num = num - 1
Accessing array data
Small complication: the position (or the index) of each bit of data is counted starting from 0, not 1. First element in the array: junkData[0] Third element in the array: junkData[2] Arrays have 0-based indexing, so we start counting the positions from 0.
The 'do' / 'while' loop
Sometimes you want to make sure your loop runs at least one time no matter what. When this is the case, you want a modified while loop called a do/while loop. ex. var loopCondition = false; do { console.log("I'm gonna stop looping 'cause my condition is " + loopCondition + "!"); } while (loopCondition); *It runs once because do tells it to, but then never again because loopCondition is false! ex. var getToDaChoppa = function(count){ do{ console.log("I'm looping until we have looped " + count + " more times!"); count--; } while (count > 0 ); }; getToDaChoppa(5);
Prompt box second string?
The default response that appears in the field when the prompt displays. If the user leaves the default response as-is and just clicks OK, the default response is assigned to the variable. Up to you to include a default response.
And logical operator
The logical operator and is written in JavaScript like this: &&. It evaluates to true when both expressions are true; if they're not, it evaluates to false. true && true; // => true true && false; // => false false && true; // => false false && false; // => false
Not logical operator
The logical operator not is written in JavaScript like this: !. It makes true expressions false, and vice-versa. !true; // => false !false; // => true
Or logical operator
The logical operator or is written in JavaScript like this: ||. It evaluates to true when one or the other or both expressions are true; if they're not, it evaluates to false. true || true; // => true true || false; // => true false || true; // => true false || false; // => false
Two ways of creating an object: object literal notation vs. object constructor
The method we've used to create objects uses object literal notation—that is, creating a new object with { } and defining properties within the brackets. Another way of creating objects without using the curly brackets { } is to use the keyword new. This is known as creating an object using a constructor. Literal notation is just creating an object with curly braces, like this: var myObj = { type: 'fancy', disposition: 'sunny' }; var emptyObj = {}; When you use the constructor, the syntax looks like this: var myObj = new Object(); This tells JavaScript: "I want you to make me a new thing, and I want that thing to be an Object. constructer ex. var me = new Object(); me.name = "Reece"; me.age = 25; You can add keys to your object after you've created it in two ways: myObj["name"] = "Charlie"; myObj.name = "Charlie"; Both are correct, and the second is shorthand for the first. See how this is sort of similar to arrays? Literal syntax: var myObj = { key1: value, key2: value }; var myObj = {}; myObj.key1 = value; myObj['key2'] = value; Object constructor: var myObj = new Object(); myObj.key1 = value; myObj['key2'] = value;
String
The quoted text Ex. "Thanks!"
return keyword on functions
The return keyword simply gives the programmer back the value that comes out of the function. So the function runs, and when the return keyword is used, the function will immediately stop running and return the value. ex var timesTwo = function(number) { return number * 2; }; var newNumber = timesTwo(10); console.log(newNumber);
while loop
The while loop is ideal when you want to use a loop, but you don't know how many times you'll have to execute that loop. Say, for example, you wanted to keep choosing playing cards from a deck until you get a spade. You don't know how many cards you'll need to choose, so a for loop won't work. In situations like these where you don't know in advance when to stop looping, we can use a while loop. Syntax: while(condition){ // Do something! } As long as the condition evaluates to true, the loop will continue to run. As soon as it's false, it'll stop. (When you use a number in a condition, as we did earlier, JavaScript understands 1 to mean true and 0 to mean false.) *If you give a while loop a condition that is true and you don't build in a way for that condition to possibly become false, the loop will go on forever and your program will crash. No good! To prevent this from happening, you always need a way to ensure the condition between your while parentheses can change. ex. understand = true; while(understand){ console.log("I'm learning while loops!"); //Change the value of 'understand' here! understand = false } another ex. var loop = function () { var number = 0; while (number++ < 3) { console.log("I'm looping!"); } }; loop(); or: var loop = function (limit) { var number = 0; while (number++ < limit) { console.log("I'm looping!"); } }; loop(9);
functions with two parameters
To call a function with more than one parameter, just enter a value for each parameter in the parentheses. For example, areaBox(3,9); would return the area of a box with a length of 3 and a width of 9. ex. var areaBox = function(length, width) { return length * width; };
Curly braces { }
Use when we need to execute multiple statements inside a look, we wrap them in curly braces *they group statements together, making them count as a single statement.
Scope (Global vs. Local variables)
Variables defined outside a function are accessible anywhere once they have been declared. They are called global variables and their scope is global. ex. var globalVar = "hello"; var foo = function() { console.log(globalVar); // prints "hello" } Variables defined inside a function are local variables. They cannot be accessed outside of that function. ex. var bar = function() { var localVar = "howdy"; } console.log(localVar); // error Using my_number without the var keyword refers to the global variable that has already been declared outside the function in line 1. However, if you use the var keyword inside a function, it declares a new local variable that only exists within that function. ex. var my_number = 7; //this has global scope var timesTwo = function(number) { var my_number = number * 2; console.log("Inside the function my_number is: "); console.log(my_number); }; timesTwo(7); console.log("Outside the function my_number is: ") console.log(my_number); Inside the function my_number is: 14 Outside the function my_number is: 7
The console.log function
We used console.log to output values. Use for testing and experimenting *the alert function can be useful as an output device when experimenting, but clicking away all those little windows will get on your nerves. Ex. var x = 30; console.log ( the value of x is", x); // --> the value of x is 30
Can strings be added to each other?
Yes, it Concatenates "Con" + "cat" + "e" + "Nate"
How to make a new line within a string
\n
Custom Constructors
function Person(name,age) { this.name = name; this.age = age; } // Let's make bob and susan again, using our constructor var bob = new Person("Bob Smith", 30); var susan = new Person("Susan Jordan", 25); -This is much better than using the Object constructor which just gives us an empty object and needs us to define every property and value for each object we would create. syntax: function Dog(myParameter) { this.property = myParameter; }; -you can already define a parameter which will show up everytime. ex. function Person(name,age) { this.name = name; this.age = age; this.species = "Homo Sapiens"; }
.toUpperCase() and .toLowerCase()
syntax: var answer = prompt("Question to the user").toUpperCase(); -This converted the user's answer to ALL CAPS before saving it in the answer variable. This helps eliminate problems that might crop up if your program tests for 'YES' but your user typed in 'yes' or 'Yes'. The input becomes all caps before we test, so we only have to test for all caps! You can also use .toLowerCase(), which converts a string to all lower-case letters.
for loop
syntax: for (var i = 1; i < 11; i = i + 1) { /* your code here */; } -Every for loop makes use of a counting variable. Here, our variable is called i (but it can have any name). The variable has many roles. The first part of the for loop tells the computer to start with a value of 1 for i. It does this by declaring the variable called i and giving it a value of 1. When the for loop executes the code in the code block—the bit between { }—it does so by starting off where i = 1. -The second part of the for loop determines where it ends. -a. A more efficient way to code to increment up by 1 is to write i++. b. We decrement down by 1 by writing i--. c. We can increment up by any value by writing i += x, where x is how much we want to increment up by. e.g., i += 3 counts up by 3s. d. We can decrement down by any value by writing i -= x. e. Be very careful with your syntax—if you write a loop that can't properly end, it's called an infinite loop. It will crash your browser!
Accessing properties on objects through dot notation
to access a property, we use ObjectName.PropertyName (e.g., bob.name)
example of building an address book
var bob = { firstName: "Bob", lastName: "Jones", phoneNumber: "(650) 777-7777", email: "[email protected]" }; var mary = { firstName: "Mary", lastName: "Johnson", phoneNumber: "(650) 888-8888", email: "[email protected]" }; var contacts = [bob, mary]; function printPerson(person) { console.log(person.firstName + " " + person.lastName); } //Prints all of the names as a list function list() { var contactsLength = contacts.length; for (var i = 0; i < contactsLength; i++) { printPerson(contacts[i]); } } /*Create a search function then call it passing "Jones"*/ function search(lastName) { var contactsL = contacts.length; for(var i = 0; i < contactsL; i++) { if(lastName === contacts[i].lastName) { printPerson(contacts[i]); } } } search("Jones"); //to add a new contact to the array function add(firstName, lastName, email, phoneNumber) { contacts[contacts.length] = { firstName: firstName, lastName: lastName, email: email, phoneNumber: phoneNumber } } add("Reece", "Obligacion", "[email protected]", 714-262-9178); list();
Object inside array example
var myObj = new Object(); myArray = [25,true, "Reece",myObj];
logical operator example
var user = prompt("What is your favorite name?","Reece,Jon or Obligacion").toUpperCase(); switch(user) { case 'REECE': var like = prompt("Do you like your first name?", "yes or no").toUpperCase(); var like2 = prompt("Is your first name a perfect fit?", "yes or no").toUpperCase(); if(like === "YES" && like2 === "YES") { console.log("You have the best name!"); } else { console.log("I wish you could change your name!"); } break; case 'JON': var middle = prompt("Do you like your middle name?", "yes or no").toUpperCase(); var middle2 = prompt("Is your middle name enjoyable to you?", "yes or no").toUpperCase(); if(middle === "YES" || middle2 === "YES") { console.log("It fits you perfectly"); } else { console.log("I wish you could change it"); } break; case 'OBLIGACION': console.log("That is your last name!"); break; default: console.log("That is not part of your name"); };
Loops and arrays
what if there were 100 elements in the array? For arrays, a useful way to systematically access every element in the array is to use a for loop! How does it work? 1. Line 3 declares the array. It has 4 elements. 2. We then start the for loop on line 5. 3. We see i starts off at value 0. 4. The for loop runs until i < 4 (because cities.length equals 4. The array cities has 4 elements in it 5. We will increment i by 1 each time we loop over. 6. We print out cities[0], which is "Melbourne". 7. We then start the loop again. Except now i = 1. 8. It will print out cities[1], which is "Amman". 9. This continues until i is no longer less than cities.length. ex. var cities = ["Melbourne", "Amman", "Helsinki", "NYC"]; for (var i = 0; i < cities.length; i++) { console.log("I would like to visit " + cities[i]); }
concisesness in while loops
when we give a variable the boolean value true, we check that variable directly—we don't bother with ===. For instance var bool = true; while(bool){ //Do something } is the same thing as var bool = true; while(bool === true){ //Do something } If you happen to be using numbers, as we did earlier, you could even do: var myNumber = 1; while(myNumber) { // Do something! }
Logical operators signs
|| or ! not && and