Intro to Javascript

Learning Objectives

Framing

The source code of Lights Out and Tic Tac Toe works, but is "bad".

Variables

A variable is a bucket. You can put data in it. Then you can re-use it as many times as you want.

"Data" just doesn't mean numbers -- it means literally anything in Javascript.

Reusability

var player = $('#player');

Now instead of having to write $('#player') everywhere, we can write player.

Ease of changing

var p1Color = 'skyblue';
var p2Color = 'pink';

Now anywhere we have 'skyblue' we can use p1Color, and same for 'pink'. If I want to change the color, I need only change those two lines.

Functions

A function is a machine. You can re-use it as many times as you want.

Reusability

function changePlayer(){
  if(player.text() == p1Color){
    player.text(p2Color)
  }else{
    player.text(p1Color)
  }
}

Now this:

if($('#player').text() == 'skyblue'){$('#player').text('pink')}else{$('#player').text('skyblue')}

...can be replaced with changePlayer().

Arguments

You can pass data into function. This is called an "argument" or a "parameter".

function setBackground(id){
  $(id).css('background-color', player.text());
}

Now we can replace $('#a').css('background-color', $('#player').text()); with setBackground('#a').

Functions calling functions

function move(id){
  if($(id).hasClass('played')){
    
  }else{
    $(id).addClass('played');
    setBackground(id);
    changePlayer();
  }
}

Now the whole onclick becomes simply onclick="move('#a')".

Salvage Lights Out

Writing Javascript

Console

Open the Chrome console (Command + Option + J). This is a REPL (Read-Eval-Print Loop), like repl.it. You will never use repl.it again. Use this instead.

You should always have this open whenever you are doing work that involves front-end Javascript. It will show you any errors.

Script files

Clone down this lesson plan, and open the folder in Atom (atom .). Look at script.js.

Practicing Javascript

JS Concepts

Getting user input

At any point in our JS code, if we write prompt() a pop up box will open in our browser for a user to enter in text.

// Prompts user and stores value in the variable
var age = prompt("What's your age?");

Console logging

console.log simply prints out some text into your Chrome console. This is the easiest way to debug your apps.

// Logs value stored
console.log('I wish I looked that good when I was ' + age);

console.log should not be confused with alert which makes a box pop up.

Javascript in your HTML vs. in a separate file

Both work. Having your JS in a separate file is considered better practice for the same reason having CSS in a separate file is considered better practice: it's much neater, and separates your concerns.

Practicing Javascript

Review Questions

Advanced