





































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!






































JavaScript is the scripting language of the Web. JavaScript is used in millions of Web pages to add functionality, validate forms, detect browsers, and much more.
JavaScript is used in millions of Web pages to improve the design, validate forms, detect browsers, create cookies, and much more. JavaScript is the most popular scripting language on the Internet, and works in all major browsers, such as Internet Explorer, Mozilla Firefox, and Opera.
JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language A scripting language is a lightweight programming language JavaScript is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scripts execute without preliminary compilation) Everyone can use JavaScript without purchasing a license Java and JavaScript are two completely different languages in both concept and design! Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in the same category as C and C++.
JavaScript gives HTML designers a programming tool - HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages JavaScript can put dynamic text into an HTML page - A JavaScript statement like this: document.write("" + name + "") can write a variable text into an HTML page JavaScript can react to events - A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element JavaScript can read and write HTML elements - A JavaScript can read and change the content of an HTML element JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser
JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on the visitor's computer.
Variables are "containers" for storing information. JavaScript variables are used to hold values or expressions. A variable can have a short name, like x, or a more descriptive name, like carname. Rules for JavaScript variable names: Variable names are case sensitive (y and Y are two different variables) Variable names must begin with a letter or the underscore character Note: Because JavaScript is case-sensitive, variable names are case-sensitive. Example A variable's value can change during the execution of a script. You can refer to a variable by its name to display or change its value.
The script above declares a variable, assigns a value to it, displays the value, change the value, and displays the value again.
Output : Welcome XYZ The script above declares a variable, assigns a value to it, displays the value, change the value, and displays the value again.
After the execution of the statements above, the variable x will still have the value of 5. The value of x is not reset (or cleared) when you redeclare it.
Numbers - are values that can be processed and calculated. You don't enclose them in quotation marks. The numbers can be either positive or negative. Strings - are a series of letters and numbers enclosed in quotation marks. JavaScript uses the string literally; it doesn't process it. You'll use strings for text you want displayed or values you want passed along. Boolean (true/false) - lets you evaluate whether a condition meets or does not meet specified criteria. Null - is an empty value. null is not the same as 0 -- 0 is a real, calculable number, whereas null is the absence of any value. Data Types TYPE EXAMPLE Numbers Any number, such as 17, 21, or 54e Strings "Greetings!" or "Fun" Boolean Either true or false Null A special keyword for exactly that – the null value (that is, nothing)
As with algebra, you can do arithmetic operations with JavaScript variables: y=x-5; z=y+5;
The operator = is used to assign values. The operator + is used to add values. The assignment operator = is used to assign values to JavaScript variables. The arithmetic operator + is used to add values together. y=5; z=2; x=y+z;
After the execution of the statements above, the variable txt3 contains "What a verynice day". To add a space between the two strings, insert a space into one of the strings: txt1="What a very "; txt2="nice day"; txt3=txt1+txt2; or insert a space into the expression: txt1="What a very"; txt2="nice day"; txt3=txt1+" "+txt2; After the execution of the statements above, the variable txt3 contains: "What a very nice day" Adding Strings and Numbers Look at these examples: x=5+5; document.write(x); x="5"+"5"; document.write(x); x=5+"5"; document.write(x); x="5"+5; document.write(x); The rule is: If you add a number and a string, the result will be a string. JavaScript Comparison and Logical Operators Comparison and Logical operators are used to test for true or false.
Comparison Operators Comparison operators are used in logical statements to determine equality or difference between variables or values. Given that x=5, the table below explains the comparison operators: Operator Description Example == is equal to x==8 is false === is exactly equal to (value and type) x===5 is true x==="5" is false != is not equal x!=8 is true > is greater than x>8 is false < is less than x<8 is true >= is greater than or equal to x>=8 is false <= is less than or equal to x<=8 is true How Can it be Used Comparison operators can be used in conditional statements to compare values and take action depending on the result: if (age<18) document.write("Too young"); You will learn more about the use of conditional statements in the next chapter of this tutorial. Logical Operators Logical operators are used to determine the logic between variables or values. Given that x=6 and y=3, the table below explains the logical operators: Operator Description Example && and (x < 10 && y > 1) is true || or (x==5 || y==5) is false ! not !(x==y) is true Conditional Operator JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.
if (time<10) { document.write("Good morning"); }
Example 2
Note: When comparing variables you must always use two equals signs next to each other (==)! Notice that there is no ..else.. in this syntax. You just tell the code to execute some code only if the specified condition is true. If...else Statement If you want to execute some code if a condition is true and another code if the condition is not true, use the if....else statement. Syntax if ( condition ) { code to be executed if condition is true } else { code to be executed if condition is not true } Example
var time = d.getHours(); if (time < 10) { document.write("Good morning!"); } else { document.write("Good day!"); }
If...else if...else Statement You should use the if....else if...else statement if you want to select one of many sets of lines to execute. Syntax if ( condition1 ) { code to be executed if condition1 is true } else if ( condition2 ) { code to be executed if condition2 is true } else { code to be executed if condition1 and condition2 are not true } Example
break; default: document.write("I'm looking forward to this weekend!"); }
Loops in JavaScript are used to execute the same block of code a specified number of times or while a specified condition is true. JavaScript Loops Very often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this. In JavaScript there are two different kind of loops: for - loops through a block of code a specified number of times while - loops through a block of code while a specified condition is true The for Loop The for loop is used when you know in advance how many times the script should run. Syntax for (var=startvalue;var<=endvalue;var=var+increment) { code to be executed } Example Explanation: The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs. Note: The increment parameter could also be negative, and the <= could be any comparing statement.
document.write("The number is " + i); document.write(""); }
Result The number is 0 The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 The number is 6 The number is 7 The number is 8 The number is 9 The number is 10 JavaScript While Loop Loops in JavaScript are used to execute the same block of code a specified number of times or while a specified condition is true. The while loop The while loop is used when you want the loop to execute and continue executing while the specified condition is true. while (var<=endvalue) { code to be executed } Note: The <= could be any comparing statement. Example Explanation: The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs.
var i=0; do { document.write("The number is " + i); document.write(""); i=i+1; } while (i<0);
Result The number is 0
There are two special statements that can be used inside loops: break and continue. JavaScript break and continue Statements There are two special statements that can be used inside loops: break and continue. Break The break command will break the loop and continue executing the code that follows after the loop (if any). Example
Result The number is 0 The number is 1 The number is 2 Continue The continue command will break the current loop and continue with the next value. Example
Result The number is 0 The number is 1 The number is 2 The number is 4 The number is 5 The number is 6 The number is 7 The number is 8 The number is 9 The number is 10
You will learn more about JavaScript events in the JS Events chapter. How to Define a Function The syntax for creating a function is: function functionname ( var1,var2,...,varX ) { some code } var1, var2, etc are variables or values passed into the function. The { and the } defines the start and end of the function. Note: A function with no parameters must include the parentheses () after the function name: function functionname () { some code } Note: Do not forget about the importance of capitals in JavaScript! The word function must be written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a function with the exact same capitals as in the function name. The return Statement The return statement is used to specify the value that is returned from the function. So, functions that are going to return a value must use the return statement. Example The function below should return the product of two numbers (a and b): function prod(a,b) { x=a*b; return x; } When you call the function above, you must pass along two parameters: product=prod(2,3);
The returned value from the prod() function is 6, and it will be stored in the variable called product. The Lifetime of JavaScript Variables When you declare a variable within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared. If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed.
Event Handlers Event Handlers are JavaScript methods, i.e. functions of objects, that allow us as JavaScript programmers to control what happens when events occur. Directly or indirectly, an Event is always the result of something a user does. For example, we've already seen Event Handlers like onClick and onMouseOver that respond to mouse actions. Another type of Event, an internal change-of-state to the page (completion of loading or leaving the page). An onLoad Event can be considered an indirect result of a user action. Although we often refer to Events and Event Handlers interchangeably, it's important to keep in mind the distinction between them. An Event is merely something that happens - something that it is initiated by an Event Handler (onClick, onMouseOver, etc...). The elements on a page which can trigger events are known as "targets" or "target elements," and we can easily understand how a button which triggers a Click event is a target element for this event. Typically, events are defined through the use of Event Handlers, which are bits of script that tell the browser what to do when a particular event occurs at a particular target. These Event Handlers are commonly written as attributes of the target element's HTML tag. The Event Handler for a Click event at a form field button element is quite simple to understand:
The event_handler_code portion of this example is any valid JavaScript and it will be executed when the specified event is triggered at this target element. This particular topic will be continued in Incorporating JavaScripts into your HTML pages. There are "three different ways" that Event Handlers can be used to trigger Events or Functions. Method 1 (Link Events):