Build a search using a For Loop
Lesson 3 part 2 of the Codecademy Javascript course runs you through creating a small piece of code that searches a string for your name. I'm going to post the final piece here and try to explain my way through it.
Lesson 3 part 2 of the Codecademy Javascript course runs you through creating a small piece of code that searches a string for your name. I'm going to post the final piece here and try to explain my way through it.
An array is like a variable, except it contains multiple values, not just one. Arrays are easy to spot, because they're stuffed between square brackets []. An array is defined just like a variable and can contain all the jiggly bits you want - numbers, strings, booleans and possibly long pieces of code that provide a value like functions or more. This is a simple example of an array:
var myArray = [1,true,"tree",4,5,"sticks"];
This is fairly simple, we're creating a loop, something that is done over and over. The for
bit tells us how long to do it for.
A for
loop looks like this:
for (something; something < else; something and math) {
stuff happens;
}
The space between the brackets is where the magic happens. Don't forget, those are semicolons separating the bits, commas won't work! Here's what they do:
Writing code in a textarea is a royal pain in the tabs. The simple solution in OSX is to use the following key combination.
CTRL-ALT-TAB
In part 2 of Lesson 2 you get to build a little rock, paper, scissors game. It introduces a new item - the random method on Math.
math.random()
I was curious, because they don't really explain it. Just looking at the command itself it looks like it has two parts math
and random
. I kind of assume that means it's a command of the type "math", and its specific function is creating a random number. Turns out I'm right: it's called a method and in this case it picks a number between 0 and 1.
Lesson 2 covers functions in Javascript. The basic idea of a function is to simplify input and reduce repetition. For example we can write:
var myAnswer = (prompt("Do you prefer Apples or Pears"));
if ( myAnswer === "Apples") {
console.log("I eat Apples");
}
else {
console.log("I eat Pears");
}
But if we use a function we can reduce the complexity by not having to repeat the command.
After the first Codecademy lesson you get to code a simple game using everything you learned in part A. Here's my version, for the record.
I'm already familiar with HTML and CSS so I'm diving into Javascript. I'm using the Codecademy Javascript course as a starter, since it's a prerequisite for the Iron Yard course I'll be taking later this year. It's also free, which is great.
Codecademy starts off with a mixed bag of simple snippets. I'll just document them here.