Javascript 101

All javascript works in both the header or the body elements,<p/ but you will find programmers usually prefer the body element. Javascript is written between  elements. Any paragraph or head statements will not work in this area. There will be more exercises in Javascript. Test yourself in every section. Write the JS to see how it works. Do the exercises and email them to me so I can critique them and get back to you. George1936@echarter.net.

Variables, Numbers and Strings

Variables are the workhorse of javascript;There are some reserved words that cannot be used for variables.  They are listed at the following website.

http://www.javascripter.net/faq/reserved.htm


The language of javascript contains numbers and strings.

Numbers can also be a string.  Strings alway have quotes around them. If you put quotes around a number, it becomes a string. x = 22 + “22” =2222 but x = 22 + 22 = 44; See the difference?

Variables are written in camelCase. They cannot start with a number;
Get use to camelCase. Always use it with variables.  The first letter is always lower case and if  there are 2 different words or half words the second is always capitalized.
‘bigmuscles should be bigMuscles’, ‘totcalcost should be totCalCost’… and so on.
You could use almost anything for a variable. Like a, a22, x, “Hi”, “anythingForAvariable”.


In order to use variables in javascript you have to declare them.
sam = “Tall”; not declared.
var sam = “Tall”; declared . It only has to be declared once unless you change it’s value.
Your browser will not recognize a variable unless it is declared or as some say defined.  A variable can be declared equal to any number of other values.

Almost all javascript actions end with ‘ ; ‘ The semicolon seperates parts of the javascript codes.
———————————————————————–

alerts; Check the syntax-
‘alerts’   give the programmer an opportunity to communicate with the user.    var sam = alert(“How are you?”);        An alert which says ‘How are you’ is assigned to the declared variable sam..

Try declaring a few variables and use them with different alerts.

var greet = “Hi”;
alert(greet);
Gives you a window alert that says Hi.
———————————————————————-
Operators;
The below Operators are seperated in almost cases with a space on either side.
Operator Description
+ Addition
– Subtraction
* Multiplication
/ Division
% Modulus if 6 is divided by 5 the remainder is the modulus or 1
++ Increment will get into later
— Decrement will get into later

———————————————————————–
Try this one out yourself:

———————————————————————–
An alert gives you a pop-up window and document.write will allow you to write to the page itself.
document.write(“How are you”); writes How are you on the screen. Unlike an alert, document.write erases everything else.

Concatenation:
This is the special way you write in alerts and document.write texts.  Variables are not strings but they represent strings and they require no quotes around them. You can tie text, variables and numbers together to represent whatever you like in alerts and document.writes, but the rules are specific. Each part of the message must be seperated by a + sign with a space on all sides of every entry. Numbers cannot be added in concatenations because of the conflict with the ‘+’ sign seperating the parts but they can be converted to numbers as we will see later.  Make sure you leave a space between the different math expressions, strings and variables in alert and document.write messages.



The syntax shows all variables are seperated by a + with a space on either side of it. If you don’t do this it will not work right.
———————————————————————-
Prompts;
This is another way to communicate with the user. The general syntax is below. They always require a declared variable. ‘prompts’, when responded to, gives a value to a variable which can then be used in a an alert or document.write and many other javascript expressions.
var pets = prompt(“What kind of cat is that?”);
This prompt provides a user with a blank pop-up window that asks the user ‘what kind of cat is that?’. The user then replys and presses the OK button that is provided. The variable pets contains the string or number with whatever answer was given to the prompt. You can add a default answer to a prompt using the below syntax.
var pets = prompt(“What kind of cat is that?”, “A long haired one” );
If the answer was “A stray” then alert(pets); would give you ‘A stray’. If no answer is given the default answer “A long haired one” shows and the variable pets contains that value. We will be using alerts and prompts a lot in these tutorials.
———————————————————————-
arrays
This creates an empty array’ var nums = [];’
Arrays can be a tremendous help both time-wise and organizationally. Below shows how you define a avariable.
var cities = [“Tampa”, “Turlock”, “Stockton”, “Medford”);
Syntax: The Elements in an array are seperated by a space and a comma. Forget just one and not nothing works.
———————————————————————–
alert(cities[2]);
alert(cities[3]);
alert(cities[0] + ” and ” + cities[1] + “are the cities I know the best”);
Gives you “Turlock and Stockton are the ones I know best”.

You start counting elements in an array with zero being the first element. In the above array Stockton would be element number 2.
The syntax cannot change. The commas and type of bracket are very specific.
———————————————————————-
Syntax:  Try this one and some of your own.


    
    

————————————————————————
var cities = [“Tampa”, “Turlock”, “Medford”,” Stockton”, “San Diego”, “Dallas”, “Austin”];
var howLong = cities.length; This will give the number of elements in the array which is 7.  Remember the syntax of this key word. array name.length returns the number of elements in an array. var cities = [“Tampa”, “Turlock”, “Medford”,” Stockton”, “San Diego”, “Dallas”, “Austin”];
howLong = cities.length;
alert(howLong);
This will give you 7
cities.pop(); will remove the last element of the array cities.
var shorter = cities.length
alert(shorter); This will give 6

Try out a few of these on your own.
—————————————————————————————
shift- removes an element from begining of array nums.shift();
————————————————————————————–
push-adds one or more elements to end of an array
var cities = [“Tampa”, “Turlock”, “Medford”,” Stockton”, “San Diego”, “Dallas”, “Austin”];
Remember the length is 6.


————————————————————————————-
Some more way to change the arrays;
shift– removes an element from beginning of array. nums.shift();
unshift– add one or more elements to beginning of an array. nums.unshift(“cats”, “dogs”);
splice– inserts one or more elements in an array while optionally removing one or more elements that come after it. 1st number inside () is the index where you add or delete and the 2nd number is how many to remove. num.splice(2, 2 , “Cat”);

slice– copies 1 or more elements from any position and puts them in a new array. The original array is unchanged. If you use the of the original array you reduce the elements of the original array to the one you copied. ist num inside () is the index of the first element to be copied. The 2nd number is the index of the element AFTER to be copied. cities.splice(2, 2);


It is possible to sort arrays and pinpoint the element locations inside an array.  Notice the sort num.sort();   that sorts the arrayUse num.reverse(); to reverse sort and array. Copy paste this into an editor and see that it sorts the numbers from smallest to biggest. Notice that the sort relies only on the first digit of the number. Now try it without the sort and note the difference.  Convert the numbers to strings by putting quotes around them and notive that the sort starts with the first number. 22 would be smaller than 3 with both numbers or strings.  Reverse the order of this array.   Later on we will learn how to sort numbers in numerical order using functions.

    


Hello






 

————————————————————————————–
The if, else if and else statements;
You can use prompts or variables for testing and prompt answers, alerts, document.write, getEementsById for the responses.  Pay close attectionn to syntax spacing and bracket type ane placing. If you use’document.write you will get your answer but everything else on the page will disappear.






————————————————————————————–
In the below example If dogCatch does not equal Mr. Cage then nothing happens.  The else statement takes care of this.




Before we go on make up a few variables and prompts and use them with if statements.   Use them with numbers and strings.

In the below example notice the prompt is asking a question and could have many answers like  ‘a lot or 40’ The answer, which is 48, will always be a string so in a comparison statement we must use quotes around the answer when used in comparison statements like ‘   if (ques === “48”) { ‘THe only way to make comments in javascript scripts is to use // and everything infront of it to the line break will be ignored by the browser. Note its use in the below example.





———————————————————————-
‘ Using if, else, and else if together gives you more flexibility. In the below code the else statement gives a default answer when the above criteria is not met.  There can be many many  ‘if and else if’ statements to narrow down your results or give you a wider range of answers.

var ray = prompt(“Where do you live?”);          
if (ray === “Turlock”) {                                            
   alert(“I live there too!”);
}
else if (ray === “Tampa”) {
   alert(“I use to live there”);
}
else {
  document.write(“Where is that?”);
}
————————————————————————————-
Sets of Conditions;
&& is and
|| is or
!== is not equal



The above condition In words ‘if you can run a hundred meters in less than or equal to 10 seconds and you can bench press over 200 pounds and your height is over 72 inches, then Youmust be a superhero! Make some more comparisons using all of the variables and comparison tags.






Practice with different sets of conditions as shown above. Contact me if  you have problems.
———————————————————————
If (a === b && c === d) { is correct syntax
if a = b and c = d

If (a === b && c ===d || a >= b) { is correct syntax

if (a === b * c === d) { is not correct – should be if ((a === b) * (c === d)) {

if (a * b === c + d) { is not correct – should be if (a * b === (c + d)) {
if a times b = c plus d

 

You get different answers if you don’t set up you math correctly.
————————————————————————————–
The next section deals with functions and loops

Go to Beginning
On to JS 102

Close Menu