You are on page 1of 63

Javascript Intro

Lesson Plan
• Core Javascript Syntax
• Types and Objects
• Functions
• DOM
• Event Handling
• Debugging
• Javascript Best Practices
What you should know

HTML and CSS


Javascript

HTML- mark up language(content)


CSS- style sheet language(presentation)
Javascript – scripting language(behavior)

Javascript is a language that's typically used inside websites, in


order to manipulate the HTML output on the screen, pull in data
from elsewhere, and do calculations.
JavaScript is limited

•Can’t access local files


•Can’t directly access the database
•Can’t access hardware(USB,etc)
Javascript is interpreted, not compiled.

Javascript is case sensitive.

Javasript is whitespace insensitive.


Javascript- is a client-side language
oJavaScript is *not* a "light" version of Java, but its own full-
featured programming language, sharing some syntax with
Java but also different in many ways
The <script> Element

<script type= “text/javascript”>


</script>
Statements

-separate instructions or commands to say a piece of what


you want or code will do.

-terminated by a semi-colon
Activity 1
<html>
<head><title>Simple Page</title>
</head>
<body>
<h1>Simple HTMLPage</h1>
<p> This is very simple HTML page</p>
<p>It's about as basic as they come. It has : </p>

<ul>
<li>An h1 tag </li>
<li>Two paragraphs </li>
<li>An ordered list </li>
</ul>
<script>

alert(
"Hello World!"
);
</script>
</body>
</html>
Where to put javascript?

Position of the code matters


write() and writeln() methods:

-Use to display text in a Web browser when the document is


first rendered

-the only difference between the write() and writeln() is that


the writeln()method adds a line breaks after the line of text.
Line breaks however are only recognized inside the <pre>
element.
Case sensitivity in Javascript

Like XHTML, JavaScript is case sensitive, and within


javascript code, object names must always be all lower case.

The statement:
Document.write(“Welcome to Nashville”);

Causes an error message because the JavaScript interpreter


Cannot recognize an object named with an uppercase D.
Adding Comments

Comments- are various types of remarks including the name


of the program, your name and the date you created the
program, notes to yourself or instructions to future
programmers who may need to modify your work.

•Line comments: hides a single line of code.


// This line comment takes up an entire line

•Block comments
/*
This line is a part of block comment.
This line is also part of block comment.
/*
Including <script> element for each
code section
<h1>Multiple Script Sections</h1>
<h2>First script section</h2>
<script type=“text/javascript”>
document.write(“ <p>Output from the first script section</p>” );
</script>
<h2>Second script section</h2>
<script type=“text/javascript”>
document.write(“ <p>Output from the second script
section</p>” );
</script>
Logic and Debugging

Logic – refers to the order in which various part of a program


run or execute.

Bug- any error in a program that causes it to function


incorrectly, whether because of incorrect syntax or flaws in
logic.

Debugging – is the act of tracing and resolving errors in a


program.
Using the Browser Console
Javascript is usually evaluated after being included in a website,
but modern browsers often come with a console that lets you run
arbitrary JavaScript and see the results.

The console can be used for quick experimentation, like for the
upcoming concepts.

Firefox Chrome

Go to Developer->Tools->Console or
Download the Firebug extension for Firefox.
press CTRL+SHIFT+J.
Basic Variables
Use var to declare a variable. Its initial value will be
undefined.
var x;

It will work if you don't use var, but then it will become a global
variable, which you usually don't want.

You can later initialize it:


x = 5;

Or you can declare and initialize all at once:


var x = 5;
var name;

undefined

name

name = “jasmine”;

jasmine
Basic Data Types
Variables are loosely typed. They can be assigned to any data
type, and can later be re-assigned to different data types.

The primitive data types in Javascript are string, number, and


boolean, undefined, and null:

var x;
x = "6";
x = 2 + 2;
x = false;
x = null;

The complex data types are Arrays or Objects (covered later).

Everything in JS is one of these types. **activity1


Numbers
All numbers are 64 bit floating point - there's no differentiation
between an int/float/double type.

The standard operators for numbers work in Javascript:


var x = 2 * 3;
var y = x / 4;
var z = x - y;

When an operation doesn't result in a valid number, it


returns NaN or in case of 1/0, Infinity.

There are various utility functions in the Math library:


var x = Math.abs(-454);
var y = Math.pow(2, 3);
...
Strings
Strings are immutable, but a new string can be created easily
with concatenation:
var x = "hello";
var y = "world";
var z = x + " " + y;
x += "!";

Single quotes and double quotes are the same:


var x = "hi";
var x = 'hi';

Single quotes can be used inside double quotes, & vice versa:
var x = "then he said, 'thats awesome!'";
var y = 'then he said, "thats awesome!"';
** Activity 2
Strings <-> Numbers
Strings can be converted to numbers by doing simple math on
them:
var x = "43.232" * 1;

Use parseFloat to turn a string into a number:


var x = parseFloat("43.232");

Use parseInt to return a number with no digits after the


decimal:
var x = parseInt("43.232");

Numbers can be converted to strings with a formal cast, or just


by appending an empty string.
var x = 23 + "";
var x = String(23);
String Methods
Strings have many native helper methods:
var greeting = "Hello there";

greeting.charAt(0); // "H" - String indices are 0-based

greeting.toUpperCase(); // "HELLO THERE"

This indexOf function returns the start index of the first occurrence of a
given character or substring, or -1 if not found.

greeting.indexOf("e"); // 1
greeting.indexOf("there") // 6
greeting.indexOf("E") // -1

Method calls can be chained in Javascript:

greeting.toUpperCase().indexOf("E") ** Activity 2
String Methods
The slice method is a handy way to create substrings.
slice(start, end) returns a copy of the string beginning at start
and extending up to but not including end:
'Hello'.slice(1, 3); // "el"

If no end is specified, it copies up to the end of the string:


'Hello'.slice(2); // "llo"

The replace method is a handy way to create a new string by


replacing a substring with another substring:
'hi, hi'.replace('hi', 'bye'); // "bye, hi"
Using in a Webpage
JavaScript can be embedded inside script tags on a page:

<script>
var x = "Hello World";
alert(x);
</script>

Javascript can also be in external files, and referenced in a


page:

<script src="external.js"></script>
Outputting to HTML
The absolute simplest way to modify the HTML of a page using
JavaScript is with the document.write method:

document is a predefined browser variable that always points


to the current HTML document. The write method will let us
insert text (or HTML) into the document immediately following
the <script> element:

<script type="text/javascript">
document.write("Hello World");
</script>

Note:The inserted content will not appear in the browser's "view


source" window (try it out), but it will appear in the page model
accessible via JavaScript (more on that later).
Debugging with Browser Consoles
The browser console will output any errors it encounters while
running JS on the current page. The most common errors are
trying to use functions or variables that don't exist. Try the
following in an HTML file:

alertt("alertt doesn't exist");

The console status bar will display "1 Error", and you can open
up the console for more information. It will often point to the line
of code that caused the error, and show a trace of the functions
called before the error was called.

You can also use console.log() to write out information to the


console from within your web page's JS.
Arithmetic operators:

+
-
/
*

Shorthand
score= score + 10; score+=10;
score= score - 10; score-=10;
score= score / 10; score/=10;
score= score * 10; score*=10;
Operator precedence

result = 5+5 *10;

Ans= 55
symbols

( ) parentheses
[ ] brackets
{ }braces

Operators:
< !=
> ===
== >=
<=
Control Structures

Control structures
– allows us to change the ordering of how the statements in
our programs are executed
Two types of Control Structures

– decision control structures


● allows us to select specific sections of code to be executed
– repetition control structures
● allows us to execute specific sections of the code a number
of times
Decision control structures

– JavaScript statements that allows us to select and execute


specific blocks of code while skipping other sections

Types:
– if-statement
– if-else-statement
– If-else if-statement
if-statement

– specifies that a statement (or block of code) will be executed


if and only if a certain boolean statement is true.
if-statement has the form:

if( boolean_expression )
statement;

or
if( boolean_expression ){
statement1;
statement2;
}
Conditional Code

if ( condition){

//code goes here


}
if-statement Flowchart
Sample Program2:

var grade = 68;


if( grade > 60 ){
document.write("Congratulations!");
document.write("You passed!");
}
Coding Guidelines

1. The boolean_expression part of a statement should


evaluate to a boolean value. That means that the
execution of the condition should either result to a value of
true or a false.

2. Indent the statements inside the if-block.


For example,
if( boolean_expression ){
//statement1;
//statement2;
}
if-else statement

– used when we want to execute a certain statement if a


condition is true, and a different statement if the condition is
false.
if-else statement has the form:

if( boolean_expression ){
statement1;
statement2;
...
}
else{
statement3;
statement4;
...
}
Sample program:

var grade = 68;

if( grade > 60 )


document.write("Congratulations!");

else
document.write("Sorry you failed");
Sample program2:

var grade = 68;

if( grade > 60 ){


document.write("Congratulations!");
document.write("You passed!");
}
else{
document.write("Sorry you failed");
}
Coding Guidelines:

1. To avoid confusion, always place the statement or


statements of an if or if-else block inside {}.
2. You can have nested if-else blocks. This means that you
can have other if-else blocks inside another if-else block.
For example,
if( boolean_expression ){
if( boolean_expression ){
//some statements here
}
}
else{
//some statements here
}
Equality

= assignment operator
== comparing equality … if the value is the same

=== strict equality ,value and data type must be the same
Sample code:

var amount =500;


if(amount<1000){
alert(“It’s less than 1000");
}
Sample code:

var grade =75;


if(grade<75){
alert(“Congratulations!");
}
else{
alert(“Sorry,you failed”);

}
Sample code:

var a =5;
var b ="5";

if(a==b){
alert("Yes they are equal");
}

else{
alert("Yes they are NOT equal");

}
if-else-else if statement:

● The statement in the else-clause of an if-else block can be


another if-else structures.
● This cascading of structures allows us to make more
complex selections.
● The statement has the form:

if( boolean_expression1 )
statement1;
else if( boolean_expression2 )
statement2;
else
statement3;
Sample Program:

var grade = 68;


if( grade > 90 ){
alert("Very good!");
}
else if( grade > 60 ){
alert(" good!");
}
else{
alert("Sorry you failed");
}
Exercise

/*Create a script that will compute the real estate tax, given
the following formulas:
a.)If value of real estate is less than 250,001.00, tax is 5% of
real estate value.
b.) If value of real estate is between 250, 001.00 to
500,000, tax is 10% of the real estate value.

c.)If more than 500,000 tax is 15% of the real estate value.*/
Exercise

/*An employee’s weekly working hours is 40. If an employee


exceeds 40 hours, it is considered overtime. Create a script
that will inspect the number of hours worked by employee and
his/her hourly rate and print the gross pay and overtime pay
rendered, if there’s no OT pay to print, print only the gross
pay. To compute for the gross pay of the employee, multiply
the number of hours worked by his/her hourly rate plus his/her
OT pay. OT hours are time rendered by employee over 40
hours. The overtime hours rendered should be computed by
using 150% of his hourly rate*/
Exercise

/*Create a script that will check the number and print either
ODD or EVEN*/
Exercise

/*Create a script that will assess which of the 3 numbers


instantiated is the highest*/
Logical and/or

if(a==b && c==d)

if(a==b || c==d)
Exercise:

Grade:

90 – 100 = “Excellent”
80 – 89 = “Good job”
60 – 79 = “Study Harder”
59 – below = “Sorry you failed”
Modulus operator : %

var num = 3;
var mod= num% 2;

if(mod==0){
alert("Even");
}
else{
alert("Odd");
}
Unary Operator

Increment
a++;
++a;

Decrement
a--;
--a;
While Loop

var a =1;

while(a<10){
document.write("Sha");
a++;

}
Do while

var a=1;

do {
document.write();
a++;
}

while(a<10);
For Loop

for(i=1; i<5; i++){

document.write(“I love Javascript”);

You might also like