Guest User

Untitled

a guest
Jun 9th, 2015
319
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.97 KB | None | 0 0
  1. length:
  2. "Maddie".length
  3.  
  4. * = muliplcation
  5. / = division
  6.  
  7. // = notes to self or others, not computer
  8.  
  9. confirm("I am great.");
  10. prompt("Where are you from?")
  11.  
  12. console.log(2*5)
  13. console.log ()= prints out whatever is in ()
  14.  
  15. 3 data types:
  16. string (e.g. "hello friends!")
  17. numbers (e.g. 4, 10)
  18. booleans (e.g. false, 5 > 4)
  19.  
  20. comparision operators
  21. > greater than
  22. < less than
  23. >= greater than or equal to
  24. <= less than or equal to
  25. === equal to
  26. !== not equal to
  27.  
  28. if statement:
  29. if (){ () }
  30. if/else statement:
  31. if () { () } else { () }
  32. if (10<4) {console.log ("The condition is true.")}
  33. else {console.log ("The condition is false.")}
  34. eg:
  35. print out else statement
  36. if ("Maddie".length > 7)
  37. {console.log ("Maddie is great")}
  38. else {console.log ("I finished my first course!")}
  39.  
  40. variables:
  41. // Declare a variable on line 3 called
  42. // myCountry and give it a string value.
  43. var myCountry = "USA";
  44. myCountry.substring(0,3)
  45. // Use console.log to print out the length of the variable myCountry.
  46. console.log ("USA".length)
  47. // Use console.log to print out the first three letters of myCountry.
  48. console.log ("USA".substring(0,3))
  49.  
  50. change variable values:
  51. // On line 2, declare a variable myName and give it your name.
  52. var myName = "Maddie";
  53. // On line 4, use console.log to print out the myName variable.
  54. console.log(myName);
  55. // On line 7, change the value of myName to be just the first 2
  56. // letters of your name.
  57. var myName = "Ma";
  58. // On line 9, use console.log to print out the myName variable.
  59. console.log(myName)
  60.  
  61. eg:
  62. //create variable myColor and give it string value
  63. var myColor = "red"; myColor.substring(0,3);
  64. //print length of myColor to console
  65. console.log ("red".length)
  66.  
  67. Bieber if/else game:
  68. confirm("I am ready to play!");// Check if the user is ready to play!
  69.  
  70. var age= 13;
  71. var age= prompt("What's you age");
  72. if(age<13)
  73. {(console.log("You may play, but we take no responsibility"))}
  74. else
  75. {console.log("Play on!")}
  76.  
  77. console.log("You are at a Justin Bieber concert, and you hear this lyric 'Lace my shoes off, start racing.'")
  78. console.log("Suddenly, Bieber stops and says, 'Who wants to race me?'")
  79. var userAnswer= "yes"
  80. prompt("Do you want to race Bieber on stage?")
  81.  
  82. if (userAnswer==="yes")
  83. {(console.log("You and Bieber start racing. It's neck and neck! You win by a shoelace!"))}
  84. else
  85. {console.log("Oh no! Bieber shakes his head and sings 'I set a pace, so I can race without pacing.'")}
  86.  
  87. var feedback=10;
  88. prompt("Please rate the game out of 10");
  89. if (feedback<8)
  90. {console.log("Thank you! We should race at the next concert!")}
  91. else
  92. {console.log("I'll keep practicing coding and racing")}
  93.  
  94. Functions (takes in inputs, does something with them and produces an output):
  95. eg:
  96. // This is what a function looks like:
  97.  
  98. var divideByThree = function (number) {
  99. var val = number / 3;
  100. console.log(val);
  101. };
  102.  
  103. // On line 12, we call the function by name
  104. // Here, it is called 'dividebythree'
  105. // We tell the computer what the number input is (i.e. 6)
  106. // The computer then runs the code inside the function!
  107. divideByThree(6);
  108.  
  109. Function eg:
  110. var sayHello = function(name) {
  111. console.log('Hello ' + name);
  112. };
  113. the code in ()= parameter(which is a spaceholder word that we give a value when we call the function)
  114. call the code by doing this, it will print out HelloEmily:
  115. sayHello("Emily");
  116.  
  117. Function eg:
  118. // Below is the greeting function!
  119. // See line 7
  120. // We can join strings together using the plus sign (+)
  121. // See the hint for more details about how this works.
  122.  
  123. var greeting = function (name) {
  124. console.log("Great to see you," + " " + name);
  125. };
  126. greeting("Maddie");
  127.  
  128. When we want to join together two strings, we put a plus sign.
  129. console.log("Hey" + "you"); will print out Heyyou. That's not what we want!
  130. If you want a space between words, you must add that space as well!
  131. console.log("Hey" + " " + "you"); will print out Hey you
  132. This joining of strings is called concatenation
  133.  
  134. Function eg:
  135. var functionName = function( ) {
  136. // code code code
  137. // code code code
  138. // (more lines of code)
  139. };
  140.  
  141. The var keyword declares a variable named functionName.
  142. The keyword function tells the computer that functionName is a function and not something else.
  143. Parameters go in the parentheses. The computer will look out for it in the code block.
  144. The code block is the reusable code that is between the curly brackets { }. Each line of code inside { } must end with a semi-colon.
  145. The entire function ends with a semi-colon.
  146. 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.
  147.  
  148. Function eg:
  149. var foodDemand =function(food) {
  150. console.log("I want to eat" + " " + food);
  151. }
  152. foodDemand("burrito");
  153.  
  154. Function eg DRY:
  155. var orangeCost=function(price) {
  156. console.log(price * 5);
  157. }
  158. orangeCost(5);
  159.  
  160. You are a creature of habit. Every week you buy 5 oranges. But orange prices keep changing!
  161. You want to declare a function that calculates the cost of buying 5 oranges.
  162. You then want to calculate the cost of the 5 all together.
  163. Write a function that does this called orangeCost().
  164. It should take a parameter that is the cost of an orange, and multiply it by 5.
  165. It should log the result of the multiplication to the console.
  166. Call the function where oranges each cost 5 dollars.
  167.  
  168. 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.
  169. eg:
  170. // Parameter is a number, and we do math with that parameter
  171. var timesTwo = function(number) {
  172. return number * 2;
  173. };
  174.  
  175. // Call timesTwo here!
  176. var newNumber = timesTwo(3)
  177. console.log(newNumber);
  178.  
  179. Functions return and if/else:
  180. eg:
  181. // Define quarter here.
  182. var quarter= function(number) {
  183. return number / 4;
  184. };
  185.  
  186. if (quarter(0) % 3 === 0 ) {
  187. console.log("The statement is true");
  188. } else {
  189. console.log("The statement is false");
  190. }
  191.  
  192. Function w/2 parameters:
  193. eg:
  194. var areaBox = function(length, width) {
  195. return length * width;
  196. };
  197. eg:
  198. Write a function called perimeterBox that returns the perimeter of a rectangle.
  199. It should have two parameters.
  200. One formula for perimeter is length + length + width + width;
  201. Call the function and pass in any value for length and width you like.
  202.  
  203. var perimeterBox = function(length, width) {
  204. return length + length + width + width;
  205. };
  206. perimeterBox(5,4)
  207.  
  208. Global vs Local variables:
  209. Scope: local or global
  210. Global: variable defines outside a function are accessible anywhere once declared.
  211. eg:
  212. var globalVar = "hello";
  213.  
  214. var foo = function() {
  215. console.log(globalVar); // prints "hello"
  216. }
  217.  
  218. Local: variable defined inside function, cannot be accessed outside that function.
  219. eg:
  220. var bar = function() {
  221. var localVar = "howdy";
  222. }
  223.  
  224. console.log(localVar); // error
  225.  
  226. If/ else if/ else statement:
  227. if (condition1) {
  228. code code code;
  229. } else if (condition2) {
  230. code code code;
  231. } else {
  232. code code code;
  233. }
  234.  
  235. nested if + if/else statement:
  236. eg:
  237. var compare = function(choice1,choice2){
  238. if (choice1 == choice2) {
  239. return "The result is a tie!";
  240. }
  241. if (choice1 == "rock") {
  242. if (choice2 == "scissors") {
  243. return "Rock wins";
  244. } else {
  245. return "paper wins";
  246. }
  247. }
  248. if (choice1 == "paper") {
  249. if (choice2 == "rock") {
  250. return "paper wins";
  251. } else {
  252. return "scissors wins";
  253. }
  254. }
  255. }
  256.  
  257. for Loops:
  258. eg:
  259. for (var counter = 1; counter < 11; counter++) {
  260. console.log(counter);
  261. } //prints out numbers 1-11
  262.  
  263. general for loop syntax:
  264. for (var i = 1; i < 11; i = i + 1) {
  265. /* your code here */;
  266. }
  267.  
  268. for loop rules:
  269. a. A more efficient way to code to increment up by 1 is to write i++.
  270. b. We decrement down by 1 by writing i--.
  271. 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.
  272. d. We can decrement down by any value by writing i -= x. (See the Hint for more.)
  273. 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!
  274. Note: x += y is the same as x = x + y. And x -= y is the same as x = x - y.
  275. for loops only run when the condition is true.
  276.  
  277. Arrays:
  278. a. store lists of data
  279. b. can store different data types at the same time
  280. c. are ordered so the position of each piece of data is fixed
  281.  
  282. eg:
  283. var names = ["Mao","Gandhi","Mandela"];
  284.  
  285. var sizes = [4, 6, 3, 2, 1, 9];
  286.  
  287. var mixed = [34, "candy", "blue", 11];
  288.  
  289. array syntax:
  290. var arrayName = [data, data, data];
  291.  
  292. Any time you see data surrounded by [ ], it is an array.
  293.  
  294. Array and Loop eg:
  295. var cities = ["NYC", "Seattle", "Buffalo", "Paris", "Berlin", "LA", "Portland"];
  296.  
  297. for (var i = 0; i < cities.length; i++) {
  298. console.log("I would like to visit " + cities[i]);
  299. } //prints out all cities with phrase in front of it
  300.  
  301. push //add
  302.  
  303. Text:
  304. 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:
  305.  
  306. /*jshint multistr:true */ =tells the computer not to mind the (\)
  307.  
  308. eg:
  309. text = "Blah blah blah blah blah blah Eric \
  310. blah blah blah Eric blah blah Eric blah blah \
  311. blah blah blah blah blah Eric";
  312.  
  313. var myName = "Eric";
  314. var hits = [];
  315.  
  316. // Look for "E" in the text
  317. for(var i = 0; i < text.length; i++) {
  318. if (text[i] === "E") {
  319. // If we find it, add characters up to
  320. // the length of my name to the array
  321. for(var j = i; j < (myName.length + i); j++) {
  322. hits.push(text[j]);
  323. }
  324. }
  325. }
  326.  
  327. if (hits.length === 0) {
  328. console.log("Your name wasn't found!");
  329. } else {
  330. console.log(hits);
  331. }
  332.  
  333. eg:
  334. /*jshint multistr:true */
  335. var text = "Maddie went to Park Slope \ she didn't ride her bike. Maddie saw \ her mom. Maddie's mom is nice.";
  336.  
  337. var myName = "Maddie";
  338.  
  339. var hits = [];
  340.  
  341. for(var i = 0; i < text.length; i ++) {
  342. if (text[i] === "M") {
  343. for(var j = i; j < (myName.length + i); j++) {
  344. hits.push(text[j]);
  345. }
  346. }
  347. }
  348. if (hits.length = 0) {
  349. console.log ("Your name wasn't found!");
  350. } else {
  351. console.log(hits);
  352. }
  353.  
  354. 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.
  355. eg:
  356. var coinFace = Math.floor(Math.random() * 2);
  357.  
  358. while(coinFace === 0){
  359. console.log("Heads! Flipping again...");
  360. var coinFace = Math.floor(Math.random() * 2);
  361. }
  362. console.log("Tails! Done flipping.");
  363. //In line 1, we create a variable named coinFace, which is a random number that is either 0 (heads) or 1 (tails).
  364. 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.
  365. If coinFace is 1 (tails), then the condition will be false, so we break out of the while loop and print Tails! Done flipping.
  366.  
  367. 1= true
  368. 0= false
  369.  
  370. while loop eg:
  371. var understand = true;
  372.  
  373. while(understand === true){
  374. console.log("I'm learning while loops!");
  375. understand = false;
  376. }
  377.  
  378. while loop eg:
  379. var condition = true;
  380. while(condition) {
  381. console.log("Hello!");
  382. // Avoid infinite loops!
  383. condition = false;
  384. }
  385.  
  386. while loop eg:
  387. var soloLoop = function(){
  388. //Your code goes here!
  389. while(soloLoop) {
  390. console.log ("Looped once!");
  391. soloLoop = false
  392. }
  393. };
  394.  
  395. soloLoop(true);
  396.  
  397. infinite loops:
  398. 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!
  399. To prevent this from happening, you always need a way to ensure the condition between your while parentheses can change.
  400.  
  401. while loop eg:
  402. var loop = function(loop){
  403. var count= 0;
  404. while(count < 3){
  405. console.log("I'm looping!");
  406. count++;
  407. }
  408. };
  409.  
  410. loop();
  411.  
  412. eg:
  413. var myCondition = true;
  414.  
  415. while(myCondition) {
  416. console.log("Looped once!");
  417. myCondition = false;
  418. }
  419.  
  420. soloLoop(true);
  421.  
  422. do/while loop:to make sure your loop runs at least one time no matter what.
  423. 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.
  424.  
  425. do/while loop eg:
  426. var loopCondition = false;
  427.  
  428. do {
  429. console.log("I'm gonna stop looping 'cause my condition is " + loopCondition + "!");
  430. } while (loopCondition);
  431.  
  432. eg:
  433. var getTo = false;
  434. var getToDaChoppa = function(){
  435. do {
  436. console.log("the chopper , " + String(getTo) + "!");
  437. } while(getTo);
  438. };
  439.  
  440. getToDaChoppa();
  441. do/while eg:
  442. // Can be false from the start, since
  443. // do/while runs at least one time
  444. var condition = false;
  445. do {
  446. console.log("I'm printed once!");
  447. } while(condition);
  448.  
  449. Dragon Game:
  450. var slaying = true;
  451. // A bit of new math magic to calculate the odds
  452. // of hitting the dragon. We'll cover this soon!
  453. var youHit = Math.floor(Math.random() * 2);
  454. var damageThisRound = Math.floor(Math.random() * 5 + 1);
  455. var totalDamage = 0;
  456.  
  457. while (slaying) {
  458. if (youHit) {
  459. console.log("You hit the dragon and did " + damageThisRound + " damage!");
  460. totalDamage += damageThisRound;
  461.  
  462. if (totalDamage >= 4) {
  463. console.log("You did it! You slew the dragon!");
  464. slaying = false;
  465. } else {
  466. youHit = Math.floor(Math.random() * 2);
  467. }
  468. } else {
  469. console.log("The dragon burninates you! You're toast.");
  470. slaying = false;
  471. }
  472. }
  473.  
  474. Dragon Game eg 2:
  475. var slaying= true;
  476. var youHit= Math.floor(Math.random() *2);
  477. var damageThisRound= Math.floor(Math.random() *5 + 1);
  478. var totalDamage= 0;
  479.  
  480. var slaying= true;
  481. while(slaying) {
  482. if (youHit) {
  483. console.log ("You hit!");
  484. totalDamage += damageThisRound;
  485. if (totalDamage >= 4) {
  486. console.log("You win!");
  487. slaying = false;
  488. } else {
  489. youHit= Math.floor(Math.random() * 2);
  490. }
  491. } else {
  492. console.log ("You missed!");
  493. }
  494. slaying= false
  495. }
  496.  
  497. if/else syntax:
  498. if (/* Some condition */) {
  499. // Do something
  500. } else if (/* Some other condition */) {
  501. // Do something else
  502. } else { // Otherwise
  503. // Do a third thing
  504. }
  505.  
  506. isNaN: If you call isNaN on something, it checks to see if that thing is not a number.
  507. eg:
  508. isNaN('berry'); // => true
  509. isNaN(NaN); // => true
  510. isNaN(undefined); // => true
  511. isNaN(42); // => false
  512.  
  513. note:
  514. You can't just do:
  515. isNaN(unicorns);
  516. unless you've already defined the variable unicorns. You can, however, do
  517. isNaN("unicorns"); // => true
  518.  
  519. 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.
  520.  
  521. switch syntax:
  522. switch (/*Some expression*/) {
  523. case 'option1':
  524. // Do something
  525. break;
  526. case 'option2':
  527. // Do something else
  528. break;
  529. case 'option3':
  530. // Do a third thing
  531. break;
  532. default:
  533. // Do yet another thing
  534. }
  535.  
  536. switch eg:
  537. var lunch = prompt("What do you want for lunch?","Type your lunch choice here");
  538. switch(lunch){
  539. case 'sandwich':
  540. console.log("Sure thing! One sandwich, coming up.");
  541. break;
  542. case 'soup':
  543. console.log("Got it! Tomato's my favorite.");
  544. break;
  545. case 'salad':
  546. console.log("Sounds good! How about a caesar salad?");
  547. break;
  548. case 'pie':
  549. console.log("Pie's not a meal!");
  550. break;
  551. default:
  552. console.log("Huh! I'm not sure what " + lunch + " is. How does a sandwich sound?");
  553. }
  554.  
  555. Logical Operators:
  556. and (&&)
  557. or (||)
  558. not (!)
  559.  
  560. eg:
  561. var iLoveJavaScript = true;
  562. var iLoveLearning = true;
  563.  
  564. if(iLoveJavaScript && iLoveLearning) {
  565. // if iLoveJavaScript AND iLoveLearning:
  566. console.log("Awesome! Let's keep learning!");
  567. } else if(!(iLoveJavaScript || iLoveLearning)) {
  568. // if NOT iLoveJavaScript OR iLoveLearning:
  569. console.log("Let's see if we can change your mind.");
  570. } else {
  571. console.log("You only like one but not the other? We'll work on it.");
  572. }
  573.  
  574. And (&&): evaluates to true when both expressions are true; if they're not, it evaluates to false.
  575. true && true; // => true
  576. true && false; // => false
  577. false && true; // => false
  578. false && false; // => false
  579.  
  580. Or (||): evaluates to true when one or the other or both expressions are true; if they're not, it evaluates to false.
  581. true || true; // => true
  582. true || false; // => true
  583. false || true; // => true
  584. false || false; // => false
  585.  
  586. Not (!): makes true expressions false, and vice-versa.
  587. !true; // => false
  588. !false; // => true
  589.  
  590. Troll video game:
  591. 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();
  592.  
  593. switch(troll) {
  594. case 'FIGHT':
  595. var strong = prompt("How courageous! Are you strong (YES or NO)?").toUpperCase();
  596. var smart = prompt("Are you smart?").toUpperCase();
  597. if(strong === 'YES' || smart === 'YES') {
  598. console.log("You only need one of the two! You beat the troll--nice work!");
  599. } else {
  600. 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!");
  601. }
  602. break;
  603. case 'PAY':
  604. var money = prompt("All right, we'll pay the troll. Do you have any money (YES or NO)?").toUpperCase();
  605. var dollars = prompt("Is your money in Troll Dollars?").toUpperCase();
  606. if(money === 'YES' && dollars === 'YES') {
  607. console.log("Great! You pay the troll and continue on your merry way.");
  608. } else {
  609. console.log("Dang! This troll only takes Troll Dollars. You get whomped!");
  610. }
  611. break;
  612. case 'RUN':
  613. var fast = prompt("Let's book it! Are you fast (YES or NO)?").toUpperCase();
  614. var headStart = prompt("Did you get a head start?").toUpperCase();
  615. if(fast === 'YES' || headStart === 'YES') {
  616. console.log("You got away--barely! You live to stroll through the forest another day.");
  617. } else {
  618. console.log("You're not fast and you didn't get a head start? You never had a chance! The troll eats you.");
  619. }
  620. break;
  621. default:
  622. console.log("I didn't understand your choice. Hit Run and try again, this time picking FIGHT, PAY, or RUN!");
  623. }
Advertisement
Add Comment
Please, Sign In to add comment