JavaScript Fundmentals

General Notes, Basic syntax, Functions, Form Validation, Debugging Skills

General Notes on JavaScript

Basic Syntax

The following introduces basic syntax of javaScript language, namely, codeiables, operators and control structures.

JavaScript Variables

  • Variable names are case sensitive
  • Variables must be begin with a letter or the underscore character
  • You do not specify a type when the variable is declared
  • Variables are usually declared with var and sometimes with let. Sometimes they are not declared, but simply used. These affect scope.
  • Variable Scope:
    • Global Scope Variables:
      • All variables declared outside a function are global.
      • If you do not use var or let before assigning to a variable, you are declaring a global scope variable.
    • Function Scope Variables:
      • All variables declared inside a function with var, no matter how deeply nested, are function scope variables and are available at all nesting depths within the function
      • Redeclaring a variable inside a block with var will redeclare it outside the block too and the old value will be lost.
      • Function parameters are function scope and do not need var.
    • Block Scope Variables:
      • These are new in the 2015 standard.
      • If you declare a variable with let, it has block scope and will no longer be available when the {} block it is declared in ends.
      • A let declared with a for loop belongs to the for loop's block and is out of scope when the loop is over.
    • More on the discussion of local versus global
    • More on the discussion of block versus local and global
  • Example declarations are:
    var myInt=20;	//integer
    var myString="hello there"; //string
    var stringQuote='the "string"'; //string
    stringQuote='Tom\'s house';
    sum=myInt + 2;

    // OR you can define in one line:
    var myInt=20, myString="hello there", stringQuote='the "string"';

JavaScript Operators

  • Using "=" to assign values.
  • Basic arithmetic operators.
    x=y+2; // Addition
    x=y-2; // Subtraction
    x=y*2; // Multiplication
    x=y/2; // Division
    x=y%2; // Modulus (division remainder)
    x=++y; // Increment, or x=y++;
    x=--y; // Decrement, or x=y--;
  • Using "+" to concatnate strings or add text values.
    var first_name = "Steve";
    var last_name = "Jobs";
    var name = first_name + " " + last_name; 
    //the person's name is "Steve Jobs"
    var hello = "Hello" + 7; 
    //the value of hello is "Hello7"
  • Comparison operators.
    var x = 5;
    x==8;    //is equal to, return false
    x==5;    //return true
    x==="5"; //is exactly equal to (value and type), return false
    x!=8;    //is not equal, return true
    x!=="5"; //is not equal (neither value or type), return true
    x>8;  //is greater than, return false
    x<8;  //is less than, return true
    x>=8; //is greater than or equal to, return false
    x<=8; //is less than or equal to, return true
  • Logical operators.
    var x = 6, y=3;
    (x < 10 && y > 1) is true // and
    (x==5 || y==5) is false // or
    !(x==y) is true // not
  • Note: an empty string, "", is not null
    var car="";
    //if car is null or car is an empty string
    car==null || car=="" // false || true, return true
    //if car is not null and car is not an empty string
    car!=null || car!="" //true || false, return true, wrong condition.
    car!=null && car!="" //true && false, return false, correct condition.

Control Structures

  • The if ... else statement.
    var time=new Date().getHours();
    if (time<10){
      x="Good morning";
    else if (time<20){
      x="Good day";
      x="Good evening";
  • The for loop.
    for (i=0;i<10;i++){
      if (i==3){
      x=x + "The number is " + i + "<br />";
  • The while and do-while loop.
    while (i<5){
      x=x + "The number is " + i + "
    "; i++; } // or use the do-while loop do{ x=x + "The number is " + i + "
    "; i++; } while (i<5);

JavaScript Functions

The following introduces javascript function related topics, including, definition of functions, javascript events and popup boxes.


  • Usually, JavaScript functions are defined in the <head> part of the HTML page.
  • The key word function is used to declare a function. The keyword should be written in lower case.
  • The following shows an example function that invoke a Alert Box:
    <!DOCTYPE html>
    <script type="text/javascript">
        	function AFunction()
    		 alert("<p>Hello CS215!</p>");
    	<button onclick="AFunction()">Try it</button>
  • A function with arguments:
    <!DOCTYPE html>
    <script type="text/javascript">
    function myFunction(name,job)
    alert("Welcome " + name + ", the " + job);
    <button onclick= "myFunction('Harry Potter','Wizard') ">Click for Harry Potter</button>
    <button onclick= "myFunction('Bob','Builder') ">Click for Bob</button>
  • Function with a return value:
    <!DOCTYPE html>
    <script type="text/javascript">
      		function myFunction(){
      			return "Hello World";
    <button onclick= "alert(myFunction()) ">Click for Harry Potter</button>


Events are things that the user does (or things that happen to the page) that can trigger JavaScript to do something. In JavaScript you write event handler functions to respond to events and assign them to the event. For instance, if the user clicks on a button, an onclick event is generated, and the assigned handler function will soon take note of the event and will do what it was assigned to do. The following provides a list of some of typical HTML events you can write handlers for. For a more comprehensive list see

  • onclick
  • onload
  • onunload
  • onmouseover
  • onmouseout
  • onfocus
  • onblur
  • onchange

You will sometimes see code like the following.
<input type="button" value="open" onclick="winmsg()" />
When you click on the "open" button, the winmsg() function will be called.

Popup Boxes

Popup Boxes Firefox Display and Returns Code
Alert Box alert box alert("Alert Message")
Confirm Box confirmBox3 confirm("Confirm Something")
Prompt Box promptbox3 prompt("Ask for Input", "default")

Form Validation

We usually do the client-side validation before sending the content (user inputs) to the server. That is, a JavaScript function will be called for form validation when clicking the "submit" button. Following are examples mainly taken from W3Schools website.

Validating Text Input

The function below checks if a field has been left empty. If the field is blank, an alert box appeatrs with a message, the function returns false, and the form will not be submitted:

function validateForm(){
	var x=document.forms.myForm.fname.value;
	if (x==null || x==""){
  		alert("First name must be filled out");
  		return false;

The HTML code is as follow:

	<form name="myForm" action="" onsubmit="return validateForm()" 
	First name: <input type="text" name="fname">
	<input type="submit" value="Submit">

Validating Radio Button Input

The HTML code:

<input type ="radio" name= "gender" value="Female"/>Female
<input type ="radio" name= "gender" value="Male"/>Male

The JS code for validation radio button:

  var  gender = document.forms.myForm.gender;
  var  gen_val = "";

  for (var i=0; i < gender.length;i++)
    if (gender[i].checked){
    empty += " * Gender\n";
    warn += " * select a gender \n";
    rt= false;
    str_user_inputs +="Gender: "+gen_val+"\n";

Validating Drop-Down List

There are multiple solutions to validate a Drop-Down List. The following provides one solution from

Using selectedIndex Attribute

The JS code:

  var dplst_e = document.forms.myForm.nationality;

  var s_index = dplst_e.selectedIndex;

  // Comparison value 
    empty += " * Nationality \n";             
    warn += " * select a nationality \n";
    rt = false;

    //  Obtain the value of the selected option
    var strUser = dplst_e.options[s_index].value;

    str_user_inputs +="Nationality: "+strUser+"\n";

Validating Checkbox Input

An example to validate the Checkbox (Radio Button):

The HTML code:

	<form name="myForm"  onsubmit="return validateForm()" 
	First name: <input type="text" name="fname">
	Medical History: <input type="checkbox" name="med_chk" value="smallpox" >Smallpox
	<input type="checkbox" name="med_chk" value="mumps" >Mumps
	<input type="checkbox" name="med_chk" value="dizziness" >Dizziness
	<input type="checkbox" name="med_chk" value="sneezing" >Sneezing
	<input type="submit" value="Submit">

The JS code for validation:

  var med = document.forms.myForm.med_chk;

  //validate checkbox 

  for (var i=0;i < med.length;i++){
    if (med[i].checked){
   empty += " * Medical History \n";
   warn += " * Please select N/A if you have no Medical History to report \n";
   rt = false;

  else {//if pass validation, then collect user choices

   str_user_inputs +="Medical History: ";
   for (var j=0; j<med.length; j++){
	if (med[j].checked){
		str_user_inputs +=med[j].value+" ";

   str_user_inputs +="\n";

Basic JavaScript Debugging Skills

Following content comes from JavaScript Debugging for Beginners

"Development environments are usually nice enough to give programmers a bunch of tools to help determine where their program's going wrong. But with JavaScript, your development environment is a web browser, and things aren't quite so hospitable.". The debugging of JavaScript is especially difficult because:

To make your code easier to debug:

There are several ways to locate JavaScript errors:

  1. Comment out pieces of your code that you think might be producing the error.
  2. Use a log() function to narrate what is happening with your code. You can download this function by clicking here.
    An example of using log() function:
    function countTo (number){
       var target = document.getElementById('counter');
       log('starting countTo');
       if (number > 1){
         log('number is too small to count to');
       for (var i = 1; i <= number; i++){
         log('count is ' + i);
         target.innerHtml += i + '... ';
    The log() function will show you what's going on when executingJavaScript:
    starting countTo
    number is too small to count to
  3. Using console.log() method, which requires your browser's debugger window. The following link provides more details of JavaScript debugging.

Using Firebug While Developing a Web Project

Firebug provides a powerful JavaScript debugger, CSS and HTML.

Firebug on Linux Machines (in CL115)

You need to check the installation of firebug on linux machines in CL115. FireBug should be installed on CL115 machines already. To active or de-active it, press F12 key.

You will also find that there's a good JavaScript debugger like Firebug built in to newer versions of Chrome and Firefox. They can also be activated or deactivated by pressing the F12 key.

Debugging JavaScript

To debug the script page, you can use the keyboard short-cuts: F12 (show/hide) or Ctrl+F12. If you use the latter, you will see following script panel: (to set a break point you can left click on the left part of a line number, e.g., line number 70) in the following screenshot:


Script Panel "The main purpose of the script panel is to debug JavaScript code. Therefore the script panel integrates a powerful debugging tool based on features like different kinds of breakpoints, step-by-step execution of scripts, a display for the variable stack, watch expressions and more."

When you click a button, you will trigger the onclick event, and the javascript function will handle this event. Firebug will execute this function and stop at the break point (the statement with a breakpoint is to be executed).


You can examine and investigate (watch) variables, stacks in the window at the left side. Also, it is possiable to add a new expression by click and type in the javascript statement.

Step by step debugging: You may use the debugging controls to locate bugs in your JavaScript. Following table provides detials of the control buttons:


In Class Exercise Lab Assignment

You have completed an HTML signup.html in lab1. A task of this assignment is validating user inputs for the signup web page by using external JavaScript. We assume all inputs are in English. The validation should satisfy the following requirements:

  1. Using external JavaScript to do the validation, for example, create a validate_signup.js file.
  2. No empty input. All form elements should have an input. If empty input, one alert box only. See image below
  3. alert box
  4. Maximum input characters of "Email" is 60 characters.
  5. Maximum input characters of "Username" is 40 characters.
  6. "Password" length is 8 characters.
  7. "Confirm Password" field has to match "Password" field.
  8. For correct user inputs, show the user inputs in an alert window. Othersiwse, warn the user in an alert window.
  9. Link your signup.html on the index.html,
  10. zip signup.html and validate_signup.js, upload on URcourses by 11:55 PM.

Note: Output all warnings in one Alert Box, as well as the final result of user inputs. Otherwise, partial marks will be deducted. Using Alert Box is a simple way to give feedback, it is not preferred. The preferred method will actually be discussed in the following lab (i.e., JavaScript and DOM Operations). You should not use alert boxes or other modal windows beyond this lab assignment.