We have now our canvas for you to try out! YAY!
Try it out as long as you want, but we recommend to you to save your own code or write it down in somewhere because it won't save. Thanks!
Check it out!
Try it out as long as you want, but we recommend to you to save your own code or write it down in somewhere because it won't save. Thanks!
Check it out!
Basic |
|
Link: www.khanacademy.org/cs/ and http://www.youtube.com/channel/UCye0TMXdb_zdfvVgXA0XtkA (multiple videos) see also there if you want to learn more. We don't own any right. Only educational purposes. |
Here's what we covered in this tutorial on variables.
A variable is a way to store values. To use a variable, we must both "declare" it, to let the program know about the variable, and then we must "assign" it, to let the program know what value we are storing in the variable.
Here's how we would declare a variable named "xPos":
var xPos;
Now, we can assign it to hold the value 10:
xPos = 10;
If we want to (and we often do!), we can declare and assign it in one statement:
var xPos = 10;
If, for some reason, we want to change the value of a variable later, we can "re-assign" it:
var xPos = 10; // some time later ... xPos = 20;
We'll soon see why re-assignment can be useful.
A variable can store the result of any expression, so a variable's value can be computed based on the values of other variables:
var bodySize = 300; var headSize = bodySize/3; // 100 var noseSize = headSize/2; // 50
How can we pick names for our variables? For variables in JavaScript, follow these rules:
A variable is a way to store values. To use a variable, we must both "declare" it, to let the program know about the variable, and then we must "assign" it, to let the program know what value we are storing in the variable.
Here's how we would declare a variable named "xPos":
var xPos;
Now, we can assign it to hold the value 10:
xPos = 10;
If we want to (and we often do!), we can declare and assign it in one statement:
var xPos = 10;
If, for some reason, we want to change the value of a variable later, we can "re-assign" it:
var xPos = 10; // some time later ... xPos = 20;
We'll soon see why re-assignment can be useful.
A variable can store the result of any expression, so a variable's value can be computed based on the values of other variables:
var bodySize = 300; var headSize = bodySize/3; // 100 var noseSize = headSize/2; // 50
How can we pick names for our variables? For variables in JavaScript, follow these rules:
- Variable names should begin with letters, "$" or "_" and only contain letters, numbers, "$" and "_"
- Variable names are "case sensitive" - that means that "xPos" is different from "xpos", so make sure you are consistent with how you type it.
- Variable names can't be the same as existing variable names, and there are a lot in our ProcessingJS programming environment. If you ever see an error pop up like "Read only!", try changing your variable name.
- Variable names should be clear and meaningful - for example, instead of "ts", use "toothSize".
- Variable names should use "camel case" for multiple words, like "toothSize" instead of "toothsize" or "tooth_size".
Here's a review of what we covered in this tutorial on text.
Before this tutorial, we were using number values for most things- passing numbers into functions, storing numbers in variables, etc. As you've now seen, we can also use text values, and we call those strings in JavaScript - think of them as a "string" of letters.
To create a string, we surround text in matching quotation marks:
"Hello World!"
We have to actually do something with that string - like pass it to the text() command:
text("Hello World!", 100, 100);
We could also store it in a variable, and then pass that variable into the text() command:
var myGreeting = "Hello World!"; text(myGreeting, 100, 100);
Note that we can also use single quotation marks:
var myGreeting = 'Hello World!';
But we *can't* mix and match quotation marks - that's an error! Pick either single or double marks, and stick with it.
var myGreeting = 'Hello World!"; // oh noes!
Just like we can manipulate number values, we can also manipulate strings, like if we want to add one string to another string:
var myGreeting = "Alo"; var myName = "Winston"; var sayHello = myGreeting + ", " + myName + "!"; // Alo, Winston!
We can also combine strings with number values, like so:
var xPos = 10; var yPos = 20; var label = "The coordinates are " + xPos + ", " + yPos;
We also saw that we can use different commands to change the text size and text font when we display string using the text() command. You can read more about those in the text section of our documentation.
Before this tutorial, we were using number values for most things- passing numbers into functions, storing numbers in variables, etc. As you've now seen, we can also use text values, and we call those strings in JavaScript - think of them as a "string" of letters.
To create a string, we surround text in matching quotation marks:
"Hello World!"
We have to actually do something with that string - like pass it to the text() command:
text("Hello World!", 100, 100);
We could also store it in a variable, and then pass that variable into the text() command:
var myGreeting = "Hello World!"; text(myGreeting, 100, 100);
Note that we can also use single quotation marks:
var myGreeting = 'Hello World!';
But we *can't* mix and match quotation marks - that's an error! Pick either single or double marks, and stick with it.
var myGreeting = 'Hello World!"; // oh noes!
Just like we can manipulate number values, we can also manipulate strings, like if we want to add one string to another string:
var myGreeting = "Alo"; var myName = "Winston"; var sayHello = myGreeting + ", " + myName + "!"; // Alo, Winston!
We can also combine strings with number values, like so:
var xPos = 10; var yPos = 20; var label = "The coordinates are " + xPos + ", " + yPos;
We also saw that we can use different commands to change the text size and text font when we display string using the text() command. You can read more about those in the text section of our documentation.
This is a review of what we covered in this tutorial on functions.
We often want to be able to re-execute blocks of code when we are writing programs, without having to re-write the block of code entirely. We need a way of grouping code together and giving it a name, so that we can call it by that name later, and that's what we call a function.
To create a function, we must first declare it and give it a name, the same way we'd create any variable, and then we follow it by a function definition:
var sayHello = function() { };
We could put any code inside that function - one statement, multiple statements - depends what we want to do. In this function, we could just output a message at a random location:
var sayHello = function() { text("Halllllllo!", random(200), random(200)); };
Now, if all we do is declare the function, nothing will happen. In order for the program to execute the code that's inside the function, we actually have to "call" the function, by writing its name followed by empty parenthesis:
sayHello();
And then we could call it whenever we wanted, as many times as we wanted!
sayHello(); sayHello(); sayHello();
We often want to be able to customize functions, to tell the program "well, do all of this code, but change a few things about how you do it." That way we have code that is both reusable *and* flexible, the best of both worlds. We can achieve that by specifying "arguments" for a function, using those arguments to change how the function works, and passing them in when we call the function.
For example, what if we wanted to be able to say exactly where we want the message displayed, just like we can say exactly where we want to draw rect()s and ellipse()s? We could imagine calling it like so, to put the message at two precise coordinates:
sayHello(50, 100); sayHello(150, 200);
To make that work, we need to change our sayHello function definition so it knows that it will receive 2 arguments, and then uses them inside:
var sayHello = function(xPos, yPos) { text("Halllllllo!", xPos, yPos); };
The arguments that get passed in basically become like variables inside your function definition, and the names depend on what you call them in the parentheses. We could just as easily rename them to something shorter:
var sayHello = function(x, y) { text("Halllllllo!", x, y); };
Our functions can accept any number of arguments - zero, one, two, or more. We could have also decided that we wanted to change our function to accept a name to say hello to:
var sayHello = function(name) { text("Halllllllo, " + name, random(200), random(200)); };
And then we would have called it like so:
sayHello("Winston"); sayHello("Pamela");
We could combine those ideas, and have it accept three arguments, for the name and position:
var sayHello = function(name, x, y) { text("Halllllllo " + name, x, y); };
And then call it like so:
sayHello("Winston", 10, 100);
It really depends on what you want your functions to do, and how much you want to customize what they can do. You can always start off with no arguments, and then add more as you realize you need them.
Now, you've actually been calling functions this whole time- that's how you've been making drawing and animations - like with rect, ellipse, triangle, etc. All of those functions are ones that come from the ProcessingJS library, and we load them into every program that you make here, so that you can always use them. We've defined the functions for you, because we thought they'd be useful, and now it's up to you to decide what custom functions you want to use in your own programs. For example, we provide the ellipsefunction, but we don't provide a cat function - if your program involves a lot of different cats in different locations, maybe you should create your own cat function!
There's another powerful thing we can do with functions - we can use them to take in some values, compute them, and return a new value. Think about all the things you can do with a calculator - add values, subtract, calculate square root, multiply, etc. All of those would be done with functions that took in the input and outputted the result. The functions would take in the input as arguments and output the result using a return statement. Here's a function that adds two numbers and returns the result:
var addNumbers = function(num1, num2) { var result = num1 + num2; return result; }; var sum = addNumbers(5, 2); text(sum, 200, 200); // Displays "7"
The return statement does two things: it gives a value back to whoever called it (which is why we could store it in the sum variable), and it immediately exits the function. That means it'd be silly if we had something like this, because that last line would never get executed:
var addNumbers = function(num1, num2) { var result = num1 + num2; return result; result = result * 2; // silly! };
Functions with return values are quite useful for manipulating data in programs, and they can be combined together in expressions, too:
var biggerSum = addNumbers(2, 5) + addNumbers(3, 2);
You can even call functions inside function calls, although that can get hard to read at times:
var hugeSum = addNumbers(addNumbers(5, 2), addNumbers(3, 7));
Now that you know how to create functions that wrap around blocks of code, we have to bring up an important concept: local variables versus global variables.
When we declare a new variable *inside* a function, we say that it is local to that function. That's because only that function can see that variable - the rest of the program outside of it cannot. Once we're outside that function, it's like it no longer exists. In the following function, localResult is a local variable:
var addNumbers = function(num1, num2) { var localResult = num1 + num2; println("The local result is: " + localResult); return localResult; }; addNumbers(5, 7); println(localResult); // oh noes!
When we run that code, we'll get an error on the final line: "localResult is not defined." The variable is only defined inside the function, because that's where we declared it with thevar localResult = line, and is not defined outside of it.
When we declare a variable outside our functions, we say that it is a global variable. That's because all functions can now access it and do whatever they want with it.
var globalResult; var addNumbers = function(num1, num2) { globalResult = num1 + num2; println("The global result is: " + globalResult); }; addNumbers(5, 7); println(globalResult);
When we run the above code, we will not get an error, because we declaredglobalResult outside of the function, so we can access it wherever we want.
Every programming language is different, but for JavaScript, it's important to know that variables have "function scope" - a function can see the local variables that were declared inside of it and the global variables that were declared outside of it, but it cannot see the local variables inside other functions.
We often want to be able to re-execute blocks of code when we are writing programs, without having to re-write the block of code entirely. We need a way of grouping code together and giving it a name, so that we can call it by that name later, and that's what we call a function.
To create a function, we must first declare it and give it a name, the same way we'd create any variable, and then we follow it by a function definition:
var sayHello = function() { };
We could put any code inside that function - one statement, multiple statements - depends what we want to do. In this function, we could just output a message at a random location:
var sayHello = function() { text("Halllllllo!", random(200), random(200)); };
Now, if all we do is declare the function, nothing will happen. In order for the program to execute the code that's inside the function, we actually have to "call" the function, by writing its name followed by empty parenthesis:
sayHello();
And then we could call it whenever we wanted, as many times as we wanted!
sayHello(); sayHello(); sayHello();
We often want to be able to customize functions, to tell the program "well, do all of this code, but change a few things about how you do it." That way we have code that is both reusable *and* flexible, the best of both worlds. We can achieve that by specifying "arguments" for a function, using those arguments to change how the function works, and passing them in when we call the function.
For example, what if we wanted to be able to say exactly where we want the message displayed, just like we can say exactly where we want to draw rect()s and ellipse()s? We could imagine calling it like so, to put the message at two precise coordinates:
sayHello(50, 100); sayHello(150, 200);
To make that work, we need to change our sayHello function definition so it knows that it will receive 2 arguments, and then uses them inside:
var sayHello = function(xPos, yPos) { text("Halllllllo!", xPos, yPos); };
The arguments that get passed in basically become like variables inside your function definition, and the names depend on what you call them in the parentheses. We could just as easily rename them to something shorter:
var sayHello = function(x, y) { text("Halllllllo!", x, y); };
Our functions can accept any number of arguments - zero, one, two, or more. We could have also decided that we wanted to change our function to accept a name to say hello to:
var sayHello = function(name) { text("Halllllllo, " + name, random(200), random(200)); };
And then we would have called it like so:
sayHello("Winston"); sayHello("Pamela");
We could combine those ideas, and have it accept three arguments, for the name and position:
var sayHello = function(name, x, y) { text("Halllllllo " + name, x, y); };
And then call it like so:
sayHello("Winston", 10, 100);
It really depends on what you want your functions to do, and how much you want to customize what they can do. You can always start off with no arguments, and then add more as you realize you need them.
Now, you've actually been calling functions this whole time- that's how you've been making drawing and animations - like with rect, ellipse, triangle, etc. All of those functions are ones that come from the ProcessingJS library, and we load them into every program that you make here, so that you can always use them. We've defined the functions for you, because we thought they'd be useful, and now it's up to you to decide what custom functions you want to use in your own programs. For example, we provide the ellipsefunction, but we don't provide a cat function - if your program involves a lot of different cats in different locations, maybe you should create your own cat function!
There's another powerful thing we can do with functions - we can use them to take in some values, compute them, and return a new value. Think about all the things you can do with a calculator - add values, subtract, calculate square root, multiply, etc. All of those would be done with functions that took in the input and outputted the result. The functions would take in the input as arguments and output the result using a return statement. Here's a function that adds two numbers and returns the result:
var addNumbers = function(num1, num2) { var result = num1 + num2; return result; }; var sum = addNumbers(5, 2); text(sum, 200, 200); // Displays "7"
The return statement does two things: it gives a value back to whoever called it (which is why we could store it in the sum variable), and it immediately exits the function. That means it'd be silly if we had something like this, because that last line would never get executed:
var addNumbers = function(num1, num2) { var result = num1 + num2; return result; result = result * 2; // silly! };
Functions with return values are quite useful for manipulating data in programs, and they can be combined together in expressions, too:
var biggerSum = addNumbers(2, 5) + addNumbers(3, 2);
You can even call functions inside function calls, although that can get hard to read at times:
var hugeSum = addNumbers(addNumbers(5, 2), addNumbers(3, 7));
Now that you know how to create functions that wrap around blocks of code, we have to bring up an important concept: local variables versus global variables.
When we declare a new variable *inside* a function, we say that it is local to that function. That's because only that function can see that variable - the rest of the program outside of it cannot. Once we're outside that function, it's like it no longer exists. In the following function, localResult is a local variable:
var addNumbers = function(num1, num2) { var localResult = num1 + num2; println("The local result is: " + localResult); return localResult; }; addNumbers(5, 7); println(localResult); // oh noes!
When we run that code, we'll get an error on the final line: "localResult is not defined." The variable is only defined inside the function, because that's where we declared it with thevar localResult = line, and is not defined outside of it.
When we declare a variable outside our functions, we say that it is a global variable. That's because all functions can now access it and do whatever they want with it.
var globalResult; var addNumbers = function(num1, num2) { globalResult = num1 + num2; println("The global result is: " + globalResult); }; addNumbers(5, 7); println(globalResult);
When we run the above code, we will not get an error, because we declaredglobalResult outside of the function, so we can access it wherever we want.
Every programming language is different, but for JavaScript, it's important to know that variables have "function scope" - a function can see the local variables that were declared inside of it and the global variables that were declared outside of it, but it cannot see the local variables inside other functions.
This is a review of what we covered in this tutorial on logic and if statements.
We often want to be able to "conditionally" do things in our programs - we want to be able to say "if this thing is true, then do X but if this other thing is true, then do Y." It's like when we wake up in the morning - "if its raining outside, then I wear an umbrella, but if its sunny, I wear sunglasses." We can do things conditionally in our programs using if statements andif/else statements combined with conditional expressions.
An if statement tells the program to execute a block of code, as long as a condition is true. In the code below, we output a message only if x is greater than 0:
var x = 5; if (x > 0) { text('x is a positive number!', 200, 200); }
Since x is 5, which is greater than 0, we would see the message on the canvas. If we changed x to -1, we wouldn't see the message show up at all, since x wouldn't be greater than 0.
The x > 0 is what we call a conditional expression - which means it's an expression that evaluates to either true or false. When a value is either true or false, we call it aboolean value (as opposed to a number or a string). For example, we could just display the conditional expression:
text(x > 0, 200, 200); // Displays "true"
We could also store it into a variable and then display it:
var isPositive = x > 0; text(isPositive, 200, 200);
We would then say that isPositive is storing a boolean value, because it's either trueor false, depending on what we set x to.
We have many ways of creating conditional expressions that will evaluate to true orfalse, because we have many comparison operators. Here are the most popular:
Assuming the following variable, here are the most common comparison operators and expressions that would be true with them:
var myAge = 28;
OperatorMeaningTrue expressions===Strict equalitymyAge === 28!==Strict inequalitymyAge !== 29
28 !== '28'>Greater thanmyAge > 25
'28' > 25>=Greater than or equalmyAge >= 28
'28' >= 25<Less thanmyAge < 30
'28' < 30<=Less than or equalmyAge <= 28
'28' <= 28It is a very common mistake to confuse the assignment operator (=) with the equality operator (===), because they both use equal signs, but they are quite different. The assignment operator will actually change the value of the variable, whereas the equality operator will just read the value of the variable and see if it's equal to something. For example:
var x = 2 + 2; // Sets it equal to 4 if (x === 4) { // Asks the question, "does this equal 4?" text("yep, 2 + 2 = 4!", 200, 200); }
We sometimes want to combine multiple comparisons together in a conditional expression, and that's why we have logical operators. These operators let us say things like "if both X and Y are true" or "if either X or Y are true" in our programs.
If we want to require that two conditions are both true, we can use the && operator ("and"):
var degreesOutside = 70; var numberOfClouds = 50; if (degreesOutside < 70 && numberOfClouds < 5) { text("Wear sun screen!", 200, 200); }
We often use that in our programs here for checking that a user's mouse position is inside a rectangle (to mimic a button), in which case we need multiple && operators:
rect(100, 50, 100, 100); mousePressed = function() { if (mouseX > 100 && mouseX < 200 && mouseY > 50 && mouseY < 150) { text("You pressed it!", 80, 75); } };
If we only care that at least one condition is true, then we can use the || operator ("or"):
var degreesOutside = 70; var numberOfClouds = 50; if (degreesOutside < 70 || numberOfClouds < 5) { text("Wear sun screen, even if its not hot out!", 200, 200); }
We can use both && and || in the same expression, if we have some very complex condition to check. Just use parentheses to group expressions, so that the program isn't confused about what order to evaluate them:
var myAge = 28; if ((myAge >= 0 && myAge < 3) || myAge > 90) { println('You\'re not quite in your peak.'); }
Now let's return to if statements. We often want to execute some block of code in the case that the if condition wasn't true - in that case, we add an else statement.
var age = 28; if (age > 16) { println('Yay, you can drive!'); } else { println('Sorry, but you have ' + (16 - age) + ' years til you can drive.'); }
Sometimes we want to check multiple conditions, and do different things based on each, in which case we can use else if:
var age = 20; if (age >= 35) { println('You can vote AND hold any place in government!'); } else if (age >= 25) { println('You can vote AND run for the Senate!'); } else if (age >= 18) { println('You can vote!'); } else { println('You have no voice in government!'); }
You can keep checking conditions as much as you want - just make sure that each of your conditions is actually reachable. Test your code by changing variables until you make it inside each of the blocks of code, so that you know it all works.
As you can hopefully now see, conditionals are an important part of programming and let us create much more powerful and flexible programs.
We often want to be able to "conditionally" do things in our programs - we want to be able to say "if this thing is true, then do X but if this other thing is true, then do Y." It's like when we wake up in the morning - "if its raining outside, then I wear an umbrella, but if its sunny, I wear sunglasses." We can do things conditionally in our programs using if statements andif/else statements combined with conditional expressions.
An if statement tells the program to execute a block of code, as long as a condition is true. In the code below, we output a message only if x is greater than 0:
var x = 5; if (x > 0) { text('x is a positive number!', 200, 200); }
Since x is 5, which is greater than 0, we would see the message on the canvas. If we changed x to -1, we wouldn't see the message show up at all, since x wouldn't be greater than 0.
The x > 0 is what we call a conditional expression - which means it's an expression that evaluates to either true or false. When a value is either true or false, we call it aboolean value (as opposed to a number or a string). For example, we could just display the conditional expression:
text(x > 0, 200, 200); // Displays "true"
We could also store it into a variable and then display it:
var isPositive = x > 0; text(isPositive, 200, 200);
We would then say that isPositive is storing a boolean value, because it's either trueor false, depending on what we set x to.
We have many ways of creating conditional expressions that will evaluate to true orfalse, because we have many comparison operators. Here are the most popular:
Assuming the following variable, here are the most common comparison operators and expressions that would be true with them:
var myAge = 28;
OperatorMeaningTrue expressions===Strict equalitymyAge === 28!==Strict inequalitymyAge !== 29
28 !== '28'>Greater thanmyAge > 25
'28' > 25>=Greater than or equalmyAge >= 28
'28' >= 25<Less thanmyAge < 30
'28' < 30<=Less than or equalmyAge <= 28
'28' <= 28It is a very common mistake to confuse the assignment operator (=) with the equality operator (===), because they both use equal signs, but they are quite different. The assignment operator will actually change the value of the variable, whereas the equality operator will just read the value of the variable and see if it's equal to something. For example:
var x = 2 + 2; // Sets it equal to 4 if (x === 4) { // Asks the question, "does this equal 4?" text("yep, 2 + 2 = 4!", 200, 200); }
We sometimes want to combine multiple comparisons together in a conditional expression, and that's why we have logical operators. These operators let us say things like "if both X and Y are true" or "if either X or Y are true" in our programs.
If we want to require that two conditions are both true, we can use the && operator ("and"):
var degreesOutside = 70; var numberOfClouds = 50; if (degreesOutside < 70 && numberOfClouds < 5) { text("Wear sun screen!", 200, 200); }
We often use that in our programs here for checking that a user's mouse position is inside a rectangle (to mimic a button), in which case we need multiple && operators:
rect(100, 50, 100, 100); mousePressed = function() { if (mouseX > 100 && mouseX < 200 && mouseY > 50 && mouseY < 150) { text("You pressed it!", 80, 75); } };
If we only care that at least one condition is true, then we can use the || operator ("or"):
var degreesOutside = 70; var numberOfClouds = 50; if (degreesOutside < 70 || numberOfClouds < 5) { text("Wear sun screen, even if its not hot out!", 200, 200); }
We can use both && and || in the same expression, if we have some very complex condition to check. Just use parentheses to group expressions, so that the program isn't confused about what order to evaluate them:
var myAge = 28; if ((myAge >= 0 && myAge < 3) || myAge > 90) { println('You\'re not quite in your peak.'); }
Now let's return to if statements. We often want to execute some block of code in the case that the if condition wasn't true - in that case, we add an else statement.
var age = 28; if (age > 16) { println('Yay, you can drive!'); } else { println('Sorry, but you have ' + (16 - age) + ' years til you can drive.'); }
Sometimes we want to check multiple conditions, and do different things based on each, in which case we can use else if:
var age = 20; if (age >= 35) { println('You can vote AND hold any place in government!'); } else if (age >= 25) { println('You can vote AND run for the Senate!'); } else if (age >= 18) { println('You can vote!'); } else { println('You have no voice in government!'); }
You can keep checking conditions as much as you want - just make sure that each of your conditions is actually reachable. Test your code by changing variables until you make it inside each of the blocks of code, so that you know it all works.
As you can hopefully now see, conditionals are an important part of programming and let us create much more powerful and flexible programs.
This is a review of what we covered in this tutorial on loops.
When we're writing programs, we often find that we want to repeat a bit of code over and over, or repeat it but change something about it each time. To save ourselves from writing all that code, we can use a loop. JavaScript has two kinds of loops, a while loop and a for loop.
A while loop is a way to repeat code until some condition is false. For example, this while loop will display the value of y at (30, y) as long as y is less than 400. The loop adds 20 to y each time it runs, so that y starts off at 40 but then increments to 60, 80, 100, 120, etc.
var y = 40; while (y < 400) { text(y, 30, y); y += 20; }
It's important that the condition inside the parenthesis becomes false at some point - otherwise we'll have what's known as an infinite loop! That's what would happen if we removed y += 20, because y would be 40 forever, and always be less than 400, and the program would never know when to stop.
var y = 40; while (y < 400) { text(y, 30, y); }
The for loop is similar to a while loop, but with a more specialized syntax. Programmers invented the for loop when they realized they were always doing the same three things- creating loop counter variables (like y above), incrementing them by some amount, and checking that they're less than a value. A for loop syntax has special places for each of those three things. Here's the same loop as above, as a for loop:
for (var y = 40; y < 400; y += 20) { text(y, 30, y); }
Loops can also be nested. It's actually very common to nest for loops, especially in 2-d drawings, because it makes it easy to draw grid-like shapes. When we nest a loop inside a loop, we're telling the program to "do this thing X many times, and for each time you do that, also do this other thing Y many times." Think about drawing a grid- we'd want to tell the program to "create a column 10 times, and for each column, also create 15 cells inside of it." Here's how you can use nested for loops to achieve that:
for (var col = 0; col < 10; col++) { for (var row = 0; row < 15; row++) { rect(col*20, row*20, 20, 20); } }
When should you use a for loop versus a while loop? That's up to you. Many programmers prefer for loops because it's harder to accidentally create an infinite loop (because it's harder to forget to increment your counter variable), but sometimes a while loop might make more sense. Try them both!
When we're writing programs, we often find that we want to repeat a bit of code over and over, or repeat it but change something about it each time. To save ourselves from writing all that code, we can use a loop. JavaScript has two kinds of loops, a while loop and a for loop.
A while loop is a way to repeat code until some condition is false. For example, this while loop will display the value of y at (30, y) as long as y is less than 400. The loop adds 20 to y each time it runs, so that y starts off at 40 but then increments to 60, 80, 100, 120, etc.
var y = 40; while (y < 400) { text(y, 30, y); y += 20; }
It's important that the condition inside the parenthesis becomes false at some point - otherwise we'll have what's known as an infinite loop! That's what would happen if we removed y += 20, because y would be 40 forever, and always be less than 400, and the program would never know when to stop.
var y = 40; while (y < 400) { text(y, 30, y); }
The for loop is similar to a while loop, but with a more specialized syntax. Programmers invented the for loop when they realized they were always doing the same three things- creating loop counter variables (like y above), incrementing them by some amount, and checking that they're less than a value. A for loop syntax has special places for each of those three things. Here's the same loop as above, as a for loop:
for (var y = 40; y < 400; y += 20) { text(y, 30, y); }
Loops can also be nested. It's actually very common to nest for loops, especially in 2-d drawings, because it makes it easy to draw grid-like shapes. When we nest a loop inside a loop, we're telling the program to "do this thing X many times, and for each time you do that, also do this other thing Y many times." Think about drawing a grid- we'd want to tell the program to "create a column 10 times, and for each column, also create 15 cells inside of it." Here's how you can use nested for loops to achieve that:
for (var col = 0; col < 10; col++) { for (var row = 0; row < 15; row++) { rect(col*20, row*20, 20, 20); } }
When should you use a for loop versus a while loop? That's up to you. Many programmers prefer for loops because it's harder to accidentally create an infinite loop (because it's harder to forget to increment your counter variable), but sometimes a while loop might make more sense. Try them both!
This is a review of what we covered in this tutorial on arrays.
We often want to store lists of values when we're creating programs, and in JavaScript, we can do that using a type of value called an array.
To create an array, we declare a variable like we always do, but then we surround our list of values with square brackets and separate each value with a comma:
var xPositions = [33, 72, 64];
We can store any sort of JavaScript value in an array - not just numbers. Here's an example where we store a list of strings:
var myFriends = ['Winston', 'OhNoesGuy', 'John', 'Sophia'];
We often want to display the length of an array, or do something based on the length of the array. Thankfully, every array has a length property that will tell us the current length of the array:
text(myFriends.length, 200, 200); // Displays "4"
When we want to access a particular value in an array, we access it by referencing its "index" in the array, which represents its position. The first index in an array is "0", so if we want to access the first element in an array, we specify the name of the array variable, then square brackets, and 0:
text(myFriends[0], 200, 0); // Displays "Winston"
The second element is at index "1", the third is at index "2", and the fourth is at index "3":<
text(myFriends[1], 200, 100); // Displays "OhNoesGuy" text(myFriends[2], 200, 200); // Displays "John" text(myFriends[3], 200, 300); // Displays "Sophia"
The zero-based indexing is one of the most confusing aspects of arrays for new programmers, so keep that in mind if you're just getting started with arrays. You'll get used to it eventually!
We often want to take some action for every element in an array, like how we used the text() command to display the names above. Instead of writing that code over and over, it's better to use a for loop to iterate through each of the elements in the array, and do something to each element inside the loop. We have to start from index 0, go until we reach the end of the array, and add 1 to the index each time. Here's how we'd do that:
for (var i = 0; i < myFriends.length; i++) { text(myFriends[i], 200, i*100); }
Notice how we put i inside the square brackets, because it represents the current index each time the loop is run.
Arrays can be changed in many ways. To start off with, we can change a value in them:
myFriends[1] = "TheErrorBuddy";
We can also add entirely new values to them, using the push() method, passing in the new value:
myFriends.push("Hopper");
After running that line of code, our array length property will change to reflect the new length, and the final index in the array will be 4 instead of 3.
If you want a full list of what you can do with arrays in JavaScript, check out this reference. But don't worry, everything in this review will get you very far!
We often want to store lists of values when we're creating programs, and in JavaScript, we can do that using a type of value called an array.
To create an array, we declare a variable like we always do, but then we surround our list of values with square brackets and separate each value with a comma:
var xPositions = [33, 72, 64];
We can store any sort of JavaScript value in an array - not just numbers. Here's an example where we store a list of strings:
var myFriends = ['Winston', 'OhNoesGuy', 'John', 'Sophia'];
We often want to display the length of an array, or do something based on the length of the array. Thankfully, every array has a length property that will tell us the current length of the array:
text(myFriends.length, 200, 200); // Displays "4"
When we want to access a particular value in an array, we access it by referencing its "index" in the array, which represents its position. The first index in an array is "0", so if we want to access the first element in an array, we specify the name of the array variable, then square brackets, and 0:
text(myFriends[0], 200, 0); // Displays "Winston"
The second element is at index "1", the third is at index "2", and the fourth is at index "3":<
text(myFriends[1], 200, 100); // Displays "OhNoesGuy" text(myFriends[2], 200, 200); // Displays "John" text(myFriends[3], 200, 300); // Displays "Sophia"
The zero-based indexing is one of the most confusing aspects of arrays for new programmers, so keep that in mind if you're just getting started with arrays. You'll get used to it eventually!
We often want to take some action for every element in an array, like how we used the text() command to display the names above. Instead of writing that code over and over, it's better to use a for loop to iterate through each of the elements in the array, and do something to each element inside the loop. We have to start from index 0, go until we reach the end of the array, and add 1 to the index each time. Here's how we'd do that:
for (var i = 0; i < myFriends.length; i++) { text(myFriends[i], 200, i*100); }
Notice how we put i inside the square brackets, because it represents the current index each time the loop is run.
Arrays can be changed in many ways. To start off with, we can change a value in them:
myFriends[1] = "TheErrorBuddy";
We can also add entirely new values to them, using the push() method, passing in the new value:
myFriends.push("Hopper");
After running that line of code, our array length property will change to reflect the new length, and the final index in the array will be 4 instead of 3.
If you want a full list of what you can do with arrays in JavaScript, check out this reference. But don't worry, everything in this review will get you very far!
This is a review of what we covered in this tutorial on objects.
We have many types of values that we can store in JavaScript variables, and sometimes we want to store a bunch of related values together: that's where objects come in!
An object is a data type that let us store a collection of properties in a single variable. To create an object, we declare a variable like we normally would, and then we use curly braces to surround key-value property pairs:
var objectName = { propertyName: propertyValue, propertyName: propertyValue, ... };
Here's an object that describes Winston - this object has two properties, hometown andhair, and each of the property values are strings:
var aboutWinston = { hometown: "Mountain View, CA", hair: "no" };
Here's a more complex object that describes a cat, with four properties- age, furColor,likes, and birthday.
var lizzieTheCat = { age: 18, furColor: "grey", likes: ["catnip", "milk"], birthday: {"month": 7, "day": 17, year: 1994} };
Notice how each property stores a different data type- age stores a number, furColorstores a string, likes stores an array, and birthday stores another object. That's the cool thing about objects (well, one of the cool things) - they can store other objects inside them! So you can have deeply nested objects to describe complex data.
You might also see objects declared using quotes around the property names, like:
var aboutWinston = { "hometown": "Mountain View, CA", "hair": "no" };
That's equivalent to what we saw before with no quote marks, but it takes longer to type. The only time that you absolutely need quote marks is if your property name has a whitespace in it, like:
var aboutWinston = { "his hair": "none" };
We have to use quotes there, because otherwise the JavaScript interpreter would get confused. Here's my tip for you: just don't use whitespace in your property names to begin with! Then you never have to use quote marks around property names.
Accessing object propertiesAn object is not useful unless we can look inside it and grab the values of the different properties. We can do that two ways - first, using what we call "dot notation", where we write the name of the variable, followed by a ".", and then the property name:
var aboutWinston = { hometown: "Mountain View, CA", hair: "no" }; text("Winston is from " + aboutWinston.hometown, 100, 100); text("Winston has " + aboutWinston.hair + " hair", 100, 150);
We can also use "bracket notation", which looks similar to how we access array elements, where we write the variable name, then square brackets, with the property name inside in quotes:
var hisHometown = aboutWinston["hometown"]; var hisHair = aboutWinston["hair"];
If we try to access a property that doesn't exist, we'd see "undefined":
text("Winston's life goal is " + aboutWinston.lifeGoal, 100, 150);
Modifying object propertiesJust like when we store other data types in variables, we can change the values of the object properties at any time during a program, using the dot or bracket notation:
aboutWinston.hair = "curly"; // Winston gets a wig!
We can also add entirely new properties!
aboutWinston.lifeGoal = "teach JavaScript";
If we're done with a property, we can delete it (but most of the time we'll probably just change it value):
delete aboutWinston.hair;
Arrays of objectsNow that you know both arrays and objects, you can combine them to make arrays of objects, which are actually really useful ways of storing data in programs. For example, an array of cats:
var myCats = [ {name: "Lizzie", age: 18}, {name: "Daemon", age: 1} ]; for (var i = 0; i < myCats.length; i++) { var myCat = myCats[i]; println(myCat.name + ' is ' + myCat.age + ' years old.'); }
Notice that we iterate through an array of objects the same way that we iterate through an array of numbers or strings, using a for loop. Inside each iteration, we access the current array element with bracket notation, and then access the properties of that array element (an object) with dot notation.
Here's another practical example that you might use in your programs, an array of coordinate positions:
var positions = [ {x: 200, y: 100}, {x: 200, y: 200}, {x: 200, y: 300} ]; for (var i = 0; i < positions.length; i++) { var position = positions[i]; ellipse(position.x, position.y, 100, 100); }
Pretty neat, aye? Objects can be confusing at first, but keep using them, and eventually you'll be addicted and turn everything into an object!
We have many types of values that we can store in JavaScript variables, and sometimes we want to store a bunch of related values together: that's where objects come in!
An object is a data type that let us store a collection of properties in a single variable. To create an object, we declare a variable like we normally would, and then we use curly braces to surround key-value property pairs:
var objectName = { propertyName: propertyValue, propertyName: propertyValue, ... };
Here's an object that describes Winston - this object has two properties, hometown andhair, and each of the property values are strings:
var aboutWinston = { hometown: "Mountain View, CA", hair: "no" };
Here's a more complex object that describes a cat, with four properties- age, furColor,likes, and birthday.
var lizzieTheCat = { age: 18, furColor: "grey", likes: ["catnip", "milk"], birthday: {"month": 7, "day": 17, year: 1994} };
Notice how each property stores a different data type- age stores a number, furColorstores a string, likes stores an array, and birthday stores another object. That's the cool thing about objects (well, one of the cool things) - they can store other objects inside them! So you can have deeply nested objects to describe complex data.
You might also see objects declared using quotes around the property names, like:
var aboutWinston = { "hometown": "Mountain View, CA", "hair": "no" };
That's equivalent to what we saw before with no quote marks, but it takes longer to type. The only time that you absolutely need quote marks is if your property name has a whitespace in it, like:
var aboutWinston = { "his hair": "none" };
We have to use quotes there, because otherwise the JavaScript interpreter would get confused. Here's my tip for you: just don't use whitespace in your property names to begin with! Then you never have to use quote marks around property names.
Accessing object propertiesAn object is not useful unless we can look inside it and grab the values of the different properties. We can do that two ways - first, using what we call "dot notation", where we write the name of the variable, followed by a ".", and then the property name:
var aboutWinston = { hometown: "Mountain View, CA", hair: "no" }; text("Winston is from " + aboutWinston.hometown, 100, 100); text("Winston has " + aboutWinston.hair + " hair", 100, 150);
We can also use "bracket notation", which looks similar to how we access array elements, where we write the variable name, then square brackets, with the property name inside in quotes:
var hisHometown = aboutWinston["hometown"]; var hisHair = aboutWinston["hair"];
If we try to access a property that doesn't exist, we'd see "undefined":
text("Winston's life goal is " + aboutWinston.lifeGoal, 100, 150);
Modifying object propertiesJust like when we store other data types in variables, we can change the values of the object properties at any time during a program, using the dot or bracket notation:
aboutWinston.hair = "curly"; // Winston gets a wig!
We can also add entirely new properties!
aboutWinston.lifeGoal = "teach JavaScript";
If we're done with a property, we can delete it (but most of the time we'll probably just change it value):
delete aboutWinston.hair;
Arrays of objectsNow that you know both arrays and objects, you can combine them to make arrays of objects, which are actually really useful ways of storing data in programs. For example, an array of cats:
var myCats = [ {name: "Lizzie", age: 18}, {name: "Daemon", age: 1} ]; for (var i = 0; i < myCats.length; i++) { var myCat = myCats[i]; println(myCat.name + ' is ' + myCat.age + ' years old.'); }
Notice that we iterate through an array of objects the same way that we iterate through an array of numbers or strings, using a for loop. Inside each iteration, we access the current array element with bracket notation, and then access the properties of that array element (an object) with dot notation.
Here's another practical example that you might use in your programs, an array of coordinate positions:
var positions = [ {x: 200, y: 100}, {x: 200, y: 200}, {x: 200, y: 300} ]; for (var i = 0; i < positions.length; i++) { var position = positions[i]; ellipse(position.x, position.y, 100, 100); }
Pretty neat, aye? Objects can be confusing at first, but keep using them, and eventually you'll be addicted and turn everything into an object!
This is a review of what we covered in this tutorial on object-oriented design.
When we create programs, we often find that we want to create many different objects that all share similar properties - like many cats, that have slightly different fur color and size, or many buttons, with different labels and positions. We want to be able to say "this is generally what a cat is like" and then say "let's make this specific cat, and this other cat, and they'll be similar in some ways and different in a few ways as well." In that case, we want to use object-oriented design to define object types and create new instances of those objects.
To define an object type in JavaScript, we first have to define a "constructor function". This is the function that we'll use whenever we want to create a new instance of that object type. Here's a constructor function for a Book object type:
var Book = function(title, author, numPages) { this.title = title; this.author = author; this.numPages = numPages; this.currentPage = 0; };
The function takes in arguments for the aspects that will be different about each book - the title, author, and number of pages. It then sets the initial properties of the object based on those arguments, using the this keyword. When we use this in an object, we are referring to the current instance of an object, referring to itself. We need to store the properties on this to make sure we can remember them later.
To create an instance of a Book object, we declare a new variable to store it, then use thenew keyword, followed by the constructor function name, and pass in the arguments that the constructor expects:
var book = new Book("Robot Dreams", "Isaac Asimov", 320);
We can then access any properties that we stored in the object using dot notation:
println("I loved reading " + book.title); // I loved reading Robot Dreams println(book.author + " is my fav author"); // "Isaac Asimov" is my fav author
Let's contrast this for a minute, and show what would have happened if we didn't set up our constructor function properly:
var Book = function(title, author, numPages) { }; var book = new Book("Little Brother", "Cory Doctorow", 380); println("I loved reading " + book.title); // I loved reading undefined println(book.author + " is my fav author"); // undefined is my favorite author
If we pass the arguments into the constructor function but do not explicitly store them onthis, then we will *not* be able to access them later! The object will have long forgotten about them.
When we define object types, we often want to associate both properties *and behavior* with them - like all of our cat objects should be able to meow() and eat(). So we need to be able to attach functions to our object type definitions, and we can do that by defining them on what's called the object prototype:
Book.prototype.readItAll = function() { this.currentPage = this.numPages; println("You read " + this.numPages + " pages!"); };
It's like how we would define a function normally, except that we hang it off the Book's prototype instead of just defining it globally. That's how JavaScript knows that this is a function that can be called on any Book object, and that this function should have access to the this of the book that it's called on.
We can then call the function (which we call a method, since it's attached to an object), like so:
var book = new Book("Animal Farm", "George Orwell", 112); book.readItAll(); // You read 112 pages!
Remember, the whole point of object-oriented design is that it makes it easy for us to make multiple related objects (object instances). Let's see that in code:
var pirate = new Book("Pirate Cinema", "Cory Doctorow", 384); var giver = new Book("The Giver", "Lois Lowry", 179); var tuck = new Book("Tuck Everlasting", "Natalie Babbit", 144); pirate.readItAll(); // You read 384 pages! giver.readItAll(); // You read 179 pages! tuck.readItAll(); // You read 144 pages!
That code gives us three books that are similar - they all have the same types of properties and behavior, but also different. Sweet!
Now, if you think about the world, cats and dogs are different types of objects, so you'd probably create different object types for them if you were programming a Cat and a Dog. A cat would meow(), a dog would bark(). But they're also similar- both a cat and dog would eat(), they both have an age, and a birth, and a death. They're both mammals, and that means they share a lot in common, even if they're also different.
In that case, we want to use the idea of object inheritance. An object type could inherit properties and behavior from a parent object type, but then also have its own unique things about it. All the Cats and Dogs could inherit from Mammal, so that they wouldn't have to invent eat()ing from scratch. How would we do that in JavaScript?
Let's go back to our book example, and say that Book is the "parent" object type, and we want to make two object types that inherit from it - Paperback and EBook.
A paperback is like a book, but it has one main thing different, at least for our program: it has a cover image. So, our constructor needs to take four arguments, to take in that extra info:
var PaperBack = function(title, author, numPages, cover) { // ... }
Now, we don't want have to do all the work that we already did in the Book constructor to remember those first three arguments - we want to take advantage of the fact that the code for that would be the same. So we can actually call the Book constructor from thePaperBack constructor, and pass in those arguments:
var PaperBack = function(title, author, numPages, cover) { Book.call(this, title, author, numPages); // ... };
We still need to store the cover property in the object though, so we need one more line to take care of that:
var PaperBack = function(title, author, numPages, cover) { Book.call(this, title, author, numPages); this.cover = cover; };
Now, we have a constructor for our PaperBack, which helps it share the same properties as Books, but we also want our PaperBack to inherit its methods. Here's how we do that, by telling the program that the PaperBack prototype should be based on the Bookprototype:
PaperBack.prototype = Object.create(Book.prototype);
We might also want to attach paperback-specific behavior, like being able to burn it, and we can do that by defining functions on the prototype, after that line above:
PaperBack.prototype.burn = function() { println("Omg, you burnt all " + this.numPages + " pages"); this.numPages = 0; };
And now we can create a new paperback, read it all, and burn it!
var calvin = new PaperBack("The Essential Calvin & Hobbes", "Bill Watterson", 256, "http://ecx.images-amazon.com/images/I/61M41hxr0zL.jpg"); calvin.readItAll(); // You read 256 pages! calvin.burn(); // Omg, you burnt all 256 pages!
(Well, we're not really going to burn it, because that's an amazing book, but perhaps if we were stuck in a glacial desert and desperate for warmth and about to die.)
And now you can see how we can use object-oriented design principles in JavaScript to create more complex data for your programs and model your program worlds better.
When we create programs, we often find that we want to create many different objects that all share similar properties - like many cats, that have slightly different fur color and size, or many buttons, with different labels and positions. We want to be able to say "this is generally what a cat is like" and then say "let's make this specific cat, and this other cat, and they'll be similar in some ways and different in a few ways as well." In that case, we want to use object-oriented design to define object types and create new instances of those objects.
To define an object type in JavaScript, we first have to define a "constructor function". This is the function that we'll use whenever we want to create a new instance of that object type. Here's a constructor function for a Book object type:
var Book = function(title, author, numPages) { this.title = title; this.author = author; this.numPages = numPages; this.currentPage = 0; };
The function takes in arguments for the aspects that will be different about each book - the title, author, and number of pages. It then sets the initial properties of the object based on those arguments, using the this keyword. When we use this in an object, we are referring to the current instance of an object, referring to itself. We need to store the properties on this to make sure we can remember them later.
To create an instance of a Book object, we declare a new variable to store it, then use thenew keyword, followed by the constructor function name, and pass in the arguments that the constructor expects:
var book = new Book("Robot Dreams", "Isaac Asimov", 320);
We can then access any properties that we stored in the object using dot notation:
println("I loved reading " + book.title); // I loved reading Robot Dreams println(book.author + " is my fav author"); // "Isaac Asimov" is my fav author
Let's contrast this for a minute, and show what would have happened if we didn't set up our constructor function properly:
var Book = function(title, author, numPages) { }; var book = new Book("Little Brother", "Cory Doctorow", 380); println("I loved reading " + book.title); // I loved reading undefined println(book.author + " is my fav author"); // undefined is my favorite author
If we pass the arguments into the constructor function but do not explicitly store them onthis, then we will *not* be able to access them later! The object will have long forgotten about them.
When we define object types, we often want to associate both properties *and behavior* with them - like all of our cat objects should be able to meow() and eat(). So we need to be able to attach functions to our object type definitions, and we can do that by defining them on what's called the object prototype:
Book.prototype.readItAll = function() { this.currentPage = this.numPages; println("You read " + this.numPages + " pages!"); };
It's like how we would define a function normally, except that we hang it off the Book's prototype instead of just defining it globally. That's how JavaScript knows that this is a function that can be called on any Book object, and that this function should have access to the this of the book that it's called on.
We can then call the function (which we call a method, since it's attached to an object), like so:
var book = new Book("Animal Farm", "George Orwell", 112); book.readItAll(); // You read 112 pages!
Remember, the whole point of object-oriented design is that it makes it easy for us to make multiple related objects (object instances). Let's see that in code:
var pirate = new Book("Pirate Cinema", "Cory Doctorow", 384); var giver = new Book("The Giver", "Lois Lowry", 179); var tuck = new Book("Tuck Everlasting", "Natalie Babbit", 144); pirate.readItAll(); // You read 384 pages! giver.readItAll(); // You read 179 pages! tuck.readItAll(); // You read 144 pages!
That code gives us three books that are similar - they all have the same types of properties and behavior, but also different. Sweet!
Now, if you think about the world, cats and dogs are different types of objects, so you'd probably create different object types for them if you were programming a Cat and a Dog. A cat would meow(), a dog would bark(). But they're also similar- both a cat and dog would eat(), they both have an age, and a birth, and a death. They're both mammals, and that means they share a lot in common, even if they're also different.
In that case, we want to use the idea of object inheritance. An object type could inherit properties and behavior from a parent object type, but then also have its own unique things about it. All the Cats and Dogs could inherit from Mammal, so that they wouldn't have to invent eat()ing from scratch. How would we do that in JavaScript?
Let's go back to our book example, and say that Book is the "parent" object type, and we want to make two object types that inherit from it - Paperback and EBook.
A paperback is like a book, but it has one main thing different, at least for our program: it has a cover image. So, our constructor needs to take four arguments, to take in that extra info:
var PaperBack = function(title, author, numPages, cover) { // ... }
Now, we don't want have to do all the work that we already did in the Book constructor to remember those first three arguments - we want to take advantage of the fact that the code for that would be the same. So we can actually call the Book constructor from thePaperBack constructor, and pass in those arguments:
var PaperBack = function(title, author, numPages, cover) { Book.call(this, title, author, numPages); // ... };
We still need to store the cover property in the object though, so we need one more line to take care of that:
var PaperBack = function(title, author, numPages, cover) { Book.call(this, title, author, numPages); this.cover = cover; };
Now, we have a constructor for our PaperBack, which helps it share the same properties as Books, but we also want our PaperBack to inherit its methods. Here's how we do that, by telling the program that the PaperBack prototype should be based on the Bookprototype:
PaperBack.prototype = Object.create(Book.prototype);
We might also want to attach paperback-specific behavior, like being able to burn it, and we can do that by defining functions on the prototype, after that line above:
PaperBack.prototype.burn = function() { println("Omg, you burnt all " + this.numPages + " pages"); this.numPages = 0; };
And now we can create a new paperback, read it all, and burn it!
var calvin = new PaperBack("The Essential Calvin & Hobbes", "Bill Watterson", 256, "http://ecx.images-amazon.com/images/I/61M41hxr0zL.jpg"); calvin.readItAll(); // You read 256 pages! calvin.burn(); // Omg, you burnt all 256 pages!
(Well, we're not really going to burn it, because that's an amazing book, but perhaps if we were stuck in a glacial desert and desperate for warmth and about to die.)
And now you can see how we can use object-oriented design principles in JavaScript to create more complex data for your programs and model your program worlds better.
Becoming a better programmer
Have you watched all of the talk-throughs and completed all of the challenges up until this point? Awesome!
Before talking about what you can learn next, let's review what you've learned so far: JavaScript and ProcessingJS.
Review: JavaScriptThere are many programming languages in the world, and JavaScript is one of the most popular ones. A programming language typically includes ways to store data in computer memory, ways to manipulate that data, ways to organize code and run code repeatedly. You learnt how to do all of that in JavaScript via:
Review: ProcessingJSTo give you a fun way to learn JavaScript here, we gave you a drawing & animation "library" called ProcessingJS. That library is a collection of functions that you learnt how to use, and those functions know how to draw pixels into a canvas on the page. Here are examples of what you learnt how to use from ProcessingJS:
Learning moreNow, there are a ton of ways that you can keep learning programming, both by going deeper into what you've learnt so far or learning something related.
Learn more on Khan AcademyWe have two advanced tracks here on Khan Academy, with articles and challenges:
Besides our advanced tutorials on Games & Visualization and Natural Simulations, you can also watch tutorials created by members of our community:
Work on a big projectSometimes, the best way to really learn how to program is to work on a project that you're really passionate about.
Once you feel comfortable with HTML and CSS, you then need to learn how to use the JavaScript "DOM API", a library that lets you manipulate a webpage using JavaScript:
Learn new languagesIf you feel very comfortable with JavaScript, maybe you'd like to learn an entirely new language. Here are a few languages you might want to learn:
Before talking about what you can learn next, let's review what you've learned so far: JavaScript and ProcessingJS.
Review: JavaScriptThere are many programming languages in the world, and JavaScript is one of the most popular ones. A programming language typically includes ways to store data in computer memory, ways to manipulate that data, ways to organize code and run code repeatedly. You learnt how to do all of that in JavaScript via:
- Variables: how to declare variables, assign, re-assign, and local vs. global scope.
- Data types: numbers, booleans, strings, arrays, and objects.
- Functions: how to group code into functions, pass arguments to them, and return values from them.
- Conditionals: how to use if/else statements and logical expressions.
- Loops: how to use while and for loops to repeat code.
Review: ProcessingJSTo give you a fun way to learn JavaScript here, we gave you a drawing & animation "library" called ProcessingJS. That library is a collection of functions that you learnt how to use, and those functions know how to draw pixels into a canvas on the page. Here are examples of what you learnt how to use from ProcessingJS:
- Shapes: like rect(), ellipse(), and line()
- Colors: like fill(), stroke(), and background()
- Text: like text() and textSize()
- Events: like draw() and mousePressed()
- Math: like random() and dist()
Learning moreNow, there are a ton of ways that you can keep learning programming, both by going deeper into what you've learnt so far or learning something related.
Learn more on Khan AcademyWe have two advanced tracks here on Khan Academy, with articles and challenges:
- Advanced JS: Games & Visualizations
- Advanced JS: Natural Simulations (Recommended for those who have some familiarity with basic trigonometry and physics, like in high school).
- TreeHouse: JavaScript Foundations
- Mozilla Developer Network: JavaScript Guide
- Codecademy: JavaScript
- W3Schools JS Tutorial
- Eloquent JavaScript
Besides our advanced tutorials on Games & Visualization and Natural Simulations, you can also watch tutorials created by members of our community:
Work on a big projectSometimes, the best way to really learn how to program is to work on a project that you're really passionate about.
- Brainstorm ideas for a game, simulation, or story, and pick one that you think would be hard but not *too* hard.
- Plan it out, using pseudo-code, sketching on paper, or writing it up in a document.
- Start programming it. When you're stuck, try to find programs that do similar things (either from our official talk-throughs or from the community) and ask questions on them.
- Share it with your friends and family when you're done. Reflect on how much you learnt.
Once you feel comfortable with HTML and CSS, you then need to learn how to use the JavaScript "DOM API", a library that lets you manipulate a webpage using JavaScript:
Learn new languagesIf you feel very comfortable with JavaScript, maybe you'd like to learn an entirely new language. Here are a few languages you might want to learn:
- Python: used for webservers and data processing. Learn it on Codecademy, Treehouse, or with this interactive online textbook.
- Java: used to make Android apps. Learn it on Treehouse.
- Objective C: used to make iPhone apps. Learn it on MakeGamesWIthUs or Treehouse.
- Ruby: used with the Rails framework to create webservers. Learn it on Codecademy or Treehouse.
- PHP: used for webservers. Learn it on Treehouse or Codecademy.
- Haskell: used for functional programming and popular with researchers. Learn it from Learn you aHaskell for Great Good.
We would now recommend you to see the docs and go to Khan academy's page to learn more and put in practice all of that knowledge! (As you now can in our webpage)