JavaScript Study Guide for Khan Academy Study... · 2019-12-11 · 1.#Drawing#Shapes#! Examples!!...
Transcript of JavaScript Study Guide for Khan Academy Study... · 2019-12-11 · 1.#Drawing#Shapes#! Examples!!...
Khan Academy JavaScript Study Guide Contents
1. Canvas graphics commands with processing.js
2. Coloring 3. Variables – data types, assignments,
increments 4. Animation with draw loop 5. Math expressions 6. Text and Strings – display, concatenate, split 7. Functions – parameters, return values 8. Logic – if, else, logic operators and, or not 9. Debugging 10. Looping – while, for 11. Clean code 12. Arrays 13. Objects – properties, methods, inheritance 14. Object oriented design
1. How to create an account in Khan Academy Khan Academy is an online school where you watch videos, take quizzes and create programs. Your teacher will track you progress through an online gradebook. Your teacher will provide you with a class code so that he/she will become your coach. 2. What is a programming language? A programming language is a way of providing instructions to the computer. All programs including games, calculators, calendars, word processors, painting applications, web browsers etc. are written in some kind of programming language. 3. What is JavaScript? JavaScript is the most widely used programming language in the world. It is used to power nearly every web site on the Internet.
JavaScript is not to be confused with Java. Java is a probably the second most used programming language in use today. The graphic below shows usage statistics on a popular programming website, github.com As you can see, JavaScript is one of the most common languages in use today.
4. What is processing.js? Kahn Academy uses a “library” of code to extend JavaScript’s capabilities. You can read about it at www.processingjs.org Programmers often use libraries in all languages to extend the capabilities of JavaScript. 5. Escape from the Khan editor You can take your JavaScript program out of the Khan Academy window and onto any web page by following these instructions .. http://stackoverflow.com/questions/25341597/how-‐can-‐khan-‐academy-‐computer-‐programs-‐be-‐run-‐offline-‐or-‐on-‐my-‐own-‐website
1. Drawing Shapes Examples
rect(10,20,50,100); Draws a rectangle on the screen. The upper left corner is 10 pixels from the left side of the screen and 20 pixels from the top. The rectangle is 50 pixels wide and 100 pixels tall.
ellipse(10,20,50,100); Draws an ellipse (oval) on the screen. Imagine that you drew the same rectangle used earlier and filled it with an oval. The upper left corner is 10 pixels from the left side of the screen and 20 pixels from the top. The rectangle is 50 pixels wide and 100 pixels tall.
.
triangle(100, 410, 200, 200, 300, 410); Draws a triangle on the screen. The three points of the triangle are (100,410), (200,200) and (300,410). Notice that 410 is actually outside of the drawing area.
line(183, 246, 245, 230); Draws a line on the screen. The two endpoints of
the line are (183,246) and (245,230).
50 px
100 px
10,20
50 px
100 px
10,20
200,200
100,410 300,410
183,246
245,230
2. Coloring
fill(102, 255, 0);
Use the fill command to change the color of the next shapes you draw. Use numbers between 0 and 255 to create a combination of red, green and blue light. In this example, fill is used just before each of the scoops of ice cream so that each shape is a different color.
background(255,0,0); Use the background command to paint a large square on the entire canvas. Be sure to use the background command before any other drawings. If you draw a background on top of any image, the image will be hidden.
stroke(100,200,0); Use the fill command to change the color of the outline of the next shapes you draw. Use numbers between 0 and 255 to create a combination of red, green and blue light.
noStroke(); Removes the outline of the next shape drawn.
3. Variables A variable is a letter or word used to represent a value. Like letters used in Algebra, the value of a variable can change.
Variable example #1 var rectWidth = 20;
rect(10, 10, rectWidth, 90); The var command declares a variable. That is, the computer knows that this is a new variable name in the program. The equals sign, =, is called the variable assignment. In this case, the variable rectWidth now holds the number 20. This program would draw a rectangle 20 pixels wide by 90 pixels tall.
Variable Example #2 eyeSize is the value of both the width and height of the ellipse. toothHeight is the value of the height of the rectangles that are the teeth.
Variable expressions Varialbes can be used in mathematical expressions. For example, the variables x and y indicate the center of the frog face at the point (200,250). The center of the left eye is at (x-‐50, y-‐50) or (150,200) The center of the right eye is at (x+50,y-‐50) or (250,200)
4. Animation
Draw The draw function is executed many times each second. Changes to a variable inside the draw function will update the position of shapes to create movement. x = x + 10 on line 20 is the important line of code in this program. It means “Add 10 to the value of X and store the answer in the variable x”.
mouseX and mouseY Two special variables, mouseX and mouseY are the coordinates of the mouse arrow on the screen. In this program, the ball moves to follow the mouse.
5. Math expressions Use the following symbols to calculate math expressions. + addition -‐ subtraction * multiply / divide ( ) parenthesis are used to group operations. Everything you learned in math class about order of operations is important in programming. For example: var x; var y; var z; x = 10; y = 7; z = 3 * x + y; z would have the value of 37 but in this code var x; var y; var z; x = 10; y = 7; z = 3 * (x + y); z would have the value of 51. z = 3 * (10 + 7)
6. Text Strings A string is a word, character or sentence enclosed in quotation marks. text(string, x, y) is the command to write words to the screen. textSize(25) will adjust the size of the letters. For example,
7. Functions A function is a collection of statements that are executed or “called” as a group. Var drawWinston = function() { // draw shapes inside the function brackets }
Function parameters Numbers are passed to a function through variables called parameters. In this example, the function is called four times using different values for the faceX and faceY parameters.
Function return values A function can give an answer to a math formula. In this example we find out how many donuts Winston eats in a lifetime. var calcTotalDonuts = function(numYears) { return 3 * 365 * numYears; }; text(calcTotalDonuts(65), 200, 240); Processing.js special functions
1. draw() – called multiple times each second.
2. mouseMoved() – called when the mouse moves
3. mouseClicked() – called when the mouse is clicked.
Global and local variables A variable that is declared inside a function is discarded when the function ends. This is a local variable. Variables declared in the program are global and retain their value. var lifeInches = 20; // global variable var calcInches = function(startAge, endAge, inchesPerYear) { var totalInches = inchesPerYear * (endAge -‐ startAge); // local variable lifeInches += totalInches; return totalInches; };
8. Logic and if statements If statements compare two numbers and make a decision based on the answer. For example this program will reverse the direction of the ball when it reaches the edge of the screen.
Booleans A Boolean value is a “true” or “false” answer to a compare problem. For example A single Boolean check… If (score > 100) { // the score is greater than 100 } The === (check for equals) sign is used to see if two values are identical. The single equals sign (=) is reserved for assigning a value to a variable. If (lives === 0) { // you have no lives. You are dead }
The && (and) operator checks if two conditions are both true… if ((score > 100) && (lives > 0)) { // the score is greater than 100 and there are more than 0 lives remaining } The || (or) operator checks if either one of two conditions is true… if ((score > 100) || (lives > 0)) { // either the score is greater than 100 or there are more than 0 lives remaining, or both conditions are true } The ! (not) operator checks to see if something is not true If (PresidentName !== “Kennedy”) { // the person is not named Kennedy } If … else The else statement allows you to do something else if the statement is false. if (integer === 0) { // do something here } else { // do something else } else if The else if statement allows you to check another condition if the first one was false. if (number < 1) { // do something } else if (number < 2) { // do something else } else { // do this if the previous two fail }
9. Debugging You can check for errors by printing the value of variables on the screen. This lets you see if the variables are actually storing the numbers you think they should. For example notice the values at the bottom of the screen. They help you find errors in your programs.
10. Looping While loops
1. Set a variable as a counter 2. Start a while loop 3. Increase or decrease the variable. 4. The loop will stop when the while
condition is met. 5. Be careful not to create an infinite loop
that never stops. For example…
For loops A for loop always has three parts:
1. Initial variable setting 2. Conditional check 3. Increase or decrease
For example… for (var y = 63; y < 313; y += 41) { text("Pineapple pizza is the best!", 69, y); }
11. Clean Code Follow these steps to make your code easier to read.
1. Use good names for variables. var circleRadius = 4.2 is better than var cr = 4.2
2. Use indenting with if statements, functions and loops.
for (var i = numCircles; i > 1; i-‐-‐) { var radius = i * 7; ellipse(mouseX, mouseY, radius, radius); };
3. Put spaces between statements and symbols.
if (x < 10){
rect(10,10,20,30); }
is better than if(x<10){rect(10,10,20,30);}
4. Use comments to explain what you are trying to do.
// Calculate y according to the path of a parabola with respect to "t": // y = (velocity)*t -‐ (acceleration)*t^2; // We can tweak the velocity and acceleration constants for our fake world
12. Arrays Arrays are variables that store a collection of values. For example… var myFriends = ["Sophia", "John", "Leif", "Winston"]; text( myFriends[0], 10, 30); text( myFriends[1], 10, 80); text( myFriends[2], 10, 130); length The length statement counts the number of items stored in the array. For example… text("I have " + myFriends.length + " friends!!!", 10, 150); Looping through arrays Use a for loop or while loop to do something with each member of an array. For example… var myFriends = ["Sophia", "John", "Leif", "Winston", "OhNoes Guy", "Sal"]; var friendNum = 0; while(friendNum < myFriends.length) { text(myFriends[friendNum], 10, 30+friendNum*30); friendNum++; } Or like this… var myFriends = ["Sophia", "John", "Leif", "Winston", "OhNoes Guy", "Sal"]; for(var friendNum=0;friendNum< myFriends.length; friendNum++) { text(myFriends[friendNum], 10, 30+friendNum*30); }
push You can add items to an array with the push statement. For example…
13. Objects Objects are collections of properties and actions used together to describe something. For example Winston has properties…
Properties of an object can be modified. For example… while(winston.age <= 40) { text("Winston is " + winston.age + " years old", 10, winston.age*20 -‐ 350); winston.age++; if (winston.age === 30) { winston.wife = "Winnefer"; } if (winston.age === 32) { winston.twins = ["Winston, JR", "Winstonia"]; } }
Objects are often stored in arrays. For example…
14. Object oriented design Objects are often created with a constructor function. The function uses the “this” keyword when referring to the object being created. For example…
Adding actions to an object with methods A method is a function that gives an object action. You can use the prototype keyword to add a function to an object.
Object Inheritance Objects are based on other objects. In the following example, creature is the first object and Winston and Hopper are descendants of creature.