You are on page 1of 64

Javascript

CMPS 246: Web Programming

Web Programming 1
How do web pages
work again?

2
You are on
your laptop

3
Your laptop is
running a web
browser, e.g.
Chrome

4
You type a URL in
the address bar and
hit "enter"

http://bau.edu.lb

5
Server at
http://bau.edu.lb

Browser sends an HTTP request


saying "Please GET me the
index.html file at
(Routing,
http://bau.edu.lb etc…)

6
Server at
http://bau.edu.lb

Assuming all goes well, the


server responds by sending the
HTML file through the internet
back to the browser to display.

7
Server at
http://bau.edu.lb
The HTML will include things like
<img src="pup.png" / > and
<link src="style.css" . . . / >
which generate more requests for
those resources

8
Server at
http://bau.edu.lb

And the server replies with


those resources for the
browser to render

9
Finally, when all resources are loaded,
we see the loaded web page

http://bau.edu.lb

10
+ produces

Describes the Describes the


content and appearance A web page…
structure of and style of
the page the page that doesn't do
anything

11
What we've learned so far

We've learned how to build web pages that:


- Look the way we want them to
- Can link to other web pages
- Display differently on different screen sizes

But we don't know how build web pages that do anything:


- Get user input
- Save user input
- Show and hide elements when the user interacts with
the page
- etc.

12
What we've learned so far?
Content Structure Style Behavior
Text and HTML CSS Javascript
Images writing web pages stylistic info for php
web pages
SQL
AJAX
Interactive
dynamic
programmable
web pages

interaction with
databases

4/19/2021 Web Programming 13


Javascript
4/19/2021 Web Programming 14
JavaScript

JavaScript is a programming language.

It is currently the only programming language that


your browser can execute natively. (There are efforts to
change that.)

Therefore if you want to make your web pages do


stuff, you must use JavaScript: There are no other
options.

15
JavaScript

• Created in 1995 by Brendan Eich (co-founder of Mozilla)


• The first version was written in 10 days
• JavaScript has nothing to do with Java
• Literally named that way for marketing reasons
• JavaScript is dynamically typed
• JavaScript’s support for objects is very different
• We’ll call collections of JavaScript code scripts,
not programs

"I was under marketing orders to make it look like Java but not make it too big for
its britches ... [it] needed to be a silly little brother language." (source)

16
in the browser
17
Code in web pages
HTML can indirectly embed JavaScript files into the web page via the <scr ipt > tag.

<!DOCTYPE html>
<html>
<head>
<title>CS 1 9 3 X< /ti tl e >
<link rel="stylesheet" href="style.css" />
<script src="filename.js"></script>
</head>
<body>
... contents of the page...
</body>
</html>

18
Code in web pages
Can also be embedded internally/directly.
<!DOCTYPE html>
<html>
<head>
<title>CS 1 9 3 X< /ti tl e >
<link rel="stylesheet" href="style.css" />
<script type="text/javascript">
-- Javascript script
</script>
</head>
This is poor code quality though:
<body>
You should always separate
... contents of the page... content, presentation, and
</body> behavior
</html> 19
console.log

You can print log messages in JavaScript by calling


console.log():

script.js

console.log('Hello, w o r l d ! ' ) ;

This JavaScript's equivalent of Java's


Syst em .out.println , p r i n t , p r i n t f , etc.

20
<head>
<title>CMPS 270 </ t it le >
< l i n k re l = " st y l e s h e e t " h r e f = " s t y l e . c s s " / >
<script src="script.js"></script>
</head>

The browser is parsing the HTML file, and gets to a script


tag, so it knows it needs to get the script file as well.

21
<head>
<title>CMPS 270</ t it le >
< l i n k re l = " st y l e s h e e t " h r e f = " s t y l e . c s s " / >
<script src="script.js"></script>
</head>

The browser makes a request to the server for the script.js


file, just like it would for a CSS file or an image...

22
<head>
<title>CMPS 270 </ t it le >
< l i n k re l = " st y l e s h e e t " h r e f = " s t y l e . c s s " / >
<script src="script.js"></script>
</head>

And the server responds with the JavaScript file, just like it
would with a CSS file or an image...

23
<head>
<title>CMPS 270 </ t it le >
< l i n k re l = " st y l e s h e e t " h r e f = " s t y l e . c s s " / >
<script src="script.js"></script>
</head>

console.log('Hello, wo r l d ! ' ) ;

Now at this point, the JavaScript file will execute


"client-side" in the browser on the user's computer.

24
JavaScript execution

• There is no "main method"


• The script file is executed from top to bottom.

• There's no compilation by the developer


• JavaScript is compiled and executed on the fly by the browser
• (Note that this is slightly different than being "interpreted": see just-in-time (JIT)
compilation)

25
first-js.html

<!DOCTYPE html>
<html>
<head>
<meta char set ="ut f - 8">
< t i t l e > F i r s t JS Example</title>
<script src="script.js"></script>
</head>
<body>
</body>
</html>

script.js

console.log('Hello, w o r l d ! ' ) ;
26
Hey, nothing happened!

27
Right-click (or control-click on Mac) and choose "Inspect"

28
Click "Console" tab 29
30
The "Console" tab is also a REPL, or an interactive language
shell, so you can type in JavaScript expressions, etc. to test
out the language.

31
Window Object
• an already available global object
• represents the currently opened
window tab in the browser
• Includes three methods for creating
dialog boxes
• alert
• prompt
• confirm

Web Programming 32
alert Dialog
alert(“hello world! \n“);

• Parameter is plain text, not HTML

• Opens a dialog box


• displays the parameter string
• OK button
• waits for the user to press the OK button

Web Programming 33
prompt Dialog
confirm(“Enter Number”,“ ”);

• Parameters
• Text message label
• Default response

• Opens a dialog box


• displays the parameter string
• OK and Cancel button
• waits for the user to press the OK button

Web Programming 34
Window Object
• Also includes the property (field)
• Document document

• Document represents the HTML HTML Document


document i.e. the webpage

Web Programming 35
Document Object
• has a method, write, which
dynamically creates content Answer: 25
• parameter is a string
• The parameter is sent to the browser,
so it can be anything that can appear
in an HTML document (<br />, but
not \n)
script.js
document.write("Answer: " +
• More to come… result + "<br />");

Web Programming 36
JS Language Features

37
Same as Java
for-loops:
for (let i =0 ; i < 5 ; i++) { … }
while-loops:
while (notFinished) { … }
comments:
/ / comment or / * comment* /
conditionals (if statements):
if(...){
...
} else{
...
}
38
Functions

One way of defining a JavaScript function is with the following


syntax:

F u n c t i o n name() {
statement;
statement;
...
}

39
script.js

function h e l l o ( ) {
console.log('Hello!');
console.log('Welcome t o J a v a S c r i p t ' ) ;
}

hello();
hello();

The browser "executes" the


function definition first, but
that just creates the h e l l o
function (and it doesn't run
the h e l l o function), similar
to a variable declaration.
Console output 40
Variables: var, l e t , const

Declare a variable in JS with one of three keywords:

/ / Function scope v a r i a b l e
var x = 15;
/ / Block scope v a r i a b l e
l e t f r u i t = 'banan a ';
/ / Block scope const ant ; cannot be reassigned
const isHungry = t r u e ;

You do not declare the datatype of the variable before using it ("dynamically typed")

41
What's a "block"?

In the context of programming languages, a block is a group of 0 or more


statements, usually surrounded by curly braces. (wiki / mdn)

• Also known as a compound statement

• Not JavaScript-specific; exists in most languages (C++, Java, Python, etc)

• Has absolutely nothing to do with the HTML/CSS notion of "block", i.e.


block elements
What's a "block"?

For example, the precise definition of an if-statement might look like:


i f (expression) statement

And a block might look like


{
console.log('Hello,w o r l d ! ' ) ;
console.log('Today i s a good d a y. ' ) ;
}

A "block" or compound statement is a type of statement, which is why we can execute multiple statements
when the condition is true.
Blocks and scope

Most languages that include blocks also tie scoping rules to blocks, i.e. via "block
scope":
/ / C++ code, not JS:
i f (...) {
i n t x = 5;
...
}
/ / c a n ' t access x here

This is the behavior of Java, C++, C, etc.


Function parameters

f u n c t i o n printMessage(message, times) {
f o r ( v a r i = 0 ; i < times; i + + ) {
console.log(message);
}
}

Function parameters are not declared with var, l e t , or const

45
Understanding var

f u n c t i o n printMessage(message, t im es ) {
f o r ( v a r i = 0 ; i < t im es; i + + ) {
Q: What happens if we try to
console.log(message); print "i" at the end of
} the loop?
console.log('Value of i i s ' + i ) ;
}

printMessage('hello', 3 ) ;
The value of "i" is readable outside of
the for-loop because variables
declared with v a r have function
scope.

46
Function scope with var
var x = 10;
if (x > 0 ) {
var y = 10;
}
console.log('Value of y i s ' + y ) ;

• Variables declared with "var" have function-level scope and do not


go out of scope at the end of blocks; only at the end of functions
• Therefore you can refer to the same variable after the block has
ended (e.g. after the loop or if-statement in which they are declared)

47
Function scope with var

But you can't refer to a variable outside of the function in


which it's declared.
48
Understanding l e t

f u n c t i o n printMessage(message, t imes ) {
f o r ( l e t i = 0 ; i < t im es; i + + ) { Q: What happens if we
try to print "i" at the
console.log(message); end of the loop?
}
console.log('Value of i i s ' + i ) ;
}
printMessage('hello', 3 ) ;
l e t has block-scope
so this results in an
error

49
Understanding const
let x =
10;
i f (x > 0) {
const y = 10;
}
console.log(y); / / e r r o r !

Like l e t , const also has block-scope, so accessing the


variable outside the block results in an error
50
Understanding const

const y = 10;
y = 0 ; / / er r or !
y++; / / er r or !
const l i s t = [ 1 , 2 , 3 ] ;
list.push(4); / / OK

• const declared variables cannot be reassigned.


• However, it doesn't provide true const correctness, so you can still modify the
underlying object

51
Contrasting with l e t

l e t y = 10;
y = 0 ; / / OK
y++; / / OK
l e t l i s t = [1, 2, 3];
list.push(4); / / OK

l e t can be reassigned, which is the difference between const and l e t

52
Variables best practices

• Use const wheneverpossible.

• If you need a variable to be reassignable, use l e t .

• You will see a ton of example code on the internet with var since const and
l e t are relatively new.
• However, const and l e t are well-supported, so there's no reason not to
use them.
• (This is also what the Google and AirBnB JavaScript Style Guides
recommend.)

53
Types
JS variables do not have types, but the values do.

There are six primitive types (mdn):


• Boolean: true and false
• Number: everything is a double (no integers)
• String: in 'single' or "double-quotes"
• Symbol: used to add unique property keys to an object
• Null: a value meaning "this has no value"
• Undefined: the value of a variable with no value assigned

There are also Object types, including Array, Date, String ,etc.

54
Numbers
const homework= 0 . 4 5 ;
const midterm = 0 . 2 ;
const f i n a l = 0.35;
const score =
homework * 87 + midterm * 90 + f i n a l * 95;
c o n s o l e . l o g( s c o r e ) ; / / 90.4

• All numbers are floating point real numbers. No integer type.


• Operators and their predecedence are like Java .
• A few special values: NaN (not-a-number), +Infinity, -Infinity
• There's a Math class: Math.floor , Math.ceil, etc.

55
Strings
l e t snack=' c o o ' ;
snack += ' k i e s ' ;
snack = snack.toUpperCase();
c o n s o l e . l o g ( " I want " + snack);

• Can be defined with single or double quotes


• Many style guides prefer single-quote, but there is no functionality difference
• No char type: letters are strings of lengthone
• Can use plus for concatenation
• Can check size via length property (notfunction)

56
Strings
String properties nd methods:

• length e.g., var len = str1.length; (a property)


• charAt(position) e.g., str.charAt(3)
• indexOf(string) e.g., str.indexOf('B’)
• substring(from, to) e.g., str.substring(1, 3)
• toLowerCase() e.g., str.toLowerCase()

Web Programming 57
Boolean
l e t isHungry = t r u e ;
l e t isTeenager = age > 12 && age < 20;

i f (isHungry && isTeenager) {


pizza++;
}

• There are two literal values for boolean: t r u e and f a l s e


• that behave as you would expect
• Can use the usual boolean operators: && | | !

58
Boolean

i f (username) {
/ / username i s defined
}

• Non-boolean values can be used in control statements, which get converted to


their "truthy" or "falsy" value:
• n u l l , undefined, 0, NaN, ' ' , " " evaluate to f a l s e
• Everything else evaluates to t r u e

59
Equality

JavaScript's == and != are basically broken: they do an implicit type conversion


before the comparison.

' ' == ' 0 ' / / f a l s e


' ' == 0 / / t r u e
0 == ' 0 ' / / true
NaN == NaN / / f a l s e
[ ' ' ] == ' ' / / true
f a l s e == undefined / / f a l s e
f a l s e == n u l l / / false
n u l l == undefined / / t r u e

60
Equality

Instead of fixing == and ! = , the ECMAScript standard kept the existing behavior
but added === and !==

' ' === ' 0 ' / / f a l s e


' ' === 0 / / f a l s e
0 === ' 0 ' / / f a l s e
NaN ===NaN / / s t i l l w e i r d l y f a l s e
[ ' ' ] === ' ' / / false
f a l s e === undefined / / f a l s e
f a l s e === n u l l / / f a l s e
n u l l ===undefined / / false

Always use === and !== and don't use == or !=


61
Null and Undefined

What's the difference?


• n u l l is a value representing the absence of a value, similar to null in Java
• undefined is the value given to a variable that hasnot been assigned a value.

62
Null and Undefined

What's the difference?


• n u l l is a value representing the absence of a value, similar to null in Java
• undefined is the value given to a variable that hasnot been assigned a value.
… however, you can also set a variable's value to undefined

63
Arrays

Arrays are Object types used to create lists of data.

/ / Creates an empty list


let list = [ ] ;
l e t groceries=[ ' m i l k ' , 'cocoa p u f f s ' ] ;
groceries[1] = ' k i x ' ;

- 0-based indexing
- Can check size via length property similar to java

64

You might also like