prompt and console.logtrue, false, "truthy", and "falsey"The source code of Lights Out and Tic Tac Toe works, but is "bad".
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.
var player = $('#player');
Now instead of having to write $('#player') everywhere, we can write player.
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.
A function is a machine. You can re-use it as many times as you want.
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().
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').
function move(id){
if($(id).hasClass('played')){
}else{
$(id).addClass('played');
setBackground(id);
changePlayer();
}
}
Now the whole onclick becomes simply onclick="move('#a')".
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.
Clone down this lesson plan, and open the folder in Atom (atom .). Look at script.js.
jquery branchAt 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.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.
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.
undefined and null?