Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- length:
- "Maddie".length
- * = muliplcation
- / = division
- // = notes to self or others, not computer
- confirm("I am great.");
- prompt("Where are you from?")
- console.log(2*5)
- console.log ()= prints out whatever is in ()
- 3 data types:
- string (e.g. "hello friends!")
- numbers (e.g. 4, 10)
- booleans (e.g. false, 5 > 4)
- comparision operators
- > greater than
- < less than
- >= greater than or equal to
- <= less than or equal to
- === equal to
- !== not equal to
- if statement:
- if (){ () }
- if/else statement:
- if () { () } else { () }
- if (10<4) {console.log ("The condition is true.")}
- else {console.log ("The condition is false.")}
- eg:
- print out else statement
- if ("Maddie".length > 7)
- {console.log ("Maddie is great")}
- else {console.log ("I finished my first course!")}
- variables:
- // Declare a variable on line 3 called
- // myCountry and give it a string value.
- var myCountry = "USA";
- myCountry.substring(0,3)
- // Use console.log to print out the length of the variable myCountry.
- console.log ("USA".length)
- // Use console.log to print out the first three letters of myCountry.
- console.log ("USA".substring(0,3))
- change variable values:
- // On line 2, declare a variable myName and give it your name.
- var myName = "Maddie";
- // On line 4, use console.log to print out the myName variable.
- console.log(myName);
- // On line 7, change the value of myName to be just the first 2
- // letters of your name.
- var myName = "Ma";
- // On line 9, use console.log to print out the myName variable.
- console.log(myName)
- eg:
- //create variable myColor and give it string value
- var myColor = "red"; myColor.substring(0,3);
- //print length of myColor to console
- console.log ("red".length)
- Bieber if/else game:
- confirm("I am ready to play!");// Check if the user is ready to play!
- var age= 13;
- var age= prompt("What's you age");
- if(age<13)
- {(console.log("You may play, but we take no responsibility"))}
- else
- {console.log("Play on!")}
- console.log("You are at a Justin Bieber concert, and you hear this lyric 'Lace my shoes off, start racing.'")
- console.log("Suddenly, Bieber stops and says, 'Who wants to race me?'")
- var userAnswer= "yes"
- prompt("Do you want to race Bieber on stage?")
- if (userAnswer==="yes")
- {(console.log("You and Bieber start racing. It's neck and neck! You win by a shoelace!"))}
- else
- {console.log("Oh no! Bieber shakes his head and sings 'I set a pace, so I can race without pacing.'")}
- var feedback=10;
- prompt("Please rate the game out of 10");
- if (feedback<8)
- {console.log("Thank you! We should race at the next concert!")}
- else
- {console.log("I'll keep practicing coding and racing")}
- Functions (takes in inputs, does something with them and produces an output):
- eg:
- // This is what a function looks like:
- var divideByThree = function (number) {
- var val = number / 3;
- console.log(val);
- };
- // On line 12, we call the function by name
- // Here, it is called 'dividebythree'
- // We tell the computer what the number input is (i.e. 6)
- // The computer then runs the code inside the function!
- divideByThree(6);
- Function eg:
- var sayHello = function(name) {
- console.log('Hello ' + name);
- };
- the code in ()= parameter(which is a spaceholder word that we give a value when we call the function)
- call the code by doing this, it will print out HelloEmily:
- sayHello("Emily");
- Function eg:
- // Below is the greeting function!
- // See line 7
- // We can join strings together using the plus sign (+)
- // See the hint for more details about how this works.
- var greeting = function (name) {
- console.log("Great to see you," + " " + name);
- };
- greeting("Maddie");
- When we want to join together two strings, we put a plus sign.
- console.log("Hey" + "you"); will print out Heyyou. That's not what we want!
- If you want a space between words, you must add that space as well!
- console.log("Hey" + " " + "you"); will print out Hey you
- This joining of strings is called concatenation
- Function eg:
- var functionName = function( ) {
- // code code code
- // code code code
- // (more lines of code)
- };
- The var keyword declares a variable named functionName.
- The keyword function tells the computer that functionName is a function and not something else.
- Parameters go in the parentheses. The computer will look out for it in the code block.
- The code block is the reusable code that is between the curly brackets { }. Each line of code inside { } must end with a semi-colon.
- The entire function ends with a semi-colon.
- To use the function, we call the function by just typing the function's name, and putting a parameter value inside parentheses after it. The computer will run the reusable code with the specific parameter value substituted into the code.
- Function eg:
- var foodDemand =function(food) {
- console.log("I want to eat" + " " + food);
- }
- foodDemand("burrito");
- Function eg DRY:
- var orangeCost=function(price) {
- console.log(price * 5);
- }
- orangeCost(5);
- You are a creature of habit. Every week you buy 5 oranges. But orange prices keep changing!
- You want to declare a function that calculates the cost of buying 5 oranges.
- You then want to calculate the cost of the 5 all together.
- Write a function that does this called orangeCost().
- It should take a parameter that is the cost of an orange, and multiply it by 5.
- It should log the result of the multiplication to the console.
- Call the function where oranges each cost 5 dollars.
- return: gives you back the value that comes out of a function, so when return is used the function will stop running and return the value.
- eg:
- // Parameter is a number, and we do math with that parameter
- var timesTwo = function(number) {
- return number * 2;
- };
- // Call timesTwo here!
- var newNumber = timesTwo(3)
- console.log(newNumber);
- Functions return and if/else:
- eg:
- // Define quarter here.
- var quarter= function(number) {
- return number / 4;
- };
- if (quarter(0) % 3 === 0 ) {
- console.log("The statement is true");
- } else {
- console.log("The statement is false");
- }
- Function w/2 parameters:
- eg:
- var areaBox = function(length, width) {
- return length * width;
- };
- eg:
- Write a function called perimeterBox that returns the perimeter of a rectangle.
- It should have two parameters.
- One formula for perimeter is length + length + width + width;
- Call the function and pass in any value for length and width you like.
- var perimeterBox = function(length, width) {
- return length + length + width + width;
- };
- perimeterBox(5,4)
- Global vs Local variables:
- Scope: local or global
- Global: variable defines outside a function are accessible anywhere once declared.
- eg:
- var globalVar = "hello";
- var foo = function() {
- console.log(globalVar); // prints "hello"
- }
- Local: variable defined inside function, cannot be accessed outside that function.
- eg:
- var bar = function() {
- var localVar = "howdy";
- }
- console.log(localVar); // error
- If/ else if/ else statement:
- if (condition1) {
- code code code;
- } else if (condition2) {
- code code code;
- } else {
- code code code;
- }
- nested if + if/else statement:
- eg:
- var compare = function(choice1,choice2){
- if (choice1 == choice2) {
- return "The result is a tie!";
- }
- if (choice1 == "rock") {
- if (choice2 == "scissors") {
- return "Rock wins";
- } else {
- return "paper wins";
- }
- }
- if (choice1 == "paper") {
- if (choice2 == "rock") {
- return "paper wins";
- } else {
- return "scissors wins";
- }
- }
- }
- for Loops:
- eg:
- for (var counter = 1; counter < 11; counter++) {
- console.log(counter);
- } //prints out numbers 1-11
- general for loop syntax:
- for (var i = 1; i < 11; i = i + 1) {
- /* your code here */;
- }
- for loop rules:
- 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. (See the Hint for more.)
- 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!
- Note: x += y is the same as x = x + y. And x -= y is the same as x = x - y.
- for loops only run when the condition is true.
- 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
- eg:
- var names = ["Mao","Gandhi","Mandela"];
- var sizes = [4, 6, 3, 2, 1, 9];
- var mixed = [34, "candy", "blue", 11];
- array syntax:
- var arrayName = [data, data, data];
- Any time you see data surrounded by [ ], it is an array.
- Array and Loop eg:
- var cities = ["NYC", "Seattle", "Buffalo", "Paris", "Berlin", "LA", "Portland"];
- for (var i = 0; i < cities.length; i++) {
- console.log("I would like to visit " + cities[i]);
- } //prints out all cities with phrase in front of it
- push //add
- Text:
- Since text could be quite long, you can use a backslash (\) at the end of each line to make your string "wrap" to the next line, like this:
- /*jshint multistr:true */ =tells the computer not to mind the (\)
- eg:
- text = "Blah blah blah blah blah blah Eric \
- blah blah blah Eric blah blah Eric blah blah \
- blah blah blah blah blah Eric";
- var myName = "Eric";
- var hits = [];
- // Look for "E" in the text
- for(var i = 0; i < text.length; i++) {
- if (text[i] === "E") {
- // If we find it, add characters up to
- // the length of my name to the array
- for(var j = i; j < (myName.length + i); j++) {
- hits.push(text[j]);
- }
- }
- }
- if (hits.length === 0) {
- console.log("Your name wasn't found!");
- } else {
- console.log(hits);
- }
- eg:
- /*jshint multistr:true */
- var text = "Maddie went to Park Slope \ she didn't ride her bike. Maddie saw \ her mom. Maddie's mom is nice.";
- var myName = "Maddie";
- var hits = [];
- for(var i = 0; i < text.length; i ++) {
- if (text[i] === "M") {
- for(var j = i; j < (myName.length + i); j++) {
- hits.push(text[j]);
- }
- }
- }
- if (hits.length = 0) {
- console.log ("Your name wasn't found!");
- } else {
- console.log(hits);
- }
- 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.
- eg:
- var coinFace = Math.floor(Math.random() * 2);
- while(coinFace === 0){
- console.log("Heads! Flipping again...");
- var coinFace = Math.floor(Math.random() * 2);
- }
- console.log("Tails! Done flipping.");
- //In line 1, we create a variable named coinFace, which is a random number that is either 0 (heads) or 1 (tails).
- Then in lines 3-5 we keep flipping the coin as long as the coin turns up heads. If coinFace is 0 (heads), then the condition in the while loop will evaluate to true, and we flip the coin again.
- If coinFace is 1 (tails), then the condition will be false, so we break out of the while loop and print Tails! Done flipping.
- 1= true
- 0= false
- while loop eg:
- var understand = true;
- while(understand === true){
- console.log("I'm learning while loops!");
- understand = false;
- }
- while loop eg:
- var condition = true;
- while(condition) {
- console.log("Hello!");
- // Avoid infinite loops!
- condition = false;
- }
- while loop eg:
- var soloLoop = function(){
- //Your code goes here!
- while(soloLoop) {
- console.log ("Looped once!");
- soloLoop = false
- }
- };
- soloLoop(true);
- infinite loops:
- We mentioned infinite loops in the previous exercise. 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.
- while loop eg:
- var loop = function(loop){
- var count= 0;
- while(count < 3){
- console.log("I'm looping!");
- count++;
- }
- };
- loop();
- eg:
- var myCondition = true;
- while(myCondition) {
- console.log("Looped once!");
- myCondition = false;
- }
- soloLoop(true);
- do/while loop:to make sure your loop runs at least one time no matter what.
- This loop says: "Hey! Do this thing one time, then check the condition to see if we should keep looping." After that, it's just like a normal while: the loop will continue so long as the condition being evaluated is true.
- do/while loop eg:
- var loopCondition = false;
- do {
- console.log("I'm gonna stop looping 'cause my condition is " + loopCondition + "!");
- } while (loopCondition);
- eg:
- var getTo = false;
- var getToDaChoppa = function(){
- do {
- console.log("the chopper , " + String(getTo) + "!");
- } while(getTo);
- };
- getToDaChoppa();
- do/while eg:
- // Can be false from the start, since
- // do/while runs at least one time
- var condition = false;
- do {
- console.log("I'm printed once!");
- } while(condition);
- Dragon Game:
- var slaying = true;
- // A bit of new math magic to calculate the odds
- // of hitting the dragon. We'll cover this soon!
- var youHit = Math.floor(Math.random() * 2);
- var damageThisRound = Math.floor(Math.random() * 5 + 1);
- var totalDamage = 0;
- while (slaying) {
- if (youHit) {
- console.log("You hit the dragon and did " + damageThisRound + " damage!");
- totalDamage += damageThisRound;
- if (totalDamage >= 4) {
- console.log("You did it! You slew the dragon!");
- slaying = false;
- } else {
- youHit = Math.floor(Math.random() * 2);
- }
- } else {
- console.log("The dragon burninates you! You're toast.");
- slaying = false;
- }
- }
- Dragon Game eg 2:
- var slaying= true;
- var youHit= Math.floor(Math.random() *2);
- var damageThisRound= Math.floor(Math.random() *5 + 1);
- var totalDamage= 0;
- var slaying= true;
- while(slaying) {
- if (youHit) {
- console.log ("You hit!");
- totalDamage += damageThisRound;
- if (totalDamage >= 4) {
- console.log("You win!");
- slaying = false;
- } else {
- youHit= Math.floor(Math.random() * 2);
- }
- } else {
- console.log ("You missed!");
- }
- slaying= false
- }
- if/else syntax:
- if (/* Some condition */) {
- // Do something
- } else if (/* Some other condition */) {
- // Do something else
- } else { // Otherwise
- // Do a third thing
- }
- isNaN: If you call isNaN on something, it checks to see if that thing is not a number.
- eg:
- isNaN('berry'); // => true
- isNaN(NaN); // => true
- isNaN(undefined); // => true
- isNaN(42); // => false
- note:
- You can't just do:
- isNaN(unicorns);
- unless you've already defined the variable unicorns. You can, however, do
- isNaN("unicorns"); // => true
- Switch: (replaces the if/else statement if you need to types if a lot) and 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.
- switch syntax:
- switch (/*Some expression*/) {
- case 'option1':
- // Do something
- break;
- case 'option2':
- // Do something else
- break;
- case 'option3':
- // Do a third thing
- break;
- default:
- // Do yet another thing
- }
- switch eg:
- 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?");
- }
- Logical Operators:
- and (&&)
- or (||)
- not (!)
- eg:
- var iLoveJavaScript = true;
- var iLoveLearning = true;
- if(iLoveJavaScript && iLoveLearning) {
- // if iLoveJavaScript AND iLoveLearning:
- console.log("Awesome! Let's keep learning!");
- } else if(!(iLoveJavaScript || iLoveLearning)) {
- // if NOT iLoveJavaScript OR iLoveLearning:
- console.log("Let's see if we can change your mind.");
- } else {
- console.log("You only like one but not the other? We'll work on it.");
- }
- And (&&): 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
- Or (||): 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
- Not (!): makes true expressions false, and vice-versa.
- !true; // => false
- !false; // => true
- Troll video game:
- var troll = prompt("You're walking through the forest, minding your own business, and you run into a troll! Do you FIGHT him, PAY him, or RUN?").toUpperCase();
- switch(troll) {
- case 'FIGHT':
- var strong = prompt("How courageous! Are you strong (YES or NO)?").toUpperCase();
- var smart = prompt("Are you smart?").toUpperCase();
- if(strong === 'YES' || smart === 'YES') {
- console.log("You only need one of the two! You beat the troll--nice work!");
- } else {
- console.log("You're not strong OR smart? Well, if you were smarter, you probably wouldn't have tried to fight a troll. You lose!");
- }
- break;
- case 'PAY':
- var money = prompt("All right, we'll pay the troll. Do you have any money (YES or NO)?").toUpperCase();
- var dollars = prompt("Is your money in Troll Dollars?").toUpperCase();
- if(money === 'YES' && dollars === 'YES') {
- console.log("Great! You pay the troll and continue on your merry way.");
- } else {
- console.log("Dang! This troll only takes Troll Dollars. You get whomped!");
- }
- break;
- case 'RUN':
- var fast = prompt("Let's book it! Are you fast (YES or NO)?").toUpperCase();
- var headStart = prompt("Did you get a head start?").toUpperCase();
- if(fast === 'YES' || headStart === 'YES') {
- console.log("You got away--barely! You live to stroll through the forest another day.");
- } else {
- console.log("You're not fast and you didn't get a head start? You never had a chance! The troll eats you.");
- }
- break;
- default:
- console.log("I didn't understand your choice. Hit Run and try again, this time picking FIGHT, PAY, or RUN!");
- }
Advertisement
Add Comment
Please, Sign In to add comment