THESE FORUMS NOW CLOSED (read only)

Fun Stuff => CLIKC => Topic started by: Sorflakne on 15 Aug 2013, 13:20

Title: Need help (lots) with Javascript
Post by: Sorflakne on 15 Aug 2013, 13:20
So I'm trying to teach myself javascript.  And when I say "trying", I mean "I am getting my ass royally handed to me".

Very little of this language is sticking.  I've read and reread passages and examples and tried out my own code, but it just will not click.  I understand a few individual aspects of it such as variables and functions, but trying to put them all together and construct my own examples, even when heavily modifying an existing example to make it my own, in practice just leaves me even more confused.

For learning material, I'm using O'Reilly's HeadFirst javascript book and going through the W3Schools site (http://www.w3schools.com/).  The Headfirst book I bought because their book on HTML and CSS was concise and made those two make sense; granted I'm no expert in them from reading one beginner's book, but I feel confident I can easily continue my self education in them.  Javascript though...no such luck.

So yeah...anyone else here know the language and/or have good methods of understanding how to develop and structure your own scripts (please keep it 'total n00b' friendly :) )?
Title: Re: Need help (lots) with Javascript
Post by: K1dmor on 15 Aug 2013, 13:56
 I'd recommend you this page: Codecademy. It's simple, you start with the basics, and it's easy to understand (and free).

 Here's the link to the Javascript part:
 Java (http://www.codecademy.com/courses/getting-started-v2/0/1?curriculum_id=506324b3a7dffd00020bf661)

 If you register, you can check where you left the last time.
Title: Re: Need help (lots) with Javascript
Post by: Pilchard123 on 15 Aug 2013, 14:27
I have no idea about how to go about learning it, though I'll second the recommendation of Codeacademy. If you want any help in particualr, post it up here and I'll (as will the many other beep-boopers around, no doubt) be happy to take a look at anything you're struggling with. I like Javascript.

Once you get further into Javascript, have a look at jQuery - it's really useful. Also try using Firebug if you're using Firefox - the console in that is great for testing stuff.
Title: Re: Need help (lots) with Javascript
Post by: Sorflakne on 15 Aug 2013, 15:22
I've tried CodeAcademy, but after the first few lessons, I just get lost.  The hints and error messages don't exactly help explain what/s missing/wrong in lines of code.
Title: Re: Need help (lots) with Javascript
Post by: snalin on 15 Aug 2013, 16:37
For development, I'd use chrome, since the chrome console (ctrl+shift+i) has a huge amount of stuff that's useful.

Be aware that javascript is a... fickle bitch. Since it's made to not fail on small errors, since that'd bother end users, errors usually propagate all the way through your code. The error messages you get are also platform dependent - you get different error messages in chrome than firefox, and they can also be... not very helpful. Also there are weird parts (https://www.destroyallsoftware.com/talks/wat) to it.

I've got spare time on my hands, so if you have time tomorrow, I could try and guide you through the CodeAcademy tutorials - just come hang out in Mumble. Just be aware that I'm in Norway, so that's GMT+1, so it'll have to be early in the day for you. Give me a PM if you're interested.
Title: Re: Need help (lots) with Javascript
Post by: Sorflakne on 19 Aug 2013, 11:38
Missed the above post because I decided to reformat my computer (and ran into...issues, but they're all better now!), however, I do have a question on arrays...

So here's a basic array:

<script>
var i;
var cars = new Array();
cars[0] = "Saab";
cars[1] = "Volvo";
cars[2] = "BMW";

for (i=0;i<cars.length;i++)
{
document.write(cars[i*] + "<*br>");
}
</script>


(*s are in the block to prevent the line from messing up, disregard them)
What does the line "for (i=0;i<cars.length;i++)" mean?  I know why it's there, but I don't quite know how to interpret it.  Is this format universal for arrays, or does it vary depending on whether the array is 1D or 2D?  And why is i less than cars.length? 

Funny enough, the above paragraph was a lot longer, but I answered a lot of it myself as I was writing my questions out, lol.
Title: Re: Need help (lots) with Javascript
Post by: cesium133 on 19 Aug 2013, 11:44
That's the notation for a loop. It starts the variable i equal to zero, then runs the command inside the loop, adds 1 to i, then checks whether i is less than the length of the cars array. It repeats the command until i is equal to or greater than the length of the cars array.

The basic syntax is
for(initial condition; test; increment command)
{
  command(s) to be repeated
}
Title: Re: Need help (lots) with Javascript
Post by: pwhodges on 19 Aug 2013, 12:03
And the reason for using < "less than" is that for three elements we are using the indices 0, 1 and 2 - but not 3, so when i=3 (i<3 is no longer true) we need to end the loop.  cars.length is the number of elements in cars, unsurprisingly.

This format of loop was introduced in C in 1972.
Title: Re: Need help (lots) with Javascript
Post by: snalin on 19 Aug 2013, 12:32
So, what happens is:

You make a variable named "i", and assign 0 to it. i is now 0.

Every time, before you do what is in the loop*, the conditional (i < cars.length) is tested. If it evaluates to false (i is larger or equal to the length of cars), the loop is not run, and the code passes on. This means that if you hadn't added anything to cars, so cars is 0, the stuff in the loop never happens. Note that you don't have to compare to the length of cars, you could put 3 there, and it would do the same thing. If you wrote i < 2, it would only print out "Saab" and "Volvo".

Every time, after you do what is in the loop, the value of i is incremented by one**.

Something which will do the exact same as what you did above, but is more easily readable, is:

Code: [Select]
var i = 0;
var cars = new Array();
cars[0] = "Saab";
cars[1] = "Volvo";
cars[2] = "BMW";

while(i < cars.length) {
  document.write(cars[i] + "<*br>");
  i++;
}

With regards to your question about whether it is universal for arrays, yes. If you have a 2d array, that is simply an array that contains arrays in every cell; an array of arrays. You can go down that rabbit hole as far as you want; 3 dimensional or 4 dimensional arrays are totally possible. You can also (in JS) have arrays that contains arrays in some cells, numbers in others and strings in yet others, this is a horrible idea.

I cooked up an example. The only thing of note that might not be straightforward is the use of console.log instead of document.write. It logs to your console, which can be found in chrome with ctrl+shift+j, or in firefox with ctrl+shift+k. It allows you to check what's happening in your code without editing how your web page looks, so you'll need to do that later on, so it's smart to start out doing it now.
So, example of use of 2d array, with 2d lookup. Copy it to a text document, put <html> and <script> tags around it, and open it in your browser of choice. Then open the console and see what a horrible person Tina is. Play around with it!

Code: [Select]
var persons = new Array();

var tom = new Array();
tom[0] = "Tom";
tom[1] = "www.Tom.com";
tom[2] = "Lasanga";

var carl = new Array();
carl[0] = "Carl";
carl[1] = "www.Carl.com";
carl[2] = "Pizza";

var tina = new Array();
tina[0] = "Tina";
tina[1] = "www.Tina.com";
tina[2] = "The Blood of the innocent";

persons[0] = tom;
persons[1] = carl;
persons[2] = tina;

for(var i = 0; i < persons.length; i++) {
console.log("Person number " + (i+1) + ":");
console.log("Name: " + persons[i][0]);
console.log("Web Page: " + persons[i][1]);
console.log("Favourite Dish: " + persons[i][2]);
console.log("\n"); //New line
}

*document.write(cars) etc. You can put as many lines as you want in there. You can also assign new values to i, which will do funny things to your code.

** These are equivalent:
Code: [Select]
i++;
i += 1;
i = i+1;

EDIT: offer to guide you though some examples over voice chat still stands! Or text chat if you are shy. Or just post more questions here. But I'd love to talk you through some stuff! I'm going to be a teachers assistant at basic level Java this semester, and I've only done higher levels before, so some experience with someone who's entirely fresh would be cool.
Title: Re: Need help (lots) with Javascript
Post by: Sorflakne on 20 Aug 2013, 00:05
Ok, so it's safe to assume that i=0 by default all the time then?

@snalin:  Eh, probably stick to posts for now.  Your example array is interesting, I'll have to mess around with it more before I feel confident on it, but it definitely made array structure clearer for me.
Title: Re: Need help (lots) with Javascript
Post by: pwhodges on 20 Aug 2013, 00:19
Ok, so it's safe to assume that i=0 by default all the time then?

Not necessarily; there are many reasons why one might want to loop (for instance) from the last element to the first, or over only a subset of the elements.
Title: Re: Need help (lots) with Javascript
Post by: snalin on 20 Aug 2013, 00:56
Yes, if you want to loop from last to first, you do:

Code: [Select]
for(var i = cars.length-1; i >= 0; i--) {

}

There's a couple of points here that's important too:
- There is no reason other than convention to use the variable name i in the loop. You could do for(var allTheBears = 0; allTheBears < cars.length etc. etc.
- Note that when you loop backwards, you have to start at length-1, while the -1 doesn't show up if you go forwards. I've also used >= on the comparison. Try to figure out why, it'll help you understand what's going on. Remember that if there's 3 elements in the array, they are indexed from 0 to 2 (n elements means indexing from 0 to n-1)

On vars, javascript is a bit wonky. If you haven't defined i anywhere, and then do this:
Code: [Select]
console.log(i);
var i;
console.log(i);
i = 5;
console.log(i);

The two first console.log statements will print "undefined", as i is... not defined. On the other hand, you can write

Code: [Select]
i = 5;
console.log(i);

and get it to print 5 as expected - the "var" statement isn't needed per se (unlike other languages). It is a really good idea to use it, though - it limits the scope of the variable, which is a more advanced topic, but an important one - when you start writing methods, it will show up to bite you in the ass if you don't use it.
Title: Re: Need help (lots) with Javascript
Post by: Loki on 21 Aug 2013, 07:18
There is no reason other than convention to use the variable name i in the loop.

That convention being derived from i being the first letter of the word "iterate" (go through, step by step).

(I am mainly commenting so that this thread goes on my "unread replies to your posts" list).
Title: Re: Need help (lots) with Javascript
Post by: pwhodges on 21 Aug 2013, 07:44
I suspect that it goes right back to it being the first letter of the group that defined variables starting with those letters (I-N) as being INTEGER rather than REAL in the original Fortran - so i for "integer", before anyone used fancy words like "iteration"!
Title: Re: Need help (lots) with Javascript
Post by: cesium133 on 21 Aug 2013, 08:01
I know this isn't really related to the thread, but... Oh God, I hate programs that do that in Fortran. "I wonder what this variable is" *goes looking for declaration* "It's not declared!" Implicit None is your friend.  :psyduck:
Title: Re: Need help (lots) with Javascript
Post by: pwhodges on 21 Aug 2013, 08:27
IMPLICIT wasn't in the language when I was using it...  When there's no alternative, the defaults are easy enough to read so long as they are stuck to.
Title: Re: Need help (lots) with Javascript
Post by: cesium133 on 21 Aug 2013, 08:29
Yes, but there are still Fortran programs I've come across that don't use it.
Title: Re: Need help (lots) with Javascript
Post by: ev4n on 21 Aug 2013, 08:43
Code: [Select]
for(var i = cars.length-1; i >= 0; i--) {

}

I do'nt know enough about Java to say for sure, but your code made me wince.

(click to show/hide)

Title: Re: Need help (lots) with Javascript
Post by: Sorflakne on 21 Aug 2013, 12:42
Ok, that makes sense on i...pretty much no indication was given as to why i seems so important in the material I'm using (I've switched over to W3Schools completely, they've made the most sense so far). 

Now I'm running into another problem, and I cannot figure out why this is happening.  A little backstory: I'm creating what amounts to a "test" or "basic reference" page of some of the stuff I've learned so far (most everything else I've written in a notebook).  It's pretty much all simple stuff like "Push this button for a message popup" and different ways of making it do that, and a couple random stuffs tied to what time of day it is.  In other words, a beginners reference pool of examples with short explanations following each block of code.

The problem now, is that whenever I try adding a block of text to the page that describes something that, ironically, is about error messages, the page just displays "Error" whenever I load it up.  However, if I delete a particular line from this paragraph, the page loads as normal.  The paragraph where this is happening is enclosed by simple <p></p>, and has no scripts or other HTML in it and is otherwise not tied to any other block of code on the page at all (well, maybe not entirely, see below).  Even putting the line in its own paragraph does not solve the problem, and it's a line that I kind of need in the description for it to make sense; it's a sentence about not defining the script as "text/javascript" in the <script> tag, but even when I break it up and make it as uncode-like as possible, it still returns "Error".  It seems that if the word "script" appears in the sentence, the page fails (I had to spell it as s-cript for it to not break the page), and even having parenthesis in the paragraph block does it too.  I've no idea how or why this is causing problems.

Edit: It seems I can't add anything to the page now without causing the "Error" to display, regardless of where I add stuff on the page...

-

Another problem I've noticed is that after doing a document.write example of displaying the heading sizes from 1 to 6 in descending order, all the text below this is now in heading 6 format.  None of the subsequent stuff is tied to it, but I can't break it away from the heading 6 size.  Not sure how to begin fixing this one...
Title: Re: Need help (lots) with Javascript
Post by: pwhodges on 21 Aug 2013, 13:32
Have you closed your <h6> with a </h6>?

In programming, or HTML, or just about anything to do with computers, understanding the strictness of the requirement to bracket things and match bracketed structures in the right places is crucial.  When you are writing code to output HTML it gets more complex because the bracketed structures in the HTML are not nested in the same universe (as it were) as the bracketed structures in the code... The fact that in some circumstances you can get away without closing brackets just complicates things - think in terms of always closing structures properly even if you think you don't have to and (a) life will actually get simpler and (b) your HTML will have a better chance of validating in the end.
Title: Re: Need help (lots) with Javascript
Post by: Masterpiece on 21 Aug 2013, 13:35
In addition to what pwhodges said, do you use an assisted editor integrated development environment? Like, one that points out when you don't close brackets or finish statements and such?
Title: Re: Need help (lots) with Javascript
Post by: snalin on 21 Aug 2013, 13:57
The problem now, is that whenever I try adding a block of text to the page that describes something that, ironically, is about error messages, the page just displays "Error" whenever I load it up.  However, if I delete a particular line from this paragraph, the page loads as normal.  The paragraph where this is happening is enclosed by simple <p></p>, and has no scripts or other HTML in it and is otherwise not tied to any other block of code on the page at all (well, maybe not entirely, see below).  Even putting the line in its own paragraph does not solve the problem, and it's a line that I kind of need in the description for it to make sense; it's a sentence about not defining the script as "text/javascript" in the <script> tag, but even when I break it up and make it as uncode-like as possible, it still returns "Error".  It seems that if the word "script" appears in the sentence, the page fails (I had to spell it as s-cript for it to not break the page), and even having parenthesis in the paragraph block does it too.  I've no idea how or why this is causing problems.


A pretty important thing to remember is that your javascript (the stuff that (usually) goes between your <script> tags) and the html is really separate entities. If the particular line of code that seems to be breaking things is containing the string <script>, the web page will interpret the rest of the page, all the way until it reaches </script>, as javascript, not html. Since what you've got right after <script> starts probably doesn't contain something that's formatted in legal javascript, you get javascript errors, as the interpretation fails. That could be it, I'd have to look at your code to be sure (if you put it in a google doc? Or just post a link to it somewhere?), but it's the only explanation I can come up with.



Code: [Select]
for(var i = cars.length-1; i >= 0; i--) {

}

I do'nt know enough about Java to say for sure, but your code made me wince.

(click to show/hide)

javascript is NOT java*. At all. It has no signage, whatsoever, just a var statement that does nothing but limiting the scope of the variable. You can do this:

Code: [Select]
var s = "string";
console.log(s); //prints string
s = 1;
console.log(s); //prints 1

See? A variable isn't tied to any kind of type whatsoever. You will get problems when trying to do stuff with different types, you can't go "hello" / 4. The classes and objects are also a lot less strict what you have in java/c++, you can just add properties and methods to an object at will. An object is kinda just a map from variable names to whatever. var object = {}; is an object instantiation. Blew my mind when I first ran into it. Javascript is weird around the edges, check out the later half of this video (http://this video) (check the first part out too, the ruby part is also funny)

The var statement is important, though. Amongst other things, it prevents this fun little thing:

Code: [Select]
var someArr = new Array(2);
someArr [0] = "hellu";
someArr [1] = "hella";

function swap(arr, ind1, ind2) {
  temp = arr[ind1];
  arr[ind1] = arr[ind2];
  arr[ind2] = temp;
};

swap(someArr, 0, 1);

console.log(temp); //WILL log "hellu". I am NOT kidding. If i had written "var temp" over, it would throw an undefined error, as you'd expect from any other language.

It is horrible at start, but you get used to it. If you tried to do something like that in java, you'd get compilation errors right away. Think of java as c++ without having to deal with pointer arithmetic or segfaults and the other things that makes c/c++ a complete fucking mess. Javascript is a lot more lenient than anything else - basically the idea is that it shouldn't fail on type errors, since it has to deal with user input to such a degree that it would crash all the times otherwise. I'm not sure if I agree with that philosophy, but you have to live with it.


* I don't quite remember why javascript is named javascript, but I've heard it said that around when javascript first popped up, java was kinda hip, so they just grabbed the name.
Title: Re: Need help (lots) with Javascript
Post by: pwhodges on 21 Aug 2013, 14:26
It was developed by NetScape under the name Mocha, and added to their Navigator browser as LiveScript.  The name change to JavaScript was at the same time as Java support was first added to Navigator, and may have been a misguided attempt to piggyback on the popularity of the hot new thing.  It is now also standardised under the name ECMAscript.
Title: Re: Need help (lots) with Javascript
Post by: Loki on 21 Aug 2013, 17:32
If the particular line of code that seems to be breaking things is containing the string <script>, the web page will interpret the rest of the page, all the way until it reaches </script>, as javascript, not html. Since what you've got right after <script> starts probably doesn't contain something that's formatted in legal javascript, you get javascript errors, as the interpretation fails. That could be it, I'd have to look at your code to be sure (if you put it in a google doc? Or just post a link to it somewhere?), but it's the only explanation I can come up with.

So basically you are suggesting he needs to put his code examples inside a <textarea></textarea> tag or that he has to html-encode his tags, writng &lt;script&gt; in his examples when he wants <script> to be displayed?
Title: Re: Need help (lots) with Javascript
Post by: snalin on 21 Aug 2013, 23:24
Something along those lines, will still have to see the code. I made an attempt; here's what I found. This crashes with "Uncaught SyntaxError: Unexpected token !":

Code: [Select]
<p> This is some text that talks about the <script> tag! </p>

<h1> This is not written to the page, it stops after "the" </h1>

<script>
</script>

As is expected, it find some garbled javascript, and fails. The second opening script tag is interpreted not as html, but javascript. If you use textarea, it works, I don't quite know why, but hey. If you do this:

Code: [Select]
<p> This is some text that talks about the <script> tag! </p>

<h1> This is not written to the page, it stops after "the" </h1>

You still stop at the, but no errors is thrown. Which is strange, but I suppose the browser is still expecting input of a final </script> token.
Title: Re: Need help (lots) with Javascript
Post by: Sorflakne on 23 Aug 2013, 01:36
Quote
Have you closed your <h6> with a </h6>?
No, it's not actually written out, but is a do...while loop.  Is written like this:
Code: [Select]
<script type="text/javascript">
i = 1
do {
document.write("<h" + i + ">This is heading " + i);
document.write("<h" + i + ">");
i++;
}
while (i <= 6)
</script>

I've tried inserting a break; statement, but that doesn't seem to do anything.  Can break; be used here and I'm just not placing it right, or do I need a different statement to keep the loop contained to the script?

Quote
In addition to what pwhodges said, do you use an assisted editor integrated development environment? Like, one that points out when you don't close brackets or finish statements and such?
I'm not...do you know of a good one?  I'm mainly using Notepad and the W3 example pages.

Quote
A pretty important thing to remember is that your javascript (the stuff that (usually) goes between your <script> tags) and the html is really separate entities. If the particular line of code that seems to be breaking things is containing the string <script>, the web page will interpret the rest of the page, all the way until it reaches </script>, as javascript, not html....
But there's no <script> tag in the paragraph, just the word "script", no markers or anything around it.

Oddly enough, it seemed to work fine when I copied the code from the W3 example page into a Notepad page, saved it there, and opened it that way...

Quote
* I don't quite remember why javascript is named javascript, but I've heard it said that around when javascript first popped up, java was kinda hip, so they just grabbed the name.
That's the story I heard too.  Along with something about having computer languages share similar names to organize them or something.  Yeah, didn't quite work out that way...
Title: Re: Need help (lots) with Javascript
Post by: pwhodges on 23 Aug 2013, 01:49
If that's a true copy of your code, you simply forgot to include the / in the closing tags.

document.write("<h" + i + ">This is heading " + i);
document.write("</h" + i + ">");
Title: Re: Need help (lots) with Javascript
Post by: snalin on 23 Aug 2013, 07:48
Quote
In addition to what pwhodges said, do you use an assisted editor integrated development environment? Like, one that points out when you don't close brackets or finish statements and such?
I'm not...do you know of a good one?  I'm mainly using Notepad and the W3 example pages.

I'd suggest at least upgrading to notepad++ if you're on windows. It's not an IDE per se, but it has a bit of syntax highlighting for javascript/html. You could also go for something bigger, that would shout at you if you do something wrong during writing, and gives you access to built-in functions in an easy way.
Title: Re: Need help (lots) with Javascript
Post by: Masterpiece on 23 Aug 2013, 11:02
I voulda sworn I had Dreamweaver here somewhere...
Title: Re: Need help (lots) with Javascript
Post by: Sorflakne on 23 Aug 2013, 11:56
It's always a missing /...   :psyduck:  It works now, though.

Quote
I'd suggest at least upgrading to notepad++ if you're on windows. It's not an IDE per se, but it has a bit of syntax highlighting for javascript/html.
I'll check it out.  I miss way too many closing / ' " ] etc...I'm surprised I haven't started pulling my hair out yet.

I'd love to get Dreamweaver, but I don't have the funds to spend on it yet.

Edit: Ok yeah, I'm already liking Notepad++.  I'm tempted to turn on autocomplete so that every [] {} <> etc is automatically closed when entered, but I know that that'd just make my habit of forgetting to close them worse.
Title: Re: Need help (lots) with Javascript
Post by: cesium133 on 23 Aug 2013, 12:30
I always turn that feature off because I end up not noticing that it closed the bracket, and I close it again.
Title: Re: Need help (lots) with Javascript
Post by: celticgeek on 23 Aug 2013, 12:39
Back when I was programming for Windows, I used Notepad++ and loved it. 
Title: Re: Need help (lots) with Javascript
Post by: Masterpiece on 23 Aug 2013, 12:45
I always turn that feature off because I end up not noticing that it closed the bracket, and I close it again.

I love that Eclipse anticipates and reacts to this by just doing it right and ignoring brackets when you add a bracket at a place where Eclipse auto-predicted that you'd place them.
Title: Re: Need help (lots) with Javascript
Post by: Loki on 23 Aug 2013, 20:23
Oh, in case you haven't already: get used to writing both the opening and the closing bracket right at the start. That way you are less likely to forget to close them. Also, you should get used to finishing every line with a semicolon. It looks neater. (There was a nother reason for why you'd do that, but I cannot think of it right now.)
Title: Re: Need help (lots) with Javascript
Post by: Stybar on 23 Aug 2013, 23:03
Because it used to be neccesary, I believe. That's how I was taught it, anyhow.

And if you find the right environment, you don't have to worry about brackets. The program I use, IntelliJ (http://www.jetbrains.com/idea/), may not be the best there is, but it automatically fills out brackets, fixes syntax errors, and even creates getters, setters, imports,...
Title: Re: Need help (lots) with Javascript
Post by: snalin on 24 Aug 2013, 01:06
On the semicolon thing - javascript works without the semicolons. There is one place where it is needed, and that is something like_

Code: [Select]
a = b + c
(d+e).print()

will be parsed as:

Code: [Select]
a = b + c(d+e).print()

So a new line starting with parentheses will be used as method arguments if possible.
Title: Re: Need help (lots) with Javascript
Post by: Loki on 24 Aug 2013, 02:10
Huh. The more you know.
Title: Re: Need help (lots) with Javascript
Post by: Masterpiece on 24 Aug 2013, 05:18
A semicolon is needed in Java (and probably a lot more programming languages, but I can't be certain) to signal the end of an expression statement. Since every other statement includes at least one expression, most "lines" are ended by a semicolon. If I remember correctly, groups of expressions (curly brackets) and conditions are an exemption to that rule.

Code: [Select]
private boolean isMasterpieceMakingSense{ // oh yeah, method declarations also don't end with semicolons, but they're also a group of statements anyway... 
     if(!isMasterpieceTalkingBonkers && isCodeExampleCorrect){ // start of a group of statements, no semicolon
          logging.put("Heck yeah, I made it!"); // semicolon after an expression!
          return true; // semicolon after an expression!
     }else{ // no semicolon after the first bracket, and none after the else statement
          logging.put("Awww, bonkers."); // another expression
          return false; // last expression
     }
} // end of method declaration, no semicolon.
Title: Re: Need help (lots) with Javascript
Post by: Stybar on 24 Aug 2013, 07:01
Why did you name a method isTalkingBonkers if your returning false when you ARE talking bonkers?
Title: Re: Need help (lots) with Javascript
Post by: Loki on 24 Aug 2013, 07:23
More importantly, why is isMasterpieceMakingSense not a function? :-D
Title: Re: Need help (lots) with Javascript
Post by: Masterpiece on 24 Aug 2013, 09:55
Why did you name a method isTalkingBonkers if your returning false when you ARE talking bonkers?

Oh. Damn. You're absolutely right. Semantics. Damn you.
I could make the code work but it would look ugly.

More importantly, why is isMasterpieceMakingSense not a function? :-D

Same as the above. OH WAIT THAT GAVE ME A GREAT IDEA!
Title: Re: Need help (lots) with Javascript
Post by: Stybar on 24 Aug 2013, 12:10
More importantly, why is isMasterpieceMakingSense not a function? :-D

Didn't even see that. Damn.
Title: Re: Need help (lots) with Javascript
Post by: Loki on 24 Aug 2013, 12:37
Technically speaking, it could still be a function, of course.
Title: Re: Need help (lots) with Javascript
Post by: Stybar on 24 Aug 2013, 13:13
In Java, yes. But in Javascript?
Title: Re: Need help (lots) with Javascript
Post by: Loki on 24 Aug 2013, 14:14
Everything is a variable in Javascript. Even functions.

Check this out:

Code: (Javascript) [Select]
function isThisAFunction(){}

document.write(typeof isThisAFunction+"<br>");

if (isThisAFunction) {
document.write("isThisAFunction evaluates to true when passed to an if, because the if checks for existence"+"<br>");
}
else
{
document.write("isThisAFunction evaluates to false"+"<br>");
}

if (isThisAFunction==true) {
document.write("isThisAFunction is the same as true"+"<br>");
}
else
{
document.write("isThisAFunction is, however, not the same as true, even by lax comparison"+"<br>");
}
isThisAFunction = 5;
document.write(typeof isThisAFunction+"<br>");

The result:
Quote
function
isThisAFunction evaluates to true when passed to an if, because if checks for existence
isThisAFunction is, however, not the same as true, even by lax comparison
number

Also,

function isThisAFunction(){}

is functionally (:-D) equivalent to

isThisAFunction=function(){} 

:roll:
Title: Re: Need help (lots) with Javascript
Post by: Sorflakne on 26 Aug 2013, 12:59
So wait, ; are NOT required in javascript?  But my scripts seem to break if I forget one...unless I'm imagining things.
Title: Re: Need help (lots) with Javascript
Post by: snalin on 26 Aug 2013, 14:31
If you're writing on a site, they might be using an extra static checker. If you are doing several things on one line (like inside a for loop), they are necessary, for the parser to tell one statement from the next. Otherwise, well, not really, but you should use them anyways. They add clarity to your code (yes I DID mean to end the statement there, I didn't just accidentally press enter at one point), and as most languages with syntax similar to JS has mandatory semicolons, most people who will read your code will be used to them.
Title: Re: Need help (lots) with Javascript
Post by: Stybar on 26 Aug 2013, 15:12
As Snalin said, semicolons may not be neccesary in a language, but it's considered good practice to do so. Same as naming your variables properly ("counter1" doesn't make much sense, "clickCounter" does), correct writing of variables (capital letters!), proper decleration of your variables,...
Learning to code is one thing, but to code well is something else.
Title: Re: Need help (lots) with Javascript
Post by: snalin on 26 Aug 2013, 15:16
Problem is, of course, that what nice code should look like... not set in stone. As many opinions as programmers. Don't get me started on tab vs. spaces discussions, or inline ifs or... jeez. Consistency is always a virtue, though. Find something that looks good, and stick to it. If you're working on an open source project or with a company, find out what the current style of the project is, and use that.
Title: Re: Need help (lots) with Javascript
Post by: Sorflakne on 27 Aug 2013, 11:30
Ah ok.  Gonna keep the ;'s then, since I'm still getting used to the code.

Ok, here's another thing I've run into, and it took some hair pulling and whatnot to figure out.  Here's code for two buttons:

Code: [Select]
<button onclick="timedCount()">Start count</button>

<input type="button" value="Start count" onClick="timedCount()" />
Both point to the same function when placed in the same block of code, but for some reason, only the top one works (this is for a basic timer; text of the function is the same for both attempts).  The second one creates a button, but its nonfunctioning.  I've had this happen several other times, and each time when I went back and changed the code from the second format to the first's, then it works fine.  What causes one to work and the other to not?

Edit: Ok I just did another timer code for practice, and now the second button code works, but the first one doesn't.  Wtf.
Title: Re: Need help (lots) with Javascript
Post by: bryntheskits on 27 Aug 2013, 11:49
Ah ok.  Gonna keep the ;'s then, since I'm still getting used to the code.

Ok, here's another thing I've run into, and it took some hair pulling and whatnot to figure out.  Here's code for two buttons:

Code: [Select]
<button onclick="timedCount()">Start count</button>

<input type="button" value="Start count" onClick="timedCount()" />
Both point to the same function when placed in the same block of code, but for some reason, only the top one works (this is for a basic timer; text of the function is the same for both attempts).  The second one creates a button, but its nonfunctioning.  I've had this happen several other times, and each time when I went back and changed the code from the second format to the first's, then it works fine.  What causes one to work and the other to not?

Get rid of the / after the onclick code, don't need that.

Other than that I cannot see what the problem could be, are you using anything to debug the Javascript? Even Chrome comes with a developer console, very handy.

EDIT: Nevermind, found the problem (what I could replicate here, anyway); onclick is supposed to be all lowercase, since methods are case sensitive it will only work that way, the 2nd bit of code you have there is in camel case (onClick) when it should be lower, like the 1st bit of code (onclick).
Title: Re: Need help (lots) with Javascript
Post by: snalin on 27 Aug 2013, 12:37
So, I wrote some test code:

Code: [Select]
<html>
<button onclick="timedCount(this)">Start count</button>
<input type="button" value="Start count" onClick="timedCount(this)" />
<script>
function timedCount(btn) {
console.log("pressed from: " + btn);
}
</script>
</html>

The "this" inside the onclicks just sends the button element in, so the timedCount method can print it out.
Pressing the first button results in: "pressed from: [object HTMLButtonElement] "
Pressing the second button results in: "pressed from: [object HTMLInputElement] "

So it seems like both input and button works from my side. Above poster is correct in that the onclick should be all lower case, but chrome handles both onclick and onClick in both the button and the input. Not sure about other browsers. You are wrong on the / not being required, it closes off the input tag... but it doesn't seem to matter if it's there or not. Javascript :psyduck:

Sorflakne, can you post your code? It'd help to be able to look at it.
Title: Re: Need help (lots) with Javascript
Post by: pwhodges on 27 Aug 2013, 13:30
Get rid of the / after the onclick code, don't need that.
You are wrong on the / not being required, it closes off the input tag... but it doesn't seem to matter if it's there or not.

<input> has no end tag in HTML (any version); however, in XHTML, the end tag is required.
Title: Re: Need help (lots) with Javascript
Post by: snalin on 27 Aug 2013, 14:22
Erp, didn't spot that, you are right.
Title: Re: Need help (lots) with Javascript
Post by: bryntheskits on 27 Aug 2013, 21:41
but chrome handles both onclick and onClick in both the button and the input.
Strange, for lack of proper time to test I used the developer console to change onclick to onClick and the onClick and it's variable disappears.
Title: Re: Need help (lots) with Javascript
Post by: Sorflakne on 28 Aug 2013, 13:25
Quote
Sorflakne, can you post your code? It'd help to be able to look at it.
I'm trying to remember which one it was (I've made several...serves me right for not giving each a unique name), but if I do, I'll post it.

On the topic of ASP stuff, the book I'm using has its ASP examples "written in VBScript for an Internet Information Server", to quote from it, and then has the file saved with an .asp extension.  Why do this, if the file is saved as .asp?  I get that for me this is rather advanced stuff so maybe I'm not seeing the reasoning for doing this yet (or maybe the book is wrong and you're not supposed to do this), but why not write the files in ASP and save them as such?  And on a similar subject, between ASP and PHP, which is the preferred coding, or are there times where one or the other is specifically required?

Quote
Other than that I cannot see what the problem could be, are you using anything to debug the Javascript? Even Chrome comes with a developer console, very handy.
I'm going to the console in Firefox and selecting Debug Mode, but nothing happens.  It displays the page code, but there's no indicators for stuff that's wrong, no way to manipulate text or whatnot...not really sure how to use it.
Title: Re: Need help (lots) with Javascript
Post by: bryntheskits on 29 Aug 2013, 03:49
ASP is more Windows based servers, while PHP is any (that's how I see it). I prefer PHP much more, and interact with more things and well I grew up with it so maybe I'm bias.

I don't use Firefox but there should be a console somewhere in the Developers part, there is in Chrome anyway.

https://developer.mozilla.org/en-US/docs/Tools/Web_Console

You should also be able to change code on the fly using the Inspecter (I think :P)
Title: Re: Need help (lots) with Javascript
Post by: Loki on 29 Aug 2013, 04:19
This is just a guess, but:

A button can stand alone pretty much anywhere in the document [1] (http://stackoverflow.com/a/14462417). An input MUST be within a form tag to confirm to the HTML standard, so that may be the problem.

Pretty sure there is no standard on attribute lower/upper case in the HTML specification. XHTML requires all lowercase. Are you using any document type declaration? If not, you should probably choose one (I think nowadays it doesn't really matter if you choose HTML5 or XHTML.) The important thing is that you stick to it. Make sure your HTML code uses the right syntax using http://validator.w3.org/.

The DTD basically tells the browser - any properly-programmed browser "hey, I am doing things this way". If you do things wrong, the browser will try to correct your code to what it thinks it should be, but it may be wrong.

No idea about ASP at all, sorry. However note that you can configure your server to treat any extension as anything you want, it is just not a good idea to do so. (You can also configure your PC to open all mp3-files with an image viewer, but that won't be a good idea either).

You might want to use http://www.jslint.com/ for validating the Javascript syntax. You will probably want to check at least the following:

Assume:
a browser,
console, alert,..

Tolerate...
assignment expressions
bitwise operators
continue
== and !=
++ and --
unused parameters

everything in the fourth column.
Title: Re: Need help (lots) with Javascript
Post by: Sorflakne on 29 Aug 2013, 11:13
Eh, most of the examples I've seen don't have <form> tags around the buttons if they're standalone.  Now if the buttons are connected with a text box or are otherwise more than just the button itself, then yeah, they pretty much all have <form> tags.

So between PHP and ASP, is it better to get smart on one and have at least a basic understanding of the other, or should a person know both about equally?

Also gave JSLint a try, and it kept telling me that I was missing "use strict" statements all over my code.  I've never heard of this, is "use strict" required for javascript writing?  Some of the info I've found says you can just put it in the first line of your javascript page, assuming you have all your stuff saved to a separate file from the webpage itself, and others say you can simply write it into its own function...how would you write a function for it?

On the other hand, JSLint seems nice, but it keeps giving back "so-and-so has not been defined"; it even does this for alert(); lines...how do you define alert(); (yes, there is messages enclosed by "" in them :P )?  I mean, the code I'm writing is modified from the book I'm using and trying to follow a similar format to it, which works fine when directly copied and tested in the browser, but JSLint keeps coming back with undefined's for the book's stuff and my own, even when adding exceptions in the Tolerate options.
Title: Re: Need help (lots) with Javascript
Post by: Loki on 29 Aug 2013, 11:29
*shrug*  I know my PHP and not a hint of ASP, served me well enough so far. (Of course, I don't program that much anymore. I study Computer Sciences after all.)
Title: Re: Need help (lots) with Javascript
Post by: Sorflakne on 29 Aug 2013, 11:36
But ASP looks so much cleaner than PHP though :P (sucks that it's more Windows-oriented than universal in that regard...)
Title: Re: Need help (lots) with Javascript
Post by: Loki on 29 Aug 2013, 11:43
Then learn ASP?

Out of curiosity, are you learning a serverside language for any special reason or just for the fun of it?
Title: Re: Need help (lots) with Javascript
Post by: pwhodges on 29 Aug 2013, 11:44
There comes a point, eventually (trust me), when you "get" the concepts that vary between languages in such a way that you can see them all as restricted dialects of one greater "computer language".  You may still have to learn different method names and the like in different environments, but that's what manuals are for, right?

Well, your mileage may vary I suppose, but that's how it went for me.

But as for ASP - that's a specific MS technology (though there is an open-source version), and most likely to be encountered in commercial all-Windows environments using IIS.  And even then something else, like PHP or Java/JSP or something is as common.  I wouldn't suggest learning ASP until you have an identified need to.  I currently have sites running PHP, Java/JSP and Perl on my Windows Server at home, but no ASP; in the office it's PHP, Java/JSP, Perl and ASP.
Title: Re: Need help (lots) with Javascript
Post by: Sorflakne on 29 Aug 2013, 11:59
Yeah, I'll probably wait until I'm more comfortable with javascript before diving too deeply into them, but it's nice to have an idea of them.

@Loki: I would like to put it to use eventually doing web design.  Yeah, I'm aware I've a ways to go in that regard.
Title: Re: Need help (lots) with Javascript
Post by: bryntheskits on 30 Aug 2013, 09:04
There comes a point, eventually (trust me), when you "get" the concepts that vary between languages in such a way that you can see them all as restricted dialects of one greater "computer language".
^this

All through my CS degree this has been drilled into me, and it is very true for a lot of languages.