Basic JavaScript

From Wikiversity
Jump to: navigation, search

Basic JavaScript is an introductory lesson for the topic of JavaScript.

Recommended prior lesson: HTML

Basics[edit]

  • JavaScript is a popular web-page scripting language, and is supported by almost every browser.[1][2]
  • It adds interactivity to web-technology pages.[3]
  • You can use editing tools on your device or within supporting software.
  • JavaScript can work with the user's (client) resources or server resources.
  • It is easy to learn the basics.

Step One: HTML & Scripts[edit]

Applications-accessories.svg
Activity: Open up your text editor of choice and create a basic page (a basic note pad works great). Now I am going to teach you how to write on your webpage using JavaScript. Type the following into your text editor:
<html>
        <head><title>Hello World!</title></head>
 	<body>
 		<script type="text/javascript">
document.write('Hello World!');
 		</script>
      </body>

</html>

As you can see, our JavaScript instruction (document.write('Hello World!');) is added directly into your HTML by adding the <script> tag. Now save the text file with an HTML file extension. Use the "save as" function for your text editor and change the filename from something like "New Text Document.txt" to "Hello World.html". Use the .html in place of the .txt, .doc, .rtf, etc... Open your newly saved file in a browser. If all went well "Hello World!" will display in your browser as HTML content. If not, perhaps set your computers folder options to show filename extensions. Javascript and 'filename changes' are not always available (by default).

Video Resources: Javascript 1

To start off with, the <script type="text/javascript"> tag tells the browser that whatever comes between that tag and the coming </script> tag is script, and the type="text/javascript" tells it that it is JavaScript. Similarly, to use VBScript, you might use type="text/vbscript" instead of "text/javascript". For the purposes of this course, though, you should only ever need to use the JavaScript tag.

It is also important to note that the <script> tag is case sensitive. What this means is if you use lowercase letters in the tag, all the letters in the tag must be lowercase, and uppercase if you use any uppercase. For example, if you wrote

<ScRiPt TyPe="TeXt/JaVaScRiPt">

Not only would you waste a lot of time typing, but you would also confuse your browser.
You are probably wondering when I'm going to explain the rest of what you did. Well, document.write() is the JavaScript standard for writing text to the browser window. The 'document' clause refers to the HTML webpage (termed a document) as a whole; what follows ('.write()') is a command for the document object to carry out. In this case, you told the page to write the classic "Hello World" to the screen.

Comments[edit]

//(Brian Crowder) A 'Hello source-reader' contribution.

.

Step Two: Variables[edit]

One of the things JavaScript is used for is the manipulation of data. In JavaScript, pieces of data can be stored either in variables or arrays.

Variables are declared using the var keyword:

var numValue;
var textValue;
var binaryValue;

and can be given values when they are created:

var numValue = 3;
var textValue = "This is text.";
var binaryValue = true;

Multiple variables can even be declared at the same time:

var numValue = 3, textValue = "This is text.", binaryValue = true;

Variables in JavaScript are weakly typed, meaning that the types of individual variables are not determined by the programmer. Unlike many languages, JavaScript only provides a generic var rather than separate types for integers, floating point numbers, characters, and strings. For example, in the statement

var x = 0;

it is fairly obvious to any individual reading the code that x is a number. However, if the statement

x = x + "This is text that is probably not a number";

were to appear later in the code, JavaScript would change the variable to a text variable. This is one of the reasons that JavaScript is referred to as weakly typed; at any particular point in time, it is impossible to tell exactly what type a particular variable is.

Step Three: Operators[edit]

Arithmetic Operators[edit]

Operator Description Example Result
+ Addition x = 2

y = 2

x + y

4
- Subtraction x = 5

y = 2

x - y

3
* Multiplication x = 5

y = 4

x * y

20
/ Division 15 / 5

5 / 2

3

2.5

% Modulus (division remainder) 5 % 2

10 % 8

10 % 2

1

2

0

++ Increment x = 5

x++

6
--

(two adjacent hyphens)

Decrement x = 5

x--

4

Assignment Operators[edit]

Operator Example Is The Same As
= x = y x = y
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
 %= x %= y x = x % y

Comparison Operators[edit]

Operator Description Example
== is equal to 5 == 8 returns false
=== is equal to (checks for both value and type) x = 5

y = "5"

x == y returns true

x === y returns false

 != is not equal 5 != 8 returns true
> is greater than 5 > 8 returns false
< is less than 5 < 8 returns true
>= is greater than or equal to 5 >= 8 returns false
<= is less than or equal to 5 <= 8 returns true

Logical Operators[edit]

Operator Description Example
&& and x = 6

y = 3

(x < 10 && y > 1) returns true

|| or x = 6

y = 3

(x == 5 || y == 5) returns false

 ! not x = 6

y = 3

!(x == y) returns true

String Operator[edit]

The string operator is used to concatenate two strings together. For example:

var x = "Hello " + "world!"

Applications-accessories.svg
Activity: Repeat our first activity with a variable and operator as shown below:
<!DOCTYPE html>
<html>
        <head><title>Hello World, Again!</title></head>
 	<body>
 		<script type="text/javascript">
                        var x = "Hello " + "world!" 
                        document.write(x);
 		</script>
       </body>
</html>

The above example results in the variable x equaling "Hello world!".

  • Save the document as helloAgain.html and open it in a browser.


Conditional Operator[edit]

JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.

The syntax would be:

 variablename = ( condition ) ? value1 : value2 

value1 is the value of the expression if "condition" is fulfilled. value2 is its value in the case "condition" is not fulfilled. For example:

var x = "Hello " + "world!"

Applications-accessories.svg
Activity: Repeat our activity with a conditional operator that assigns a value to a variable as shown below:


<!DOCTYPE html>
<html>
        <head><title>Hello World, Again!</title></head>
 	<body>
 		<script type="text/javascript">
                        var x = "hello"; 
                        var towrite = ( x == "hello")? "Hello world, again!" : "Look at the state of that!" 
                        document.write(towrite);
 
//The example results in "Hello world, again!" because x is "hello" and condition "Hello world, again!" is logically true.
 		</script>
 
 
<p>
Save the document as helloToo.html and open it in a browser. 
Change the line var x = "hello" to var x = "punk" and use CRTL + S to save. 
Run it in your browser.
</p>
       </body>
</html>


References[edit]

  1. http://en.wikipedia.org/wiki/Comparison_of_web_browsers#JavaScript_support
  2. Flanagan, David JavaScript:The Definitive Guide. O'Reilly Media, 2006 , p. 1.
  3. Flanagan, David JavaScript:The Definitive Guide. O'Reilly Media, 2006 , p. 236.