For loops in JavaScript

0

For loops in JavaScript

For is a repetitive instruction. It is used when you wish to perform a command several times.
In javaScript we can use the following repetitive instruction:
  • for - loops through a block of code a specified number of times
    for ... in - loops through the elements of an array or through the properties of an object.
    for each ... in - iterates over the property values of an object.

1. The for loop

The for loop is used when you know how many times the script should run. It has the following syntax:
for (nr_start; condition_nr; nr_increment) {
    code to be executed
}
- "nr_start" specifies a variable and assigns an initial value to it. It sets up the initial state for the loop.
"condition_nr" This second part tests for a condition. The loop will keep running as long as this condition is True.
"nr_increment increments or decrements the "nr_start", then its value is checked again with the second parameter, "condition_nr", until the result is FALSE.
Inside the for instruction you can introduce other "for" or any conditional statements.
Here's a simple example using the "for":
<script type="text/javascript"><!--
for (i=0; i<5; i++) {
  document.write("<br /> i = "+i);
}
--></script>
- These statements define a loop that uses the variable "i", initializes it with the value of zero, and loops as long as the value of "i" is less than 5.
- The increment expression, "i++', adds one unit to the value of "i" with each iteration of the loop.
- Because this happens at the end of the loop, the output will list the numbers zero through five.
This script will display the following result:
i = 0
i = 1
i = 2
i = 3
i = 4

2. The for ... in loop

The for…in loop is less flexible than an ordinary for() loop. This instruction goes through the elements of an object (or an Array) and gets the name (or key) of each property of that object.
The "for ... in" has the fallowing sintax:
for (variable in object) {
    instructions
}
- "variable" is a index variable that takes the name of the property. For each iteration of the loop, the variable is set to the next property of the object.
Example:
<script type="text/javascript"><!--
var obj = {apple:100, bool:false, astring:"coursesweb.net"};
for (var prop in obj) {
  document.write(prop + ' - '+ obj[prop]+ '<br />');
}
--></script>
- Results:
apple - 100
bool - false
astring - coursesweb.net

3. for each .. in

Another loop structure built on the "for" keyword, is the for each .. in loop. It works the same way as "for .. in" , but instead of iterating over an objects property names, it iterates over the property values.
The general syntax is:
for each (variable in object) {
    statements;
}

The following is an example of using of "for each .. in" on a custom object.
<script type="text/javascript"><!--
var obj = {apple:100, bool:false, astring:"coursesweb.net"};
for each (item in obj) {
  document.write(item + '<br />');
}
--></script>
- This will produce the following output:
100
false
coursesweb.net


Conditional statements: if, else, switch

0

Conditional statements: if, else, switch

The most interesting, but difficult, in writing a script is designing it so that it can take decision while is executed.
Using conditional instructions can make programs to test various conditions and then decide how to manipulate the datas.
JavaScript uses the following conditional instructions:
  • if - use if statement to execute some code only if a specified condition is True.
  • if ... else - it executes some code if a condition is True and another code if the condition is not true..
  • switch - selects which piece of code to be executed.

1. The "if" statement

The general form of this instruction is the following:
if (condition) {
  The code will be executed if condition is true
}
- 'condition' can be any logical expresion.
- If 'ondition' return TRUE, executes the code within curly braces, otherwise, when the condition returns false, it passes over the code.
Here's an example. The following script prints "Hello" if the hour is greater than 11.
- We use the Date object, will be explained in another lesson.
<script type="text/javascript"><!--
// if the hour > 11, prints Hello!
var d = new Date();
var time = d.getHours();
if (time>11) {
 document.write("<b>Hellow!</b>")
}
--></script>
- We defined the variable 'd', whose value is an object with the current date, then the variable 'time' takes only the hour from the variable 'd'. The condition of 'if' statement checks if 'time' is greater than 11 and if True executes the command of the braces, which displays the message.
If the hour is less than 11, the script will do nothing.

2. The "if ... else" statement

In the previous example we saw that it displays "Hello!" if "time>11" and if not, nothing happens.
Using the instruction "if ... else" we can set commands to be executed when the condition of "if" instruction" is FALSE.
The general form of the "if ... else" instruction is:
if (condition) {
  The code will be executed if condition is True
}
else {
  The code will be executed if condition is False
}
- 'condition' can be any logical expresion.
If 'ondition' return TRUE it is executed the code inside the first braces (that belongs to "if"), otherwise, when the condition returns false it is executed the code of the second group of braces (after else).
Here again the previous example, this time using the "if ... else" statement.
The script displays "Hello!" if the hour is greater than 11, otherwise display "It's ... o`clock".
<script type="text/javascript"><!--
// if 'time' > 11, prints Hello!
// Otherwise "It's ... o`clock"
var d = new Date()
var time = d.getHours()
if (time>11) {
  document.write("<b>Hello!</b>")
}
else {
  document.write("<b>It`s " +time+ " o`clock</b>")
}
--></script>
- If 'time' is less than 11 the script will execute the code of second braces group, from "else".

3. switch statement

This instruction is used to compare a value with others from a list.
The syntax of switch instruction is:
switch (expresion) {
case value1:
    code executed if expresion = value1
    break
case value2:
    code executed if expresion = value2
    break
case value3:
    code executed if expresion = value3
    break
default :
    code executed if expresion is other then value1, valoare2 or valoare3
}
- First we have a single expression between parentheses (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically.
Here is a sample script that displays a message depending on weekdays:
<script type="text/javascript"><!--
var d = new Date();
var day = d.getDay();

switch(day) {
 case 5:
   document.write("Today is friday");
 case 6:
   document.write("Today is saturday");
 case 0:
   document.write("Today is sunday");
 default:
   document.write("There is a lot until saturday");
}
--></script>
- The variable 'day' takes the number of the week-day from the variable 'd' (Sunday = 0, Monday = 1, ...).
- The switch statement compares the value of "day" with the value of each "case". If there is a match, the block of code associated with that 'case' is executed.
- If none of the values of 'case' match the variable 'day', will execute the code associated with 'default'.

Here is another example where the "case", uses string values.
<script type="text/javascript"><!--
var nume = "Marius";
switch (nume) {
 case "Cristi":
   document.write("Friend");
   break
 case "Marius":
   document.write("Brother");
   break
 case "Maria":
   document.write("Sister");
   break
 default:
   document.write("Somebody else");
}
--></script>
- Will return Brother.


JavaScript Operators

0

JavaScript Operators


With operators we can manipulate, combine and modify data in a program or script. There are many kinds of operators, in this lesson it is presented the types of operators used in JavaScript.

1. Arithmetic operators

We can say that arithmetic operators are the main operators for numbers, they make arithmetic operations:
  • = (used to asign values) - eg, (x=8)
  • + (used to add values) - eg, (x=7+8)
  • - (substraction) - eg, (x=7-8)
  • * (multiplication) - eg, (x=7*8)
  • / (division) - eg, (x=7/8)
- Besides these operators there are other special operators used in programming.
  • Modulo (%) - it determines the rest of the division of two numbers
    Example:
    • 8%3 result 2
      10%2 result 0
  • Increment (++) - This operator increases the value by one unit, is often used in programming.
  • For example, if we have a variable 'i', we can use the increment operator: i++ which is similar to i = i+1.
    Example:
    • x = 7;
      x++;
      the result is x = 8
  • Decrement (--) - This operator substract the value by one unit.
  • If we have a variable 'i', we can use the decrement operator: i-- which is similar to i = i-1.
    Example:
    • x = 7;
      x--;
      the result is x = 6
  • These two operators can be also placed before the variable name (++i, --i). The result value is the same, but the order of operation is different. In this case, first modify the value and then it assign it to the variable.

2. Assigning operators

These operators evaluate first the operand on the right and the value is assigned to the variable of the left side of the sign "=".
OperatorExampleSame 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

3. Comparation operators

Expressions using these operators make a question about two values which they compare. The answer can be TRUE or FALSE.
A commonly used comparison operator is the identity operator, represented by two equal signs "==".
Comparison operators are presented below:
OperatorMeaningExample
==     Identical     3 == 8   result FALSE
!=     Different     3 != 8   result TRUE
>     Bigger     3 > 8   result FALSE
<     Smaller     3 < 8   result TRUE
>=     Bigger or identical     3 >= 8   result FALSE
<=     Smaller or identical     3 <= 8   result TRUE

4. Logical operators (booleans)

The logical operators compare two expressions and return TRUE or FALSE.
  • && - AND - It compare two expressions and return TRUE if both are true, otherwise it returns FALSE.
    • x = 5
      y = 8
      x<7 && y>3
      (return TRUE)
  • || - OR - It compare two expressions and return TRUE if at least one of them is true, otherwise it returns FALSE.
    • x = 5
      y = 8
      x>7 || y<3
      (return FALSE)
  • ! - NOT - unary operator, uses a single expression and returns TRUE if the expression is false, if the expression is true, returns FALSE.
    • x = 5
      y = 8
      !(x==y)
      (it returns TRUE becouse 'x' and 'y' are different)

5. Operator used on strings

The "+" operator can also be used to join (add) string variables or text values together.
  • t1 = "Have a good "
    t2 = "life."
    t3 = t1+t2

    (The 't3' variable will contain the string "Have a good life.")

6. The typeof operator

This operator returns the data type of its operand. It is especially useful to determine if a variable is defined with a specific data type. 
Studying the table below you can understand how thi operator works:
OperatorDescription
 typeof parseFloat returns the string 'function'
 typeof 33 returns the string 'number'
 typeof "some text" result 'string'
 typeof true returns the string 'boolean'
 typeof window returns the string 'object'

7. Operators used on functions

Functions will be explained in one of the following lessons, however it is useful to be familiar with two operators:

1. The first is known as calling operator and is represented by a pair of parentheses () who are always after the function name. A function is declared as follows:
function function_name() {
  // Instructions
}
Then, the "callig operator" is used when we call the function in the script:
  • function_name()
The parentheses shows that we use a function. 

The second operator for functions is the comma operator (,) which is used to separate multiple arguments that a function receives. 
The arguments are always written inside parenthesis, and separated by commas. 
A function with two arguments would look like:
function function_name(arg1, arg2) {
  // Corpul functiei
}

8. Operators used on objects

1. The main operator for objects is the character point (.). This operator allows us to refer to a member (variable, function or object) that belongs to the specified object. 
The syntax is:
  • objectName.variable_name
    objectName.function_name()
    objectName.childObject
This way of referring to an information, called point notation, returns the value of variable, function or object at the right.

2. The operator for array elements, a pair of brackets [], called the array index operator, allow us to refer to any member of an array. 
JavaScript arrays are objects and will be detailed in subsequent lessons. 
The syntax for using this operator is
  • array_name[key]

9. Conditional operator "? :"

JavaScript contains a conditional operator ? : that assigns a value to a variable based on condition.
The syntax for using this operator:
  • variable = (condition) ? val1 : val2;
- It evaluates the condition, if it's True then the variable takes the value 'VAL1', otherwise, takes the value 'VAL2'. 
Here's an example:
<script type="text/javascript">

var visitor = "man";
message = (visitor=="man") ? "Sir. " : "Dear Madam";
document.write(message) 
</script>
If the variable "visitor" has the value 'man', the variable "message" gets the value 'Sir.', otherwise receives the value "Dear Madam". And the display instruction "document.write()" will display the value of "message".

10. Operators precedence

When in expressions are used many operators, the JavaScript takes into account the precedence (the importance) of each operator. As in arithmetic, in an equation with multiplication and addition (2 + 3 * 4), if there aren't parentheses, multiplication is performed first. The same thing is for the programming operators, too. 
If there are several operators with the same precedence, JavaScript will evaluate them from left to right. 
The following table apresents in order the precedence of the operators:
OperatorDescription
()   []   .     for calling, data structures
!   ++   --     negation, increment
*   /   %     multiplication, division
+   -     addition, subtraction
<   <=   >   >=     comparison
==   !=     equality
&&     logical AND
||     logical OR
? :     conditionnal
=   +=   -=   *=   /=   %=     assigning
,     comma


Variables and Operators

0

Variables and Operators

In this tutorial you will learn the basics of programming, which are required to write a script. These notions are similar to those of PHP and other programming languages.

1. Using variables

In a script (or program) we use constants and variables datas. The variables can change their values during program execution. These data are called "variables".
  • Variable = name of a location in computer memory, used to store data.
The simplest way to use and refer to a variable is to write it. The name of the variable permits the access at its value and also can change the value if necessary. 
You can create a variable and assign a value to it in this way:
- With statement var
var name = value;
- You can change its value just using the variable name (without "var"):
name = other_value;
Variable Types - Unlike other languages (such as Pascal or C), JavaScript has no fixed types of data, that allows you to change the type of a variable in the script, it can recognizes when the data is a string, numerical or other type. 
For example:
var x = "xyz";
x = 8;
Notice that the 'string' values (consisting of letters) are written between quotation marks (simples or doubles), and the 'number' can be written without quotation marks. 

The life spam of a variable - A variable written within a function is a local variable, its value is recognized only within that function, it doesn't exist out of that function. Thus, another function can declare a variable with same name, JS (JavaScript) treats the two as different variables (functions and working with it will be explained in a subsequent lessons ).
The variables created out of the functions can be used everywhere in that script, inclusively inside the functions and other JS script from that HTML page.

2. Operators

To work with datas in a script and manipulate variable values we use operators.
Operators are symbols and identifiers that determines how data are modified and how it is evaluated a combination of expressions and variables.

JavaScript recognizes:
  • binary operators - that need two operands.
  • unary operators - that need only one operand.
Operators are several types:
  • - Arithmetic operators
    - Assigning operators
    - Comparation operators
    - Logical operators (booleans)
    - Operators for strings
    - Typeof operator
    - Conditional operator (? :) 
    - Operators for functions
    - Operators for objects
These will be detailed in the next lesson.


JavaScript Syntax

0

JavaScript Syntax

1. Adding JavaScript in an HTML page

To insert JavaScript into an existing HTML document, it is necessary to introduce the label <script> </script>. This tag requires the "type" attribute, or the attribute "language" (the latter is depreciated in XHTML) that will specify to the browser the language used to interpret the included code.
Inside the label <script> ... </script> we write our JS code.
To write and execute JavaScript programs we need a simple text editor (such as Windows Notepad or emacs Unix) and a browser (Mozilla Firefox, Internet Explorer).
- The "language" attribute (which is not used in XHTML, but only in standard HTML Web pages) - will have the following syntax:
                language = "JavaScript"
- the browser specifies which language is used.
- The "type" attribute - replacement of "language" - will have the following syntax:
                type = "text/javascript"
- this tells the browser that the script is written in plaintext format with JavaScript code.
We can also place the JS instructions in a separate JavaScript file, external, that will have the ".js" extension. To edit this file is needed only a simple text editor, like Notepad. The advantage of an external file is that we can use the same code in multiple HTML pages in case of a # necessary change in the JavaScript code, we just need to modify the data in a single file (the one with the extension. "js"), the disadvantage of this method is that in an ".js" external file we can't use HTML tags, but JavaScript instructions.
If the JavaScript code is in an external file, the label <script> from HTML page should contain the "src" attribute, whose value determines the location of the external ".js" file.
In the external file, the one with ".jx" extension, we should not write the "<script>" tag.
Here is a sample JavaScript script written within a web page (XHTML):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Cod JavaScript</title>
</head>
<body>
    <script type="text/javascript">
        document.write("The text will be displayed");
    </script>
</body>
</html>
For HTML:
<html>
<head>
<title>Cod JavaScript</title>
</head>
<body>

<script type="text/javascript">
  document.write("The text will be displayed");
</script>
</body>
</html>
- The document.write instruction is used to print something on the page.
- The displayed result of this script (XHTML and HTML) will be:
The text will be displayed

&bull If you want to load the script from an external file (eg, "code.js "), our code in the HTML document will look like:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ro">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Cod JavaScript</title>
</head>
<body>
    <script src="cod.js" type="text/javascript">     </script>
</body>
</html>
- The "code.js" contains:
  • document.write("The text will be displayed")

2. Hiding code in old browsers

Some browsers do not recognize the scripts and displays them on the web page as text. To avoid this we can use the HTML tag for comments <!-- ... --> delimiting with this the JavaScript instructions, thus it avoids the appearance of script in web page:
This is done as you can see in the following example:
<script type="text/javascript"><!--
        Codul scriptului
--></script>

3. Syntax conventions

In any language, the code has conventions and rules of syntax.
Now it's presented the JavaScript syntax rules:
  1. Case-sensitive - It makes distinction between large and small letters, such words as "examples, Examples" will be treated differently.
  2. Semicolon (;) - All line statements must end with a semicolon character (;) (Example" var1 = 3; var2 = 8;).
  3. Blank spaces - JavaScript ignores blank spaces, tabs and blank lines that appear in the instructions, they are useful for making code more structured and easy to read. Admit only the spaces that appear in strings. (Example: var1 = 2; is the same as var1 = 2;).
  4. Quotes - The single quotes ('') and double quotes (" ") are used to delimit strings. (Example: 'I learn JavaScript' or "I learn JavaScript").
  5. Special Characters - When we write scripts, sometimes we need to use a special character in values or in data output, or a key press such as the TAB key, or a new line. In that case we must use the backslash character "\" in front of one of the Escape codes:
    • \b - backspace
      \f - new page
      \n - new line
      \r - indicate a carriage return
      \t - indicate a pressing TAB key
      \\ - a backslash character
      \' - indicate an apostrophe (single quotes)
      \" - double quotes

    • For example, if you want to display a text using document.write(), and that text should include quotes and backslash character "\", like ("JavaScript" Course \ www.MarPlo.net), to not confuse the script in code interpretation, becouse the quotes and backslash are part of the syntax, we add \ in front of these characters within the string. The command for display the string will be: document.write ("\" JavaScript \" Course \\ www.MarPlo.net");
  6. Comments - The comments within the code are necessary when we want to specify the role and functions of certain variables or instructions, for easy understanding of the script later.
    To add a comment on a single line, inside the code, use double slash //. All characters to the right of the double slash represent a comment.
            Example:   // Comment on a single line
    If you want to write comments on multiple lines, use /* at the beginning of the comment, and */ at its end
            Example:
    /* comment on ...
    multiple lineas
    ... */
    .
  7. The name of the variables and functions - The name given to variables and functions must follow the following rules:
    • - The first character must be a letter, an underscore (_) or $ sign.
      - The first character can not be a number.
      - the name should not contain blank space.
      - Do not use reserved words that are part of the JavaScript language (such as "array", "status", "alert"), because the interpreter program will not make the difference between these names and JavaScript commands with the same name.


Introduction to JavaScript

0

Introduction to JavaScript

JavaScript was first developed by the Netscape company, with the name "Live Script", a scripting language that extended HTML capabilities, offers a partial alternative to using a large number of CGI scripts to process forms and information that add dynamism to web pages.
After the release of Java, Netscape began to work with Sun, in order to create a script with a similar syntax and semantics of Java, and for marketing reasons the name of the new scripting language was changed to "JavaScript:".
JavaScript has emerged from the need to that the logical and intelligent be on the client side too, not only on the server side. If all logic is server side, all processing is done at the server, even for simple things, such as data validation. Thus, JavaScript makes it endows the client relationship to be a true client-server system.
HTML Web page authors offer some flexibility, but static. HTML documents can not interact with the user in other things more dynamic than it provides links to other resources (URLs). Creating CGI's (Common Graphics Interface) - [programs running on Web server and accept incoming information from the website and returns HTML] - led to the enrichment of work opportunities. Thus, an important step to interaction was made by JavaScript that allows to insert scripts that run within the web page, specifically in the user's browser, thus easing traffic between server and client. For example, a page for collecting data from the user can add JavaScript scripts to validate the accuracy of introduction and then the server sends only datas to be processed correctly.
JavaScript contains a fairly extensive list of features and commands to help with mathematical operations, string manipulation, sounds, images, objects and browser windows, checking URL links and data entries of the forms. The code for these actions can be inserted into the web page and executed by the visitor's computer.
After its launch in December 1995, JavaScript has attracted support and key industry vendors such as Apple, Borland, Informix, Oracle, Sybase, HP and IBM. It developed further, obtaining recognition of most browsers. Understanding the importance of web site scripting, Microsoft wanted to provide support for JavaScript. Netscape has chosen to license Microsoft's technology in place to sell, so Microsoft has analyzed JavaScript, and relying on public documents, created its own implementation, "Jscript", which is recognized by Microsoft Internet Explorer.
Jscript 1.0 is roughly compatible with JavaScript 1.1, which is recognized by Netscape Navigator. However, later versions of JavaScript and specific differences between browsers platforms have started to give web developers enough problems. Netscape, Microsoft and other vendors have agreed to pass the language of international standardization organizations - ECMA, it finalized a specification language known as ECMAScript, recognized by all distributors. Although ECMA standard is useful, both Netscape and Microsoft have their own implementations of the language and continue to expand beyond the standard basic language.
Besides Jscript, Microsoft has introduced a competitor to JavaScript, called VBScript, designed to facilitate penetration of VB programmers on the web. VBScript is a subset of Visual Basic. However, JavaScript became known as the standard for web scripting language. It is generally considered that there are ten fundamental aspects of the JavaScript language that any programmer in the language should knows:
  1. JavaScript can be included in HTML - JavaScript code is usually hosted and executed inside HTML documents. Most JavaScript objects have HTML tags that represent, so the program is included on the client side. JavaScript uses HTML to get into the web application working.
  2. JavaScript is dependent on the environment - JavaScript is a scripting language; the software program which is actually running is the web browser (Firefox, Opera, Netscape Navigator, Internet Explorer, Safari, etc..) It is important to consider this dependence browser when you use aplicatiiJavaScript.
  3. JavaScript is an entirely interpreted language - the script code will be interpreted by the browser before being executed. JavaScript does not require compilation or preprocessing, but remains part of the HTML document.
  4. JavaScript is a flexible language - In JavaScript we can declare a variable of some kind of type, or we can work with a variable although we not know the specified type before running.
  5. JavaScript is based on objects - JavaScript is an object oriented programming language like Java, but more accurately, is "based on objects" JavaScript object model is based on the instance and not on inheritance.
  6. JavaScript is event driven - most of the JavaScript code responds to events generated by user or system. HTML objects, such as buttons, are enhanced to support event handlers.
  7. JavaScript is not Java - The two languages have been created by different companies, the reason of these similar name is just marketing.
  8. JavaScript is many-functionally - this language can be used in a variety of contexts to solve various problems: graphics, mathematical, and others.
  9. JavaScript is evolving - JS is an evolving language, a positive thing, but it can generate problems, the programmers need to always check what version to use for applications that can be available for a larger number of users of different browsers.
  10. .JavaScript covers diverse contexts - this programming language is directed mainly towards the client side, but we can use JavaScript on server side too. JavaScript is the language native to some web development tools like Macromedia Dreamweaver or IntraBuilder Borland.

This course teaches the basics of JavaScript and how to work with this language, as an initial course that is best suited for beginners in web programming, which wants to learn this scripting language.


Home

0

With HTML you can create your own Web site.
This tutorial teaches you everything about HTML.
HTML is easy to learn - You will enjoy it.

Examples in Each Chapter

This HTML tutorial contains hundreds of HTML examples.
With our online HTML editor, you can edit the HTML, and click on a button to view the result.

Example

_________________________________
|<!DOCTYPE html>
|<html>
|<body>
|
|<h1>My First Heading</h1>
|
|<p>My first paragraph.</p>
|
|</body>
|</html>
|_________________________________


Post navigation