0% found this document useful (0 votes)
61 views27 pages

Robotics Review Notes

This document provides an overview of arrays in JavaScript. It explains that arrays allow storing lists of values using square brackets and separating items with commas. The length property returns the array size, and values are accessed using their index number starting from 0. Loops like for can iterate through arrays. Arrays can be modified by changing values, adding new items with push, or other methods. Debugging techniques include printing values, explaining code verbally, and exaggerating output for visibility.

Uploaded by

Achionta Nandy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views27 pages

Robotics Review Notes

This document provides an overview of arrays in JavaScript. It explains that arrays allow storing lists of values using square brackets and separating items with commas. The length property returns the array size, and values are accessed using their index number starting from 0. Loops like for can iterate through arrays. Arrays can be modified by changing values, adding new items with push, or other methods. Debugging techniques include printing values, explaining code verbally, and exaggerating output for visibility.

Uploaded by

Achionta Nandy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

ROBOTICS REVIEW NOTES

ARRAYS CHAPTER !!!!!!!!!!!!!!!!!!!!!!!

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+1)*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+1)*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!

DEBUGGING !!!!!!!!!!!!!!!

There are many ways to debug your programs! Here's a list to get you started:

Print debugging

As we just showed, you can insert print()s or println()s into your code to help you figure
out which code is being called and with what values. Both of these functions output values in a
console that pops up over the canvas. You can also use debug() to send the output to your
browser's JavaScript console, if you know how to use that.

Screenshot of using the print console in a program


Rubber-duck debugging

Sit a rubber duck next to your computer—or whatever duck-like object you have handy—and
explain your program and problem to it, line by line. Many programmers find that just the
process of putting the problem in words helps their brains realize what's wrong. You can also
ask a friend or teacher to be your rubber duck, sitting and listening to you explain it. Sometimes
they might even think of a solution for you, but regardless, they're doing you a service by just
listening to the explanation.

Here's the closest thing we have to a rubber duck in the Khan Academy office:

Photo of stuffed Oh Noes guy next to a laptop


Exaggerate your output

Since you're making programs in ProcessingJS, you're dealing with lots of fill colors and strokes.
When I'm not seeing the visual output I expect, sometimes it helps to use really big or extreme
values for the fill and strokes—like strokeWeight(30). Since our environment is realtime
and includes the number scrubbers, it's really easy to change up the numbers in your program
to see what effect the change has on the output. For example, it might help you figure out where
a missing shape went.

Screenshot of program with exaggerated strokeWeight()

It's a good idea to get comfortable with all your options for debugging programs so that you can
use whichever one works the best in a particular situation.

LOOPS!!!!!!

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 the first while loop 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!
LOGIC AND IF STATEMENTS

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 it's raining outside, then I take an umbrella, but if it's sunny, I wear
sunglasses." We can do things conditionally in our programs using if statements and if/else
statements combined with conditional expressions.

An if statement tells the program to execute a block of code, if 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 a boolean
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 true or
false, depending on what we set x to.

We have many ways of creating conditional expressions that will evaluate to true or false,
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;

Operator Meaning True expressions

=== Strict equality myAge === 28

!== Strict inequality myAge !== 29 28 !== 29

> Greater than myAge > 25 28 > 25

>= Greater than or equal myAge >= 28 28 >= 28

< Less than myAge < 30 28 < 30

<= Less than or equal myAge <= 28 28 <= 28


It 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 if it's hot outside or there aren't many


clouds!", 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 until 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 >= 30) {

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.
RANDOM NUMBERS

We've been using our if conditions to check values about the


environment, like the user's current mouse position, and respond
predictably.

But what if we want unpredictability? What if we want our program to act differently each time it
runs?

Randomness to the rescue!

We can generate random numbers and use if and else if conditions to change our
program's behavior based on the random values.

For example:

var randNum = random(0, 10);


if (randNum < 5) {
text("Trick!", 200, 200);
} else {
text("Treat!", 200, 200);
}

The program outputs "Trick!" half of the time, and "Treat!" the other half.
How it works:

● The randNum variable is assigned a random number, starting at 0 and including


numbers up to 10. Returned values could include 0, 0.2, 3.3, 4, 5.5, 6.9, 8, 9, or 9.99,
but not 10 itself.
● The condition checks if the returned number is less than 5, outputting "Trick!" if so and
"Treat!' otherwise.

Sometimes it's easier to deal with whole numbers instead of floating point numbers, so that we
can check exact values. Here are a few functions that turn floating point numbers into integers:

● round(): Rounds a number down to the nearest integer if the decimal portion is lower
than .5 and rounds up if the decimal portion is .5 or greater.
● ceil(): Always rounds a number up to the next integer.
● floor(): Always rounds a number down to an integer.

Typically we want to generate random numbers that are picked relatively evenly. For example, if
we are simulating flipping a coin, then we expect there to be an equal chance of either "Heads"
or "Tails".

This code accomplishes that goal:

var randFlip = floor(random(0, 2));


if (randFlip === 0) {
text("Heads", 200, 200);
} else {
text("Tails", 200, 200);
}

The variable randFlip will always be either 0 or 1, since it calls floor() on the return value
of random(0, 2).
To give you a feel for why that's the case, here's the result of calling floor() on various values
from random(0, 2):

random(0, 2) floor(result)

0.0 0

0.217… 0

0.542… 0

0.973… 0

1.0 1

1.332… 1

1.589… 1

1.999… 1

The return values from random() are random, so they won't necessarily look as equally
distributed as the values in that table. If you run the coin-flipping code just 10 times, you might
see a string of all "Heads" or all "Tails". However, if you run it thousands of times and keep
count, you'll see "Heads" and "Tails" each about 50% of the time.
As a general rule, when our goal is to obtain a fair and even distribution of integer values, it is
best to use floor() with random(). [Why not ceil()?]

The random() function is a great way to add a little variety to your programs. However, use it
carefully: figure out the range of numbers that you're generating, decide whether you need to
round the numbers, and check the values appropriately.

You'll have a chance to try that out yourself in the next project!

FUNCTIONS

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 on
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 parentheses:

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
drawings 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 ellipse function, 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 output 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 the var
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 declared globalResult
outside of the function, so we can access it wherever we want.

⚠️ You might be tempted to use global variables for everything, since you'll never get an error
that they're undefined. But actually, global variables are a common source of hard-to-find errors.
In larger programs or collaborative programs, it’s easy to lose track of where and how you (or
others!) used those global variables. When possible, use local variables.

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.

STRINGS OF TEXT

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.
We call these text values strings in JavaScript; think of them as a string of letters.

To create a string, we surround text in quotation marks:

"Hello World!"

Then we have to actually do something with that string, like pass it to the

text()

text()

t, e, x, t, left parenthesis, right parenthesis

command:

text("Hello World!", 100, 100);

We could also store it in a variable, and then pass that variable into
the

text()

text()

t, e, x, t, left parenthesis, right parenthesis


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 them.

var myGreeting = 'Hello World!"; // oh noes!

Just like we can manipulate number values, we can also manipulate


strings. We can, for example, add one string to another string:

var myGreeting = "Alo";


var myName = "Winston";
var sayHello = myGreeting + ", " + myName + "!"; // Alo,
Winston!

When we combine strings in JS, we call it concatenating strings. We


can also combine strings with number values:

var xPos = 10;


var yPos = 20;
var label = "The coordinates are " + xPos + ", " + yPos;
We also saw in this tutorial that we can use different commands to
change the text size and text color when we display strings using the

text()

text()

t,

e, x, t, left parenthesis, right parenthesis

command. You can read more about those commands in the text
section of our documentation (click the "documentation" tab to
access).

ENJOYYY

You might also like