Translate

Monday, 23 April 2012

JavaScript For...In Statement


JavaScript For...In Statement

The for...in statement loops through the properties of an object.

Syntax


for (variable in object)
  {
  code to be executed
  }

Note: The code in the body of the for...in loop is executed once for each property.

Example

Looping through the properties of an object:

Example

var person={fname:"John",lname:"Doe",age:25}; 
var x;

for (x in person)
{
document.write(person[x] + " ");
}

JavaScript Break and Continue Statements


The break Statement

The break statement will break the loop and continue executing the code that follows after the loop (if any).
Example
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
  {
  if (i==3)
    {
    break;
    }
  document.write("The number is " + i);
  document.write("<br />");
  }
</script>
</body>
</html>

The continue Statement

The continue statement will break the current loop and continue with the next value.
<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
  {
  if (i==3)
    {
    continue;
    }
  document.write("The number is " + i);
  document.write("<br />");
  }
</script>
</body>
</html>

JavaScript While Loop


In JavaScript, WHILE loop has same function as the FOR loop. The Syntax however is bit different. The WHILE Loop will check if a condition is being met, if yes then it will execute the code lines specified within the Brackets, else it will stop the looping process.
The counter variable must be incremented within the code lines to enable the while command to work properly. Unlike the FOR loop, the syntax does not provide a special spot for specifying the increment.
The initial value of the variable must also be specified before the While command.

Syntax

While(Condition)
{
code lines to be executed
}

Simple JavaScript While Loop Example

We will use the same example as used in the last lesson. Here we will achieve the same objective with While Loop instead of the FOR loop. It will help you easily compare both.
Create a mathematical table for the number 5, i.e. multiply it with numbers 1 to 10 and display results.

Js While Loop

Step 1- We declared a variable called 'a' and assigned it a value of 5.
Step 2- We declared a variable called counter and assigned it a value of 1. We called it counter because its value will change every time the loop is run.
Step 3- The condition- Until the condition in the following round brackets is true (counter <= 10), execute the code in the curly brackets below.
Step 4- We then print on the screen, the number 5, multiplication symbol x, the current value of the variable counter and the result of 5 multiplied with the current value of counter.
Step 5- After printing it will increment the value of variable counter and then go back to top of the loop command. Note that unlike the For Loop example in the last lesson, we enter the increment code within the code to be executed.
STEP 6- When the counter variable value becomes 11 and the loop goes back to top, the condition becomes FALSE as 11 is neither 10 nor less than it. So the loop will no longer be executed.
First time the code is executed, 5 x 1 and the result is a *5 which is five.
Now the next time code is executed, all values remain same but the value of the variable counter is incremented by 1 as we instructed in the for command- counter++ which is same as counter = counter+1. So the second time the loop runs, a * counter is 5 * 2 which results in 10.
While loop result

Example-

Make a JavaScript Program for creating/displaying mathematical tables of any number that user wants

Much similar to the example above. Just that here we will ask the user to enter a number through aPrompt PopUp box, whose mathematical table she wants. Instead of incrementing the value of counter variable by 1, we will do it by 2 in this example.
Instead of providing a value for a, here user will enter a value in the prompt box, which we will assign to a.

javascript while loop
Here we increment the value of the variable counter by 2. counter=counter + 2 means, the new value of counter is equal to the old value of counter + 2.
Once the value of counter becomes 11, it no longer meets the condition of < = 10. therefore the loop stops.

Result

A popup box will prompt the user to enter a number.
popup box JS for loops
table result for Javascript for loop

JavaScript For Loop

The JavaScript FOR loop is the simplest and most frequently used looping command. It simply executes a block of code until a certain condition is met. On every cycle/loop, it will first check if the specified condition is true, if yes then it will execute the block of code within the curly brackets.

Syntax

For (Counter variable name and initial value ; Condition ; Increment;)
{
code lines to be executed
}
Initial value of the counter variable- Starting value.
Condition- to keep looping until the condition is true OR in other words stop as soon as condition gets False.
Increment- How to increment the value of counter variable on every loop.

Simple JavaScript For Loop Example

Create a mathematical table for the number 5, i.e. multiply it with numbers 1 to 10 and display results.

javascript for loop example

Step 1- We declared a variable called 'a' and assigned it a value of 5.
Step 2- We declared a variable called counter and assigned it a value of 1. We called it counter because its value will change every time the loop is run.
Step 3- The condition- Until the condition in the following round brackets is true (counter <= 10), execute the code in the curly brackets below.
Step 4- We then print on the screen, the number 5, multiplication symbol x, the current value of the variable counter and the result of 5 multiplied with the current value of counter.
First time the code is executed, 5 x 1 and the result is a *5 which is five.
Now the next time code is executed, all values remain same but the value of the variable counter is incremented by 1 as we instructed in the for command- counter++ which is same as counter = counter+1. So the second time the loop runs, a * counter is 5 * 2 which results in 10.
for loop result

Example-

Make a JavaScript Program for creating/displaying mathematical tables of any number that user wants

Much similar to the example above. Just that here we will ask the user to enter a number through aPrompt PopUp box, whose mathematical table she wants. Instead of incrementing the value of counter variable by 1, we will do it by 2 in this example.
Instead of providing a value for a, here user will enter a value in the prompt box, which we will assign to a.
advance for loop

Here we increment the value of the variable counter by 2. counter=counter + 2 means, the new value of counter is equal to the old value of counter + 2.
Once the value of counter becomes 11, it no longer meets the condition of < = 10. therefore the loop stops.

Result

A popup box will prompt the user to enter a number.
popup box JS for loops
table result for Javascript for loop

JavaScript Loops


What is a loop or looping?

Looping is a technique in computer programming, through which a certain block of code can be executed(or looped) a number of times.
Programmer can :-
Method 1- Specify the exact number of times a loop should be executed
Method 2- Instruct the computer to keep executing the block of code over and over again (i.e. loop) till a certain condition is being met (i.e is TRUE). As soon as the condition gets False, the looping is stopped. JavaScript looping generally uses this method.

Uses of Loops

What is the need of loops? why do we need to repeat blocks of code? Loops are frequently used in the programming world. Specially when working with arrays(advance topic). The exact same code is not executed a no. of times, often one variable's value changes on each execution which is refered to as the counter variable. Like on one loop, its value is 1, on the next it is incremented by 1 and beomces 2, 3 on next and so on.
About its use in Arrays. Lets say we wish to display names and salaries of all the employees in a certain dept. The names of employees are stored in an array variable(which can hold multiple data items). Instead of writing invidual commands to display every employees names, we can create a loop to print all the values contained in an array.
Throughout this course we will use practical examples to dispaly how and where loops are necessary. In the next lesson on For Loops, we will start with a simple example of creating mathematical tables using loops.

Loop Commands used in JavaScript

  • JavaScript For Loop
  • JavaScript While Loop
  • JS For each Loop
  • JS Break Loop
We will cover these with practical examples in the coming lessons.

JavaScript Switch


It performs the same function as the else if statement in the last lesson. It basically deals with multiple scenarios and tests various conditions.
A condition in a switch statement is refered to as a CASE. If case is true-execute a block of code, if it is False see if any other case is true. If any other case is true, execute a block of code, repeat the process until find a true case / condition.
If none of the cases mentioned are true, will tell the browser what to do by using simply DEFAULT. default performs the same function as else.

JavaScript Else If statement


It tells the computer of actions to take in multiple possible scenarios (more than two). i.e. What to do if condition is true, if it is False see if any other condition is true. If another condition is true, execute a block of code, repeat the process until find a true condition.
If none of the conditions mentioned are true, will tell the browser what to do by using simply ELSE.

Else If statement SYNTAX

if (Condition)
{
Block of code to be executed, if condition is True
}
else if
{
Block of code to be executed, if condition is True
}
else if
{
Block of code to be executed, if condition is True
}
else
{
Block of code to be executed, if condition is True
}
If a condition is TRUE, the code is executed and the browser skips the ELSE part moves to the next line in the HTML document.
If the condition is FALSE, then it moves to see if any other condition is true and execute its code
If all conditions are False, the code in the else block is executed.

Example
We have a site for displaying semester results of students when they log in to the site.
Possible Scenarios
  • Passed
  • Failed
  • Absent
  • Any other problem due to which result could not be displayed.
if (status = passed)
{
"Congratulations, you have passed and been promoted to the next level "
}
else if (status = failed)
{
"Sorry. You failed the exam. Contact the administration department for further info"
}
else if (status = absent)
{
"Sorry. You did not appear in the exam. Contact the administration for the retake procedure"
}
else
{
"There was an unspecified error with your result. Contact the administration to sort it out and obtain your result"
}
NOTE: IF Else is genearlly used when there are two possible scenarios. Either condition can be TRUE and if it is FALSE there is only one alternate scenario. What if the person has not passed, but the alternate scenarios are either "Failed" or "Did not appear". To handle that we use IF ELSE .... IF ELSE which we will see in next lesson.


JavaScript Else statement


It tells the computer of actions to take in both the scenarios. i.e. What to do if condition is true and what to do if it is False. If a certain condition is true, execute a block of code, if false- execute another block of code mentioned.
IF Else is genearlly used when there are two possible scenarios. Either condition can be TRUE and if it is FALSE there is only one alternate scenario. Example below will clarify it, and also see the note below.

If statement SYNTAX

If (Condition)
{
Block of code to be executed, if condition is True
}
Else
{
Block of code to be executed, if condition is True
}
If the condition however is TRUE the code is executed and the browser skips the ELSE part moves to the next line in the HTML document.
If the condition is FALSE, then it executes the block of code in the ELSE part and then moves to the next lines in the html document.

Example
We have a site for displaying semester results of students when they log in to the site. What instructions to give to the student incase she has passed and what in other scenarios.
Possible Scenarios
  • Passed
  • Failed
If (status = passed)
{
"Congratulations, you have passed and been promoted to the next level "
}
Else
{
"Sorry. You could not pass the exam. Contact the administration department for further info"
}
NOTE: IF Else is genearlly used when there are two possible scenarios. Either condition can be TRUE and if it is FALSE there is only one alternate scenario. What if the person has not passed, but the alternate scenarios are either "Failed" or "Did not appear". To handle that we use ELSE Ifwhich we will see in next lesson.


JavaScript If statement

This statement is simply used to tell the computer 'What to do in case of a certain situation". If a certain condition is true, execute a block of code. By 'condition being TRUE' it is meant that the mentioned condition is being met.

if statement SYNTAX

if (Condition)
{
Block of code to be executed, if condition is True
}
LOWER CASE???
If the condition however is TRUE the code is executed and the browser moves to the next line in the HTML document.
If the condition is FALSE, then it simply moves to the next lines

Example
We looked at a simple example in the previous lesson. we will now write that example in JavaScript code.
If (gender = male)

JavaScript Conditional Statements

In programming, we often need to give computer the intelligence to take decisions in different situtations. If a certain condition is met, perform an action, if another condition is met perform the another specified operation. These are referred to as conditional statements-example below will clarify it.

Example
When customers come to our fashion website, they have to enter name and select Gender. Based on the Gender information receive, through programming we give computer the intelligence to decide whether to Greet the Visitor as Madam or Sir. 
Condition 1- Gender = Male
Condition 2- Gender = Female
How we program it into the computer
We tell the computer the list of Conditions and the actions to perform if a condition is met.
IF Gender is male , greet the visitor as 'Dear Sir. Welcome to the site'
IF Gender is female, greet the visitor as 'Dear Madam. Welcome to the site'
The thing is we cannot have a person sitting with a computer and everytime someone visits the site, the operator types in the Dear sir greeting or Dear madam greeting Programming lets us automate such operations. Computer decides and computer types the greeting.

Conditional statements used in JavaScript

We will be covering the following conditional statements used in JavaScript
  • If statement
  • If else statement
  • If else ... If else statements
  • Switch statement
We will look at each one of these in detail and with practical examples in the coming lessons.
Conditional Statements table. Differences

JavaScript Window and Page Events


OnError- When an error occurs in loading of page or elements within it.
Onload- When a page is loaded
OnUnload- When a user leaves or closes a page
OnAbort
OnBlur
OnScroll
OnFocus
OnMove
OnResize

JavaScript Form Validation and Field Events


OnSelect
OnSubmit
OnBlur
OnFocus
OnChange
OnReset

JavaScript Keyboard Events


JS keyboard events are those associated with some keyboard activity by user. The most commonly used are :-
  • OnKeydown Event -Event occurs, as soon as key is pressed. Like alphabet written in text box.
  • OnKeyup Event - Event occurs, just as the pressed key is released.
  • OnKeypress Event - A combination of Onkeydown and Onkeyup event handlers.
These event handler is used to instruct the browser on What action to take when a keyboard key is pressed or released. Generally used with text fields in forms.
As we studied in previos lessons, the events are commonly used in combination with functions.

Onkeydown and OnkeyUp Example

As you will write a letter in the text box below, a message will be displayed "User is currently typing". Then once you release the button, the text character will be converted to upper case.
only numbers allowed.

 

http://www.w3schools.com/jsref/event_onkeyup.asp
http://www.javascriptkit.com/jsref/eventkeyboardmouse.shtml

JavaScript OnClick Event

This event handler is used to instruct the browser on What action to take when a certain object is clicked.
If the concept of events is new to you, it is recommened that you first see lesson on What are Javascript events

Syntax

onclick="functionname( )"
The name of function that has to be called when this event occurs.
NOTE: Simple Js code can also be written here instead of calling function, but standard practice with events is to use them with functions.
Step 1- Declare the function
declare function
  • We declared a funciton in the head section of the page and named it 'welcome'.
  • No variables were required for this simple operation, so the ( ) are empty.
  • In the Curly Braces, we wrote instructions on what to do when the function is called by its name from anywhere in the page.
  • When the function is called, javascript should popup a 'Confirm Box' displaying a particular message.
Step 2- Call the Function
Call the function by its name where it is required.

js calling function
  • We created some form buttons within the body and associated a mouse OnClick event with them.
  • Whenever these buttons are clicked, browser will detect the event and run the function called 'welcome'.

JavaScript Mouse Events

JS Mouse events are those associated with some mouse activity by user. The programmer can tell the browser what to do when that event occurs.
Events are captured and subsequent actions defined using JavaScript Functions. If you do not have a concept of what functions are, it is recommended that you first take a look at lesson on JavaScript Functions - Click Here

JS OnMouseOver Event

The event occurs when mouse is pointer is moved over a certain object (to which the onmouseover command has been applied).
Example

S OnMouseOut Event


JS OnMouseDown Event


JS OnMouseUp Event


JS OnMouseMove Event



JavaScript Events


What is a Javascript Event?

An event is an action or a happening that browser can detect. For example a button placed on a webpage is clicked, some text is selected, pressing a keyboard button, mouse pointer is moved over to a picture. Whenever these and such other actions occur, Javascript code in the browser is able to detect the event and thus the proceeding action can be programmed- i.e. javascript programmer can tell the browser about what to do when a certain event occurs.
Generally events refer to some action by the user/visitor of the webpage however loading of a picture on a webpage or loading of a new webpage are also happenings that browsers recognize as events.
The actions to proceed the event are usually coded in the form of functions(will study them later in this course). A simple intro to a function is that it is a block of code lines that perform a specific task/function. A single function can be used on many pages throughout the site.

JS Events and Browser Compatibility issues


List of JavaScript Events

There are many types of javascript events. We will cover most of them in this course.
  1. JavaScript Mouse Events
    • OnMouseOver
    • OnMouseOut
    • OnMouseMove
    • OnMouseup
    • OnMousedown
  2. JavaScript Mouse Click Events
    • Onclick
    • Ondblclick
    • Oncontextmenu - (right click)
  3. JavaScript Keyboard Events
    • OnKeydown
    • OnKeypress
    • OnKeyup
  4. Form and Field Events
    • OnClick
    • OnSelect
    • OnSubmit
    • OnBlur
    • OnFocus
    • OnChange
    • OnReset
  5. Window Events
    • OnError- When an error occurs in loading of page or elements within it.
    • Onload- When a page is loaded
    • OnUnload- When a user leaves or closes a page
    • OnAbort
    • OnBlur
    • OnScroll
    • OnFocus
    • OnMove
    • OnResize
We will look at examples of each one of the frequently used events mentioned above in the coming lessons.
IMPORTANT NOTE: We have mentioned all the events generally used. However if you are a beginner, you might find all this information on JS events overwhelming. In that case, you can study only the most generally used events.

List of Most Frequently used JS Events

  • Onsubmit
  • Onclick
  • OnMouseOver

JavaScript Confirm box


JavaScript Confirm box

JavaScript Confirm is also a type of a popup box. It is used to ask user to confirm a certain requested action. If user confirms it, the browser proceeds and performs that action.
For example you ask the Browser to delete a picture from your facebook profile. A confirm box will pop up asking you to confirm the action "Are you sure to delete the file?", You can proceed by pressing OK Button or Cancel if you mistakently pressed the delete button or just changed your mind.

Syntax

confirm("message");

Example 1

In the example below, we are displaying a warning message to the user. If she chooses ok, she will be redirected to the main page, however she can also choose to click cancel.
We can later add more functionality to the script below using the If statement, to redirect those who click 'OK' to the site's main page, while do not load the page for those who choose to cancel. However since this lesson is part of Javascript basics, we only explain the basic use of confirm box here. We will deal with the IF part in later lessons on Conditional statements.
javascript confirm box
In the example above, we put a Button on a simple web page. Besides we defined a function in the head section of the page, and named it jsconfirm. This function will launch the confirm box whenever it is called.
We also programmed the button to call the function jsconfirm whenever the button is pressed(the button press event captured using Onclick event handler).

You can Copy Paste the code below into a new html file.

<html>
<head>
<title>JS Confirm Box</title>

<script type="text/javascript">
function jsconfirm()
{
confirm("Warning! The Content of this site may be disturbing to some viewers" + '\n' + "Viewer Discretion Is Advised");
}
</script>
</head>

<body>
<p>Click Here to Enter the site</p>

<input type="button" onclick="jsconfirm()" value="Enter Site" />
</body>
</html>

Result

When the button is pressed, the popup box will appear.
js confirm
NOTE: After you press ok, nothing will happen, because as mentioned above, in this example we are not telling the browser about what to do with the input taken.

PopUp Box Message Line Break '\n'

If the message is too lengthy, it will be put into the next line, however we can also enter a line break '\n' to manually enter a line break in the popup window message as in the example above.

JavaScript Confirm and the Boolean Values (Advance topic)

This part of the lesson explains a slightly advanced topic and also makes use of the conditional statements. If you are taking this course step by step from the beginning, you can skip this part and maybe later refer to it after we have covered the conditional statements.
In JavaScript a confirm OK pressed is equal to a boolean 1 or 'TRUE' and a confirm Cancel is equal to a boolean 'False'.

Example

In the example below, we will use the Confirm command as a condition in a Conditional statement. So if OK is pressed it will mean that the condition has been met OR is true.
js confirm code
We did not mention any event with the confirm command, so the confirm box will pop up with page load.
Javascript confirm conditional
If the condition is true, i.e. OK has been pressed in the confirm popup box, it will execute the command in the brackets. It will pop up an alert
js confirm boolean true
If the condition is False, i.e. Cancel has been pressed in the confirm popup box, it will execute the command in the brackets after the ELSE. It will pop up a different alert as specified in the code.
js confirm boolean false


JavaScript Prompt box /Window

JavaScript Prompt is also a type of a popup box. It is used to ask(prompt) user for certain input, which then javascript uses for certain operations and decision making. For example, ask visitor to enter age, before he can be allowed to enter a site which is restricted for those under 13.

Syntax

prompt ("message", "default value");

Example 1

In the example below, we are prompting the visitor to enter her age.
We can later add more functionality to the script below using the If statement, to redirect those above 13 to the site's main page, while deny entrance to those under 13. However since this lesson is part of Javascript basics, we only explain the use of the prompt box to take input, what we later do with that input, is a part of later lessons.
js prompt
In the example above, we put a Button on a simple web page. Besides we defined a function in the head section of the page, and named it jsprompt. This function will launch the JS Prompt box whenever it is called.
We also programmed the button to call the function jsprompt whenever the button is pressed(the button press event captured using Onclick event handler).

You can Copy Paste the code below into a new html file.

<html>
<head>
<title>JS PopUp Boxes</title>
<script type="text/javascript">

function js_alert()
{
alert("This is your first alert box");
}

</script>
</head>

<body>
<p>Clicking the Button below will launch an alert box.</p>

<input type="button" onclick="js_alert()" value="Launch Alert Box" />

</body>
</html>

Result

When the button is pressed, the popup box will appear. Here we chose the click button event to launch the box, we can also program to launch the prompt box on any other event, like simple page load.
javascript prompt window
NOTE: After you press ok, nothing will happen, because as mentioned above, in this example we are not telling the browser about what to do with the input taken.

Example 2- Making use of the input value

In this example, we will use a simple code to work with the input taken.
prompt user
1. We defined a function called jsprompt2. This function not only makes use of the prompt command to ask for input, but will also assign the input value to a variable called visitorname.
2. Then the function will display the customized welcome message on the screen with the value of the variable we named visitorname(the value user entered in the prompt).
3. We placed a button on the page and programmed it to call the function jsprompt whenever the button is pressed(the button press event captured using onclick).

Result


When Ok is pressed.
prompt result
NOTE: In this example, we also mentioned a default Value for the prompt box input, so when the box pops up, by default the value 'Visitor' is already there. User can click in the box and enter her own name however.

You can Copy Paste the code below into a new html file.

<html>
<head>
<title>JS Prompt Box</title>
<script type="text/javascript">
function jsprompt2()
{
var visitorname = prompt("Please Enter your Name","visitor");
document.write("Hi " + visitorname + " Welcome to our Company Website");
}
</script>
</head>
<body>
<p>Plz Click the Button and enter your name</p>
<input type="button" onclick="jsprompt2()" value="Enter Name" />
</body>
</html>
Example 3- Another example of the JavaScript PopUp box making use of Loops is presented at a later lesson at- JavaScript For Loops

JavaScript Alerts PopUp Box


Alert is a way of passing on some information to the page user/visitor OR simply it alerts the user about a certain event. Event like Page load, button click, form submit, clicked inside a field etc. See JavaScript Events for more.
The Alert command launches a PopUp box containing some text message for the visitor. The user is required to acknowledge the receipt of information usually by pressing a 'OK' button that appears in the box.

Syntax

Alert ("message");
Example
javascript alert box
In the example above, we put a Button on a simple web page. Besides we defined a function in the head section of the page, and named it js_alert. This function will launch the alert box whenever it is called.
We also programmed the button to call the function js_alert whenever the button is pressed(the button press event captured using Onclick event handler).

You can Copy Paste the code below into a new html file.

<html>
<head>
<title>JS PopUp Boxes</title>
<script type="text/javascript">

function js_alert()
{
alert("This is your first alert box");
}

</script>
</head>

<body>
<p>Clicking the Button below will launch an alert box.</p>

<input type="button" onclick="js_alert()" value="Launch Alert Box" />

</body>
</html>

Result

alert box in chrome
Note that the alert box appears as a separate small size window in Chrome browser.

JavaScript PopUp Boxes / Windows


JavaScript PopUp Boxes / Windows

What is a PopUp Box/ window?

A PopUp box is a small message box window that appears(pops up) in your browser in response to a certain Event like Page load, button click, form submit, clicked inside a field etc. See JavaScript Eventsfor more.The main types of Javascript popup boxes
  • Alert Box- Give some info to user
  • Prompt Box - Ask user to input some value like name, age etc.
  • Confirm Box- Confirm before proceeding with a request ex- delete a file.
Popup boxes appear differently in different browsers.

PopUp Box as it appears in FireFox

In Mozilla Firefox 5.0, the JavaScript Popup box appears in the center of page. But unlike IE and Chrome, the box does not appear as a separate movable window. you cannot click and drag it across the screen.
JS popup box firefox

JS PopUp Box Appears in Internet Explorer 8

You can click and hold down the mouse key as shown in the screenshot below and drag the popup window across the screen.
javascript popus in internet explorer
Note the Yellow symbol, that is an IE 8 symbol for Alerts.

JavaScript PopUp Box / Window Appears in Google Chrome

alert box in chrome

PopUp Boxes Sytntax

We will deal with practical examples of popup windows in the next lesson, however the general syntax is
command name ("text message");

PopUp Box Message Line Break

If the message is too lengthy, it will be put into the next line, however we can also enter a line break '\n' to manually enter a line break in the popup window message. Example in Lesson on JS Confirm box

JavaScript Document.Write Command


Document.write is one of the very basic commands in JavaScript. It is used to display some text or values of variables on the screen.

Why Use document.write? Can't we achieve same objective with HTML tags?

HTML text written in <p> tags will always display the text on the screen. JavaScript is dynamic and often needs to make decisions and display messages according to the options selected.For example if the user who submitted a form on our website is a female, so on the next page(confirmation page) JavaScript will display "Thankyou Madam for contacting us, we will get back to you shortly" and a different message if the user was a male "Thank you Sir for contacting us, we will get back to you shortly".

So there needs to be a text displaying command that can go within the javascript code i.e. within <script> </script>tags. That requirement can be fulfilled by a JavaScript specific command and not simple html. Besides simple html cannot output/display the values of variables or compute values of mathematical expressions. That is why document.write command is used.

Syntax

document.write ("text or variable name");

Example 1 - Simple text display and computing Mathematical expressions.

javascript document.write
1. In the first code we will display a simple text message on screen.
2. In the second code part, we declared and assigned values to two variables 'a' and 'b' and using the document.write command, put them in a mathematical expression(a+b) to calculate and display the sum of the two variables.
Result
Load the page in browser to see result.
js display text result

Example 2- Document.write using Variable names and Text Concatenation

In this example we will concatenate(join) some text and a variable name to display them in the browser screen.
document write concatenation
We declared a variable, named it nm and assigned it a value "Julie".
We mentioned the variable name in the document.write command. Instead of the variable name, it will display/print the value of the variable on screen.
javascript write command

Example 3- JavaScript document.write - Using HTML tags within JavaScript

We can also include html tags within the quotes " " in the javascript document.write command to modify text formatting(how text is displaye)
HTML tags within javascript
The text 'My name is' will be made italic, while the value of variable will be displayed in bold. The proceeding tag is enclosed within <h3> tags so will be displayed in a new paragraph.

Result

html in JS  writeln- new line after every print

Writing a Simple Program/code in JavaScript


In the previous chapters on JavaScript Basics, we studied how to insert JS code into html documents. We also mentioned that for the purpose of this course we will be using the Free code Editing software Called Komodo Edit.
So now lets start and write our first simple code.

Example 1

In the example below we will first display some text on the screen using Simple Html code. Then display the same text again using JavaScript command document.write.
first javascript code

RESULT (Page Viewed in Browser)

javascript code result

Example 2- Same Functionality but JavaScript Code in External File

STEP 1- In this example we will place the Javascript code in an external .JS file and link the html document to that.
STEP 2- The element to which we wish to apply some part of JS code(ex. function) from the External File, will be assigned a unique identifying name called 'ID'. In this case that is the paragraph tag. An ID is a unique identifier of an element.
JS External Script

STEP 3- Define a Function in the external .JS Extension Filejavascript external file


Above Code parts explained one by one.
window.onload- window onload is the event handler for page load
displaytext is the name of the function(you can assign name of your choice) that Javascript will execute when the page load event occurs. the function is defined below in the code.
Braces- under the brackets {} will come the code that will be executed when function is called.

document.getElementById("extmsg").innerhtml-
document. Look into the current document,
.getElementById. In the document go to the element with the given id name(in this case the <p> tag was given that id name)
InnerHTML , innerhtml changes the html code withing that selected element to the code written after the'=' sign.

RESULT (Page Viewed in Browser)

js result

Confusion- Html is also Displaying the Text, then why Use JavaScript?

Using programming we can automate the writing of the text and make it dynamic. That is browser can decide which text to write and under what circumstances to hide or display it. This type of decision making is not possible using simple HTML.
Its use will get clearer as we move on to writing more complex codes.


NoScript Tag


Sometimes websites receive visitors whose browsers either do not support JavaScript or JavaScript is disabled in their browsers. In such cases, Noscript tag is used to display an error message to the visitors, that the site requires JavaScript to display all the contents properly.
NOTE: The noscript tag needs to be placed outside the <script> </script> tags as anything between them will be considered javascript and thus javascript disabled browser will not display the Error Message/Note withing the noscript tags.

SYNTAX

<noscript>
Message
</noscript>


Example

JavaScript NoScript tag

You can Copy Paste the code below into a new htm file code view.

<html>
<head>
<title> JavaScript Noscript tags</title>
</head>

<body>

<noscript>
<h3> All the contents of the page cannot be properly displayed because your browser does not support JavaScript </h3>
<h4>This could be because 1. Javascript is disabled in your browser. How to enable Javascript? Click Here </h4>
<h4>Cause 2- Your Browser is quite old and does not support JavaScript. We recommend Downloading Mozilla Firefox. To Download Firefox. Click Here</h4>
</noscript>
<p>
<script type="text/javascript">
document.write("Welcome to my first page. This text is being displayed using JavaScript");
</script>
</p>
</body>
</html>

Test The code- Disable JavaScript

To test this code, you first need to turn off JavaScript in your Browser, otherwise normal JavaScript code will be executed and this noscript message will not be dispalyed.
To disable javascript in Mozilla Firefox, go to options > Content tab and remove the check from Enable Javascript.

disable javascript firefox

Result

Now View the page in a browser and the noscript message will be displayed.



prev<<JavaScript Comments
Back to index of javascript
part2-->Writing your First JavaScript Code

JavaScript Comments

It is good programming practice to write comments with your blocks of code. Comments are simply notes to self, describing certain blocks of code- what is it that you have attempted to do with certain lines of code, how that fits into the whole document and any other explanations. Comments are ignored and not executed by browsers.

Giving headings to various parts of code using comments, makes looking at hundreds of lines less complicated. The comments are also useful if later on some other programmer works on your document, she can understand your document more easily if blocks of codes are explained or headings are used in comments.
You might recall that comments were also used in html. However they are much more needed in Javascript and other programming languages.

Javascript Single line comments

SYNTAX
//comments
Example
javascript single line comments

Javascript Multi line comments

SYNTAX
/*
comments
comments
*/
javascript multi line comments
NOTE: Observe that the comments part does not appear in the browser when page is loaded.


Javascript comments to temporary disable part of code

Javascript comments are also used to temporary disable some part of code in the whole document. If we wish to remove the code for some time, instead of deleting it we can comment it out, and later when wish to restore that functionality on the website, can just remove the comments /*.
/*
document.write("<p>This is an<strong> example</strong></p>");
*/
the above lines of code will not be executed now.

Javascript Data Types



Data is of various types and is processed by javascript differently. For example it can be numeric, text etc. Mathematical operations like addition, subtraction can only be performed on data that is numeric in nature.
Variable data type cannot be specified in javascript.
It is different from variable type in the sense that a variable type can have various sub data types. Like numeric data can have data types integers, floating points and many others in various programming languages. ???? like short and long integers in other programming languages or that is also variable sub types?
Similarly every data type has some properties and only some specific operations can be performed on a type.

Strongly and Loose / Dynamic Typed languages

In some languages, while defining a variable or generally dealing with data we have to mention its data type. Such languages are also know as 'Strongly typed languages'.
Javascript losely typed language in the sense that dont have to specify data type. Javascript guesses on its own based on the type of actions the user is trying to perform. However it is not accurate all the time, and there are situations where we need to tell it, how to handle data.
Numerical Data
  1. Integers or whole numbers- Can be in positive or negative. Ex. 54, 211230, -4, -342
  2. Floating Point Numbers or Decimal numbers. Ex 99.5, 0.3, 2132.98
Back to index of javascript

Javascript Logical Operators


List of Logical Operators

OperatorOperator nameExample
&&ANDCONDITION : if x > 5 AND x < 20 ; True (both conditions met)
  • x = 10 . TRUE as both conditions true
  • x =25 . False as only one condition true ( x is greater than 5, but not less than 20)
||ORCONDITION : if x > 5 OR x < 20 ; True (both conditions met)
  • x = 10 . TRUE as x is greater than 5
  • x =25 . still TRUE as only one condition needs to be true ( x is greater than 5)
!NOTSCENARIO- Access to company financial data is allowed to all levels of employees except level 1 employees.
if level != 1 then Allow access
(for simple explanation, command not in javascript syntax. examples to come in later lessons)
So if the level of employee is anything but 1, she will be granted access.
level = 1 FALSE (condition not met, disallow access)
level = 3 TRUE (condition met, allow access)


Examples of How Logical Operators are practically used.

Specifying multiple conditions using AND operator.

Entry to a teenager only web portral is allowed for only ages 13 to 19. If we give condition greater than 13, then those with ages 25, 40 and 50 will also be able to enter. similarly if a single condition like less than 19, then ages 5, 6 and others will also qualify as that is less than 19. In many situations we need to specify multiple conditions, then we use the logical operators.
condition
if age > 13 and age < 19 Let the user enter.
When using the AND operator, both the conditions MUST be true. If any one is not met, then the result is false.

Specifying multiple conditions using OR operator.

As opposed to the AND operator, using OR either of the condition has to be true. If one of the two is true, the result will be true.
using the above example of teenagers' website.
Condition
if age < 13 OR age > 19 Notify user that she is not permitted to enter the site.
Either if the age of the visitor is less than 13 or is greater than 19. One of the conditions has to be met to execute the no entry notification.

Javascript Comparison Operators


The comparison operators are used in Javascript to compare values of variables. That means to check if two variables are equal, greater or less than other and some other functions.

List of Comparison Operators

OperatorOperator nameExamples
==Equal (note single = sign is used for assignment, not for comparison)
  • x = 9;
  • if x == 9 (comparison result is true)
  • if x == 18 (This comparison result is false)
!=Not equal to
  • x = 9;
  • if x != 9 (comparison result is false)
  • if x != 18 (This comparison result is True)
===Strict Equal to (not only should match value but also variable type)x = 50;
y = "50";
  • if x == y (comparison result is true as value is same)
  • if x === y ( comparison result is false as although value is same, one variable is numeric type while the other 'y' is string type)
    For details See Lesson on - Javascript variable types
<Less than
  • x = 9;
  • if x < 10 (comparison result is true)
  • if x < 6 (This comparison result is false)
>Greater than
  • x = 9;
  • if x > 10 (comparison result is false)
  • if x > 6 (This comparison result is true)
<=Less than or equal to
  • x = 9;
  • if x <= 10 (comparison result is true)
  • if x <= 9 (This comparison result is also true) Either has to be true, smaller than or equal to. Although x is not less than 9, but it is equal to 9. therefore it is true.
>=Greater than or equal to
  • x = 9;
  • if x >= 10 (comparison result is false)
  • if x >= 6 (This comparison result is true) Either has to be true, greater than or equal to.


Examples of How Comparison operators are practically used.

In the example below, we will enter marks obtained by multiplestudents in the final exams (out of 1000 total marks) and at the backend, javascript code will compare the marks and list the highest marks(largest number) obtained along with the name of the student.
Peter's Final Exam Marks : 

Julie's Final Exam Marks : 

Joey's Final Exam Marks : 

Dont worry now about how the code is working, we will look at that in the later lessons once we get familiar with more basic code writing. If you however wish to see the explanation for the code used in the above example, click here. (expand)