Different methods of declaring JavaScript variables
// declaring one javascript variable var firstName; // declaring multiple javascript variables var firstName, lastName; // declaring and assigning one javascript variable var firstName = 'Homer'; // declaring and assigning multiple javascript variables var firstName = 'Homer', lastName = 'Simpson'; |
Using JavaScript variables
Although there are many uses for JavaScript variables, here is a quick and dirty
Example:
Rules for JavaScript Variables
* Can contain any letter of the alphabet, digits 0-9, and the underscore character.
* No spaces
* No punctuation characters (eg comma, full stop, etc)
* The first character of a variable name cannot be a digit.
* JavaScript variables' names are case-sensitive. For example firstName and
FirstName are two different variables.
Writing a function in JavaScript
It's not that hard to write a function in JavaScript. Here's an example of a JavaScript function.
Results:
Call the function: |
Example If statement:
Results:
Just like the sky! |
Example If Else statement:
Results:
Didn't pick blue huh? |
Example If Else If statement:
Results:
Just like shiraz! |
Example For statement:
Results:
My bank balance is $0 My bank balance is $1 My bank balance is $2 My bank balance is $3 My bank balance is $4 My bank balance is $5 My bank balance is $6 My bank balance is $7 My bank balance is $8 My bank balance is $9 My bank balance is $10 |
Example of void(0):
We have a link that should only do something (i.e. display a message) upon two clicks (i.e. a double click). If you click once, nothing should happen. We can specify the double click code by using JavaScript's "ondblclick" method. To prevent the page reloading upon a single click, we can use "JavaScript:void(0);" within the anchor link.
Results:
Same Example, but without void(0):
Look at what would happen if we didn't use "JavaScript:void(0);" within the anchor link...
Results:
Code with a Try... Catch statement:
Results:
Sorry, an error has occurred...but hey, don't let that stop you! |
No comments:
Post a Comment