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.

Why?

After years of not taking the time to do so, I am starting my coding journey. Just one problem - it appears a large number of the resources out there start with formulaic coding, but fail to explain those formulas in a way that makes sense.

I hate rote memorisation. Firstly, the phrase "If memory serves me correct" is a bit of a joke with me. Yes, I forget things I don't commit to memory with absolute diligence. Secondly, I just don't learn effectively by memorising things, but rather by figuring out how they work.

Pages

Subscribe to I Learn Code RSS