GithubHelp home page GithubHelp logo

head-first-javascript-programming's Introduction

head-first-javascript-programming's People

Contributors

bethrobson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

head-first-javascript-programming's Issues

Object Magnets - Page : 221 || Mistake

In the last statement it's written dog.bark which refers to the "bark" property of the object "dog". I think it's supposed to be the variable "bark" instead of "dog.bar". Isn't it?

JavaScript - Pass-by-value || Page 92

var age = 7;
function addOne (x) {
x = x +1;
}
addOne(age);
document.write(age);

I'm gonna break this down the way I have understood.

So, we have a function called addOne which adds 1 to the value it accepts, right?
And then we call the function with an argument of the value 7. So, now the function adds 1 to 7 and age is 8.
But why is it that when I print out the value of age, it prints out 7 ??

Why can't I set an attribute to an element through JS ?

function init() {
var drink = document.getElementById("coffee");
drink.innerHTML = "I love tea.";
drink.setAttribute("color", "red");
}

window.onload = init; 

I love coffee.

This is my code.
I have selected the element with the id "coffee" and assigned it to the variable "drink".
I changed its content with the "innerHTML" property.
And, now, I want to set a "color" attribute to the element .
What's wrong with my code ? Why is the color not changing ??

object name

Hi
In an array of Objects like the one for ( Head-First-JavaScript-Programming/chapter10/plane.html ) the plane problem, is the singular variable (i.e. PASSENGER) the default variable name for each object in the PASSENGERS array of objects? or does it get designated by default once we use it?
I ask because I see no variable passenger defined anywhere but it is used in the functions to check on the no fly list, has/has not paid etc. What is the convention here? I probably would have opted for this.passengers [x].paid for example instead of passenger.paid as used. Where or who defined singular passenger as the variable to use?
I apologize if what I am asking is too trivial but it has me confused.
thanks for all assistance.
Pirooz

A more interesting implementation of the sit method Question

When we call barnaby and spot is the instance object value already set to true automatically even though our prototype is set to false? As I was tracing through trying to understand why the instance object would not be set to false as it inherits from the prototype as it doesn't make sense to me. If it was set to false than the first call would console.log Barnaby is already sitting but if it was true than it would skip this and console.log as show in the example. Scratching my head on this one.

// adding new property for sitting
Dog.prototype.sitting = false;
// adding new method for sit
Dog.prototype.sit = function() { 
    if (this.sitting) {
        console.log(this.name + " is already sitting"); 
    } else {
        this.sitting = true;
        console.log(this.name + " is now sitting"); 
    }
};

barnaby.sit();
barnaby.sit();
spot.sit();
spot.sit();

Chapter 13 Robot game solution (p. 583 in pdf book)

Hello,

Why is a function needed under the unlock function? The following doesn't work... why doesn't it?

Game.prototype.unlock = function() {
if (this.level === 42) {
console.log(this.name + " is blasting you with laser beams.");
}
}

...

robby.unlock();
rosie.unlock();

Question re Battleship game in Ch. 8: why functions are not part of our objects?

I have a question about this Battleship code in Chapter 8. We have the model, view, controller objects; however, some functions, like helper function parseGuess() and handler functions, like handleKeyPress are not a part of the objects.

For example, why couldn't we make the parseGuess() function a method of controller object? And is init function always a stand-alone function because it needs to start everything?

Thank you so much!

battleship game in chapter 2 is flawed !!!

The code used in battleship game has a very serious bug using which a person can win the game even by getting his one HIT correct.
For example if the battleship is present at indices 2,3 & 4.And I come to know by guessing that there is a HIT at 3 then,I can enter "3" two more times and win without even caring about other HITS.

Chapter 8 - Battleship

Hi, I'm on chapter 8 where you build a battleship game. I have finished the Viewer and Model part without the Controller part. My problem:
I type in the console model.fire("somecell") to make 3 hits and drown a ship, but I keep getting that the ship is sunk on every hit. It never says "Hit!"

My code:
`var view = {
displayMessage: function(msg){
var messageArea = document.getElementById('messageArea');
messageArea.innerHTML = msg;
},
displayHit: function(location){
var cell = document.getElementById(location);
cell.setAttribute("class", "hit");
},
displayMiss: function(location) {
var cell = document.getElementById(location);
cell.setAttribute("class", "miss");
}
};

var model = {
boardSize : 7,
numShips: 3,
shipLength: 3,
shipsSunk: 0,

ships:[
{locations: ["10", "20", "30"], hits: ["", "", ""]},
{locations: ["32","33","34"], hits:["", "", ""]},
{locations: ["63","64","65"], hits:["", "", ""]}
],

fire: function(guess){
for(var i = 0; i < this.numShips; i++) {
var ship = this.ships[i];
var index = ship.locations.indexOf(guess);

  if (index >=0) {
    //trafiony
    ship.hits[index] = "hit";
    view.displayHit(guess);
    view.displayMessage("Hit!");

    if (this.isSunk(ship)){
      view.displayMessage("Sunk!");
      this.shipsSunk++;
    }
    return true;
  }
}
view.displayMiss(guess);
view.displayMessage("Miss!")
return false;

},
isSunk: function(ship) {
for (var i=0; i < this.shipLength; i++){
if (ship.hits[i] !== "hit") {
return false;
}
return true;
}
}
};
`

I compared the code and it's the same as in the book and don't understand why it won't work. Can you help me?
Btw. this book is awesome. I bought a polish version :)

typeof array ??

var x = ["abc", 123];
var y = typeof x;
console.log(y);

I was expecting the output "array" but it resulted as an object. How come array be an object ?

Does anybody understand the thingamajig code?

Hi all,

I just started with JavaScript by reading this book.

So far so good :) But I stuck on the thingamajig code.

I cannot exactly understand how the code is executed and why the console says 120, if we call the thingamajig function with 5.

Thanks a lot in advance

Cheers
Mee

How/where do we call the isSunk method in chapter 8 ?

`var model = {
boardSize: 7,
numShips: 3,
shipLength: 3,
shipsSunk: 0,

ships: [{
locations: ["06", "16", "26"],
hits: ["", "", ""]
},
{
locations: ["24", "34", "44"],
hits: ["", "", ""]
},
{
locations: ["10", "11", "12"],
hits: ["", "", ""]
}

],
fire: function(guess) {
for (var i = 0; i < this.numShips; i++) {
var ship = this.ships[i];
var index = ship.locations.indexOf(guess);
if (index >= 0) {
ship.hits[index] = "hit";
if (this.isSunk(ship)) {
this.shipsSunk++;
}

return true;
}
}
return false;
},
isSunk: function(ship) {
for (var i = 0; i < this.shipLength; i++) {
if (ship.hits[i] !== "hit") {
return false;
}
}
return true;
}

};
`
Edit: The first if-statement above calls the method isSunk and then the body of the isSunk method will be executed. And if it's true, the code jumps back to if (this.isSunk(ship)) and executes the body.

Chapter 4. Bubbles 2.

Hello everyone!
I've got a question about the final version of the code in Chapter 4 (root: Chapter 4 -> bubbles2.html). The function getMostCostEffectiveSolution(scores, costs, highScore) is meant to choose the lower price for the highest scores that repeat twice. The best costs turned out to be .22 and .25. As a result of invoking the built-in return function, we get .22, but how does the function understand that we need a lower price, though we didn't mention any condition for that?

function getMostCostEffectiveSolution(scores, costs, highScore) {
var cost = 100; // much higher than any of the costs
var index;

for (var i = 0; i < scores.length; i++) {
	if (scores[i] == highScore) {
		if (cost > costs[i]) {
			index = i;
			cost = costs[i];
		}
	}
}
return index;

}

different ways of Calling a function?

Hi,

Curious if there is a difference between the way we do callbacks shown below

// Here's the function extracted. We just called it eat. You could have made this a function declaration 
// after anonymous function
var eat = (function(food){
    if (food === "cookies") {
        alert("More please");
    } else if (food === "cake") {
    alert("Yum yum")
    }
});
// callback with argument
(eat)("cookies");
// or you can do a callback like this  
//(eat("cookies"));

What's the difference? advantage or disadvantage? or do they same thing just different syntax choice?

For the Blur/zeroBlur image exercise

For anyone interested: This code based on previous lessons from this excellent book will also work for this Event Handler exercise. It uses the setAttribute( x, y) method instead of the image.src object/property/value pathway.

<!doctype html>

<title> Image Guess </title> <style> body { margin: 20px; } img { margin: 20px; } </style> <script> window.onload = init;
function init() {
	var image = document.getElementById("zero");
	image.onclick = showAnswer;
};

function showAnswer() {
	var image = document.getElementById("zero").setAttribute("src", "zeroblur.jpg");
	
}
</script>

Appendix RegExp, Recursion and JS Algorithms Practice

Hi Beth,

I was curious if you had any recommendations for practicing and studying RegExp and Recursion in greater detail. Hoping you could point me in the right direction for a resource on a good book, a blog, or online tutorial that goes into greater detail to really hone my Javascript chops and have more practice with this.

Also I really loved the "ah ha moments" I had when walking through and applying some of the various algorithms throught the book. I'll be honest feel a bit lost I know there are 100's if not 1000's of algorithms but I don't know where I can find a complete resource on all or majority of common algorithms used for javascript. I keep telling myself wait till you run into a problem than search for a common algorithm that pertains to the problem i encounter in the future, but what if I could just refer to a list, that I could see possible algorithms that I could use in the future?

Thanks again and firm believer in practice practice practice :)

What is the license for the source in this repository?

I'm a teacher who assigned Head First JavaScript Programming to a student learning JavaScript. He completed the book, and ended up with a working version of the battleship game. Now I would like him to modify and extend this in a variety of ways. I would like him to make his version available to others under a free software license, so I was wondering what the current license is?

Exercise forwards and backwards.

Hi,

I am doing the final exercise for matching words forwards and backwards.

Curious about this line

var len = this.length-1;

When I try to do lexical scope as I walk through this exercise I am stumped as to how this variable gets the length. When I read this it seems that it is getting the length minus one character or this is getting the reversed order. Am I reading this correctly?

// Exercise forwards and backwards.
String.prototype.palindrome = function () {

    // first we get the length of the string
    var len = this.length-1;
    // then we iterate over each character in the string, and test to see if the character at i is the the same
    // as the character at len-i (ex: the character at the other end)
    for (var i = 0; i <= len; i++) {
        if (this.charAt(i) != this.charAt(len-i)) {
            // if they are not equal we return false because we don't have a palindrom
            return false;
        }
        if (i === (len-i)) {
            // if we get to where i is in the middle of the string, or we get to the end of the loop, we return 
            // true because we've got a palindrome
            return true;
        }
    }
    // if we get to where i is in the middle of the string, or we get to the end of the loop, we return 
            // true because we've got a palindrome
    return true;
}

Object Magnets Solution (pg. 221)

The speak variable is incorrect in the book. The correct solution is the following:

var speak = dog.name + " says " + bark + " when he wants to " + dog.activity;
console.log(speak);

Should print out in the console: Fido says WOOF WOOF when he wants to fetch balls

It can't be dog.bark because the bark variable isn't assigned to the dog object. We're finding out what the bark variable would be with this specific (dog) object.

Chapter 8 - Battleship game.

I am trying to hard code the ships and try to hit and sunk them, but the message that Ships were either, hit, or sunk, or were missed is not displaying on the webpage. Instead, it's displaying as Ships were sank all the time on top. I checked the console for Errors, and there were none. I don't know what's wrong in my code.

So far my code looks like this. And the console is not showing any errors.



var view = { 
displayMessage: function(msg){
	var messageArea = document.getElementById("messageArea");
	messageArea.innerHTML = msg;
},
displayHit: function(location){
	var cell = document.getElementById(location);
	cell.setAttribute("class","hit");
},
displayMiss: function(location){
	var cell = document.getElementById(location);
	cell.setAttribute("class","miss");
}

};


view.displayMiss("00");
view.displayHit("34");
view.displayHit("12");
view.displayMiss("25");

view.displayMessage("are you on?");

var model = {
	boardsize: 7,
	numships: 3,
	shipLength: 3,
	shipSunk: 0,
 ships: [{ locations: ["06", "16", "26"], hits: ["hit", "", ""] },
 { locations: ["24", "34", "44"], hits: ["", "", ""] },
 { locations: ["10", "11", "12"], hits: ["", "", ""] }],
fire: function(guess) {
	for(var i = 0; i < this.numships; i++){
		var ship = this.ships[i];
		var index = ship.locations.indexOf(guess);
		if(index >=0){
			ship.hits[index] = "hit";
			view.displayHit(guess);
			view.displayMessage("HIT!");
			if (this.isSunk(ship)){
				view.displayMessage("You sank my warship");
				this.shipSunk++;
			}
			return true;
		}
	}
	view.displayMiss(guess);
	view.displayMessage("You Missed.");
	return false;
	
	},
	isSunk: function(ship) {
		for (var i = 0; i < this.shipLength; i++){
			if (ship.hits[i] !== "hit"){
				return false;
			}
		}
		return true;

	}
};
/*
model.fire("53");
model.fire("06");
model.fire("16");
model.fire("26");
model.fire("34");
model.fire("24");
model.fire("44");
model.fire("12");
model.fire("11");
model.fire("10");
*/
function parseGuess(guess){
	var alphabet = ["A","B","C","D","E","F","G"];
	if(guess === null || guess.length !== 2){
		alert("Enter a valid number and letter");
		} else{
			var row = alphabet.indexOf(guess.charAt(0));
			var column = guess.charAt(1);
			
			if (isNaN(row) || isNaN(column)){
			alert("invalid number");
			}
			else if (row < 0 || row >= model.boardsize || column < 0 || column >= model.boardsize){
				alert("off the board");
		} else {
			return row + column;
		}

		}
		return null;
		}
	
var controller = {
	guesses: 0,
	processGuess: function(guess){
		var location = parseGuess(guess);
		if(location){
			this.guesses++;
			var hit = model.fire(location);
			if(hit && model.shipSunk === model.numships) {
				view.displayMessage("You sank the warship, in" + this.guesses + "guesses");
			}
		}
	}
}
controller.processGuess("A0");
controller.processGuess("A6");
controller.processGuess("B6");
controller.processGuess("C6");
controller.processGuess("C4");
controller.processGuess("D5");
controller.processGuess("E4");
controller.processGuess("B0");
controller.processGuess("B1");
controller.processGuess("B2");

function init(){
	var fireButton = document.getElementById("fireButton");
	fireButton.onclick = handleFireButton;
	guessInput.onkeypress = handleKeyPress;
}
	
	function handleKeyPress(e){
		var fireButton = document.getElementById("fireButton");
		if(e.keycode === 13){
			fireButton.click();
			return false;
		}
	}
	function handleFireButton(){
		var guessInput = document.getElementById("guessInput");
		var guess = guessInput.value;
		controller.processGuess(guess);
		guessInput.value = "";
	}
	window.onload = init;

Global Variable.

I see that we need to declare the variable "i" in the for loop using the keyword "var". example
for ( var i = 0 ; i <scores.length ; i++)

As I have learned in the previous lessons that if I don't declare a variable inside a function it becomes a global variable. What if I don't write var in front of i? Does that make it a global variable??

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.