Francois's blog

Array and For Loops

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"];

For Loops in Javascript

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:

Rock, Paper, Scissors...

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.

All about Functions

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.

Let's get started.

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.

Pages

Subscribe to RSS - Francois's blog