SlideShare a Scribd company logo
1 of 13
Download to read offline
1 
CodeActually 
Dr. 
Cindy 
Royal 
Texas 
State 
University 
School 
of 
Journalism 
and 
Mass 
Communication 
Introduction 
to 
Programming 
for 
Communicators 
¡ JavaScript 
is 
a 
scripting 
language 
commonly 
implemented 
as 
part 
of 
a 
web 
browser 
in 
order 
to 
create 
enhanced 
user 
interfaces 
and 
dynamic 
websites. 
¡ JavaScript 
is 
not 
the 
same 
as 
Java. 
¡ Can 
be 
run 
client 
side 
or 
server-­‐side 
(Node.js 
– 
a 
JavaScript 
environment). 
¡ Foundation 
for 
code 
libraries 
like 
JQuery. 
For 
the 
first 
series 
of 
exercises, 
we’ll 
be 
practicing 
in 
Chrome’s 
console. 
This 
is 
an 
environment 
that 
let’s 
you 
run 
code 
and 
see 
the 
result. 
Later, 
we 
will 
be 
implementing 
JavaScript 
in 
html 
pages 
using 
JSFiddle. 
In 
Chrome, 
choose 
View, 
Developer 
Tools 
and 
click 
on 
the 
Console 
tab. 
Or 
Ctrl-­‐click 
on 
the 
screen 
and 
choose 
Inspect 
Element. 
Normally, 
these 
commands 
would 
be 
in 
a 
.js 
file 
or 
encapsulated 
in 
the 
<script> 
tag 
in 
an 
html 
document. 
But 
we 
are 
just 
practicing 
with 
concepts 
in 
this 
demonstration. 
Your 
First 
Program 
Write 
the 
string 
“Hello 
World!” 
console.log("Hello World!"); 
document.write("Hello World!"); 
Don’t 
worry 
if 
you 
see 
“undefined” 
in 
the 
console 
after 
the 
code 
returns. 
The 
console 
is 
attempting 
to 
determine 
the 
type 
that 
the 
code 
returns, 
and 
in 
most 
cases 
in 
our 
exercises 
that 
is 
“undefined.” 
console.log 
logs 
to 
the 
console. 
document.write 
writes 
to 
the 
document. 
Try 
them 
both. 
Objects, 
Properties 
and 
Methods 
For 
this 
exercise, 
we 
will 
mostly 
be 
using 
the 
console 
object 
to 
write 
code 
to 
the 
console. 
console.log(“info goes here”); 
Later 
we 
will 
use 
the 
document.write 
method 
to 
write 
to 
the 
html 
document. 
We 
do 
this 
by 
calling 
the 
document 
object 
and 
the 
write 
method. 
Basic 
JavaScript 
Syntax 
End 
lines 
with 
semicolon 
; 
Put 
arguments/parameters 
in 
parentheses 
( 
)
2 
Period 
(.) 
between 
object 
and 
method 
or 
property. 
Strings 
in 
quotation 
marks 
" 
Unlike 
other 
languages, 
you 
do 
not 
have 
to 
declare 
a 
type 
when 
instantiating 
a 
variable. 
Some 
objects 
are 
built-­‐in 
(i.e. 
document, 
window), 
some 
can 
be 
defined. 
Data 
Types 
String, 
Number, 
Boolean, 
Array, 
Object, 
Null, 
Undefined 
-­‐ 
programming 
languages 
have 
syntax 
and 
functions 
that 
work 
with 
a 
variety 
of 
data 
types. 
We 
will 
mainly 
be 
concerned 
with 
strings 
and 
numbers, 
later 
adding 
booleans 
and 
arrays. 
Length 
Length 
is 
a 
string 
property 
that 
returns 
the 
length 
of 
the 
string. 
console.log("Hello World!".length); 
This 
returns 
a 
number 
that 
is 
the 
length 
of 
that 
string, 
including 
the 
space. 
Concatenation 
Use 
concatenation 
to 
join 
strings. 
The 
empty 
space 
between 
the 
quotation 
marks 
(" 
") 
represents 
a 
space. 
The 
plus 
sign 
is 
the 
concatenation 
operator. 
console.log("Hello" + " " + "Cindy!"); 
Variables 
Use 
variables 
to 
store 
numbers 
and 
strings. 
The 
var 
prefix 
is 
optional. 
var name = "Cindy"; 
console.log("Hello" + " " + name); 
and 
var firstname = "Cindy"; 
var lastname = "Royal"; 
console.log(firstname + " " + lastname);
3 
Math 
and 
numbers 
Operators 
and 
Math 
Within 
your 
script 
tag, 
try 
the 
following 
individually. 
You 
will 
see 
the 
different 
operators 
for 
math 
functions. 
console.log(3+4); 
console.log (3-4); 
console.log (3*4); 
console.log (3/4); 
console.log(3%4); 
The 
“%” 
operator 
is 
the 
modulo 
that 
shows 
the 
remainder 
of 
division 
calculation. 
Substrings 
I’m 
using 
these 
scripts 
to 
see 
what 
my 
JLo 
name 
would 
be, 
finding 
the 
first 
character 
of 
my 
first 
name 
and 
the 
first 
two 
characters 
of 
my 
last 
name. 
var firstname = "Cindy"; 
var lastname = "Royal"; 
console.log(firstname.substring(0,1) + 
lastname.substring(0,2)); 
or 
var first = "Cindy".substring(0,1); 
var last = "Royal".substring(0,2); 
console.log(first + last); 
Notice 
that 
we 
used 
a 
combination 
of 
variables 
and 
the 
substring 
method 
in 
two 
different 
ways 
to 
achieve 
the 
same 
result. 
Often 
in 
programming, 
there 
are 
multiple 
ways 
to 
solve 
a 
problem. 
Alerts 
and 
Prompts 
Alert 
-­‐ 
a 
general 
warning 
alert("Danger"); 
Confirm 
-­‐ 
answer 
yes 
or 
no 
before 
you 
can 
continue. 
confirm("Are you sure?");
4 
Prompt 
-­‐ 
answer 
anything 
-­‐ 
creates 
variable 
prompt("What is your name?"); 
var name = prompt("What is your name?"); 
console.log("Hello " + name); 
Booleans 
and 
if 
statements 
Use 
booleans 
to 
test 
if 
something 
is 
true 
or 
false. 
Combine 
with 
an 
if/else 
statement 
to 
define 
different 
outcomes. 
Notice 
that 
the 
“if 
statements” 
actions 
are 
delineated 
with 
curly 
braces. 
You 
can 
also 
test 
for 
mathematical 
statements 
like 
greater 
than 
>, 
less 
than 
< 
or 
equal 
to 
==. 
name="Cindy"; 
if(name.length==5){ 
console.log("Yes"); 
} 
else { 
console.log("No"); 
} 
or 
x=2; 
if(x>1) { 
console.log("Yes"); 
} 
else { 
console.log("No"); 
} 
Comparisons 
(= 
or 
==) 
A 
single 
equal 
sign 
(=) 
indicates 
assignment, 
usually 
used 
to 
assign 
a 
value 
to 
a 
variable. 
If 
you 
are 
doing 
a 
test 
for 
comparison, 
then 
you 
use 
2 
equal 
signs 
(==). 
2+2==4; 
var name="Cindy"; 
if(name=="Cindy";)...
5 
Functions 
Functions 
allow 
you 
to 
define 
an 
operation 
and 
then 
use 
it 
later. 
Notice 
the 
statements 
in 
the 
function 
are 
enclosed 
in 
curly 
braces. 
Then 
we 
call 
the 
function 
using 
its 
name 
to 
execute 
it. 
There 
are 
two 
different 
ways 
to 
write 
a 
function. 
var hello = function () { 
var name = prompt("What is your name?"); 
console.log("Hello " + name); 
} 
hello(); 
or 
function hello() { 
var name = prompt("What is your name?"); 
console.log("Hello " + name); 
} 
hello();
6 
Arguments 
You 
can 
add 
arguments 
in 
the 
parentheses 
of 
a 
function 
to 
pass 
information 
into 
it. 
var hello = function (a) { 
console.log("Hello " + a); 
} 
hello("Cindy"); 
or 
function hello(a) { 
console.log("Hello " + a); 
} 
hello("Cindy"); 
Loops 
Loops 
allow 
for 
iteration 
through 
a 
cycle. 
We 
will 
switch 
to 
document.write 
command 
to 
see 
the 
result 
in 
the 
browser 
window. 
The 
while 
loop 
is 
a 
statement 
that 
uses 
a 
variable 
as 
initializer, 
condition 
and 
iterator. 
var i=0; // initializer 
while (i<5) { //condition 
document.write("I am writing this five times"); 
i++; // iterator 
} 
Loops, 
continued 
The 
for 
loop 
reduces 
some 
of 
the 
coding 
by 
having 
three 
statements 
in 
the 
parentheses, 
separated 
by 
a 
semicolon; 
-­‐ 
an 
initializer, 
a 
condition 
to 
test 
and 
an 
iterator. 
for (var i=0; i<4; i++) 
{ 
document.write("I am writing this 4 times<br />"); 
} 
Or 
if 
you 
want 
to 
get 
fancy, 
you 
can 
add 
the 
iterator 
to 
have 
a 
different 
number 
in 
each 
line. 
for (var i=0; i<4; i++) 
{ 
document.write("This is time " + i + "<br />"); 
}
7 
Arrays 
Arrays 
allow 
you 
to 
store 
a 
collection 
of 
information 
in 
a 
variable 
and 
then 
access 
it 
via 
its 
index 
number. 
Index 
numbers 
start 
with 
0. 
Enclose 
elements 
of 
an 
array 
in 
square 
brackets. 
var favGroups = ["Old 97s", "Spoon", "Wilco"]; 
document.write(favGroups[1]); 
This 
accesses 
the 
item 
in 
the 
array 
in 
location 
1. 
Notice 
that 
it 
isn’t 
the 
first 
item 
in 
the 
array. 
Arrays 
start 
with 
0, 
so 
to 
access 
the 
first 
item, 
use 
favGroups[0]. 
You 
can 
use 
a 
loop 
to 
iterate 
through 
an 
array. 
Concatenate 
a 
break 
so 
the 
items 
appear 
on 
a 
different 
line. 
Your 
condition 
uses 
the 
length 
property 
of 
an 
array 
to 
determine 
how 
many 
items 
are 
in 
it. 
var i=0; 
var favGroups = ["Old 97s", "Spoon", "Wilco"]; 
while(i<favGroups.length){ 
document.write(favGroups[i] + "<br />"); 
i++; 
} 
Notice 
how 
we 
can 
add 
html 
items 
as 
a 
string. 
We 
are 
beginning 
to 
integrate 
html 
and 
JavaScript 
for 
interactivity. 
Objects 
Objects 
are 
similar 
to 
arrays 
except 
they 
store 
items 
in 
key/value 
pairs 
rather 
than 
accessing 
them 
by 
their 
index 
number. 
Instead 
of 
using 
square 
brackets, 
you 
use 
curly 
braces 
for 
objects. 
var bands; 
bands = { 
name: "Old 97s", 
city: "Dallas", 
genre: "alt-country" 
}; 
document.write(bands.name + ", " + bands.city + ", " + 
bands.genre);
8 
We 
can 
use 
an 
array 
in 
conjunction 
with 
an 
object 
to 
add 
multiple 
elements 
to 
the 
object. 
var bands; 
bands = [ 
{ 
name: "Old 97s", 
city: "Dallas", 
genre: "alt-country" 
}, 
{ 
name: "Spoon", 
city: "Austin", 
genre: "Indie Rock" 
}, 
{ 
name: "Wilco", 
city: "Chicago", 
genre: "alt-country" 
} 
]; 
document.write(bands[1].name + ", " + bands[1].city + ", " 
+ bands[1].genre); 
And 
we 
can 
loop 
through 
an 
object 
just 
like 
we 
did 
with 
an 
array. 
Your 
condition 
uses 
the 
length 
property 
of 
an 
object 
to 
determine 
how 
many 
items 
are 
in 
it. 
var bands; 
bands = [ 
{ 
name: "Old 97s", 
city: "Dallas", 
genre: "alt-country" 
}, 
{ 
name: "Spoon", 
city: "Austin", 
genre: "Indie Rock" 
},
9 
{ 
name: "Wilco", 
city: "Chicago", 
genre: "alt-country" 
} 
]; 
for(var i=0; i<bands.length; i++) { 
document.write(bands[i].name + ", " + bands[i].city + ", " 
+ bands[i].genre + "<br />"); 
} 
You 
will 
sometimes 
see 
data 
embedded 
in 
objects 
in 
JavaScript 
referred 
to 
as 
JSON 
(JavaScript 
Object 
Notation).
Using 
JavaScript 
in 
an 
html 
document 
getElementById(); 
is 
a 
magical 
method 
that 
you 
can 
use 
to 
access 
parts 
of 
a 
Web 
page. 
We 
need 
to 
work 
with 
a 
web 
page, 
so 
that 
this 
function 
can 
manipulate 
the 
Document 
Object 
Model 
(DOM). 
The 
function 
below, 
when 
called, 
changes 
the 
innerHTML 
of 
the 
element 
with 
the 
id 
“first”. 
This 
is 
very 
powerful 
when 
combined 
with 
forms 
to 
ask 
a 
user 
for 
input 
to 
change 
something 
on 
a 
page. 
Let’s 
properly 
structure 
the 
document 
now 
to 
include 
the 
HTML5 
doctype 
declaration, 
too. 
10 
<!DOCTYPE html> 
<html> 
<head> 
<title>My JavaScript</title> 
</head> 
<body> 
<p>Hello <span id="first">Cindy</span></p> 
<script> 
function nameChange() { 
document.getElementById('first').innerHTML = 'Jon'; 
} 
nameChange(); 
</script> 
</body> 
</html>
Events 
An 
advanced 
use 
of 
JavaScript 
in 
an 
html 
document 
has 
to 
do 
with 
mouse 
events. 
An 
event 
is 
an 
interaction 
– 
onclick, 
onload, 
onmouseover, 
onmouseout. 
Simple: 
11 
<!DOCTYPE html> 
<html> 
<head> 
<title>My JavaScript</title> 
</head> 
<body> 
<h1 onclick="this.innerHTML='Good work!'">Click on this 
text!</h1> 
</body> 
</html> 
The 
“this” 
operator 
tells 
the 
code 
to 
operate 
on 
the 
current 
element. 
In 
a 
function: 
<!DOCTYPE html> 
<html> 
<head> 
<script> 
function changetext() 
{ 
document.getElementById("new").innerHTML="You're a 
pro!"; 
} 
</script> 
</head> 
<body> 
<h1 id="new" onclick="changetext()">Click on this 
text!</h1> 
</body> 
</html> 
You 
will 
use 
events 
combined 
with 
getElementById() 
to 
create 
interactivity 
on 
your 
site.
More 
advanced 
use 
of 
getElementById() 
with 
form 
This 
form 
requests 
your 
name, 
then 
it 
stores 
that 
info 
in 
a 
variable 
and 
presents 
it 
in 
the 
message 
below 
on 
the 
page. 
<!DOCTYPE html> 
<html> 
<head> 
<title>Fun With Forms</title> 
</head> 
<body> 
<form id="form1" action=" "/> 
<p>Name: <input type="text" id="newname" /></p> 
<input type="submit" value="Submit"> 
</form> 
<p>Hi <strong><span id="yourname">"Your Name 
Here"</span></strong>. Welcome to the site.</p> 
<script> 
document.getElementById("form1").onsubmit=function() { 
12 
var newName = document.forms["form1"]["newname"].value; 
document.getElementById("yourname").style.color = "red"; 
document.getElementById("yourname").innerHTML = newName; 
return false; // required to not refresh the page 
} 
</script> 
</body> 
</html> 
This 
code 
changes 
the 
innerHTML 
of 
the 
span 
tag 
in 
the 
html 
document 
to 
the 
text 
from 
the 
form. 
It 
also 
changes 
the 
color. 
We’ll 
get 
more 
practice 
with 
JavaScript 
in 
the 
charting 
exercise.
Comments 
Developers 
use 
comments 
to 
leave 
notes 
in 
the 
code, 
provide 
instructions 
for 
other 
developers 
or 
to 
provide 
clues 
to 
certain 
techniques. 
It 
helps 
to 
organize 
code. 
Comments 
can 
also 
be 
used 
to 
temporarily 
remove 
and 
test 
code 
without 
having 
to 
delete 
it. 
With 
the 
script 
tag. 
13 
// This is a comment 
/* This is a multi-line 
comment */ 
Note: 
basic 
html 
comments 
are 
handled 
by 
<!-­‐-­‐ 
-­‐-­‐>. 
This 
would 
be 
used 
in 
html 
documents 
outside 
the 
<script> 
tag. 
Now 
you 
have 
a 
basic 
understanding 
of 
programming 
concepts. 
There 
are 
many 
ways 
to 
go 
from 
here. 
You 
can 
learn 
more 
about 
coding 
Web 
pages 
with 
HTML/CSS, 
so 
that 
you 
can 
integrate 
interactive 
concepts. 
Or 
you 
can 
move 
into 
the 
world 
of 
JQuery 
to 
learn 
how 
to 
take 
advantage 
of 
coding 
libraries.

More Related Content

What's hot

descriptive programming
descriptive programmingdescriptive programming
descriptive programmingAnand Dhana
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and ArraysWebStackAcademy
 
JavaScript Arrays
JavaScript Arrays JavaScript Arrays
JavaScript Arrays Reem Alattas
 
DevNation'15 - Using Lambda Expressions to Query a Datastore
DevNation'15 - Using Lambda Expressions to Query a DatastoreDevNation'15 - Using Lambda Expressions to Query a Datastore
DevNation'15 - Using Lambda Expressions to Query a DatastoreXavier Coulon
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashBret Little
 
AutoIt for the rest of us - handout
AutoIt for the rest of us - handoutAutoIt for the rest of us - handout
AutoIt for the rest of us - handoutBecky Yoose
 
Javascript built in String Functions
Javascript built in String FunctionsJavascript built in String Functions
Javascript built in String FunctionsAvanitrambadiya
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreNicolas Carlo
 
Symfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 IntegrationSymfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 IntegrationJonathan Wage
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesRasan Samarasinghe
 
Kotlin on Android: Delegate with pleasure
Kotlin on Android: Delegate with pleasureKotlin on Android: Delegate with pleasure
Kotlin on Android: Delegate with pleasureDmytro Zaitsev
 
Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...
Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...
Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...Eelco Visser
 
Should I Use Scalding or Scoobi or Scrunch?
Should I Use Scalding or Scoobi or Scrunch? Should I Use Scalding or Scoobi or Scrunch?
Should I Use Scalding or Scoobi or Scrunch? DataWorks Summit
 

What's hot (20)

descriptive programming
descriptive programmingdescriptive programming
descriptive programming
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
 
JavaScript Arrays
JavaScript Arrays JavaScript Arrays
JavaScript Arrays
 
DevNation'15 - Using Lambda Expressions to Query a Datastore
DevNation'15 - Using Lambda Expressions to Query a DatastoreDevNation'15 - Using Lambda Expressions to Query a Datastore
DevNation'15 - Using Lambda Expressions to Query a Datastore
 
What are arrays in java script
What are arrays in java scriptWhat are arrays in java script
What are arrays in java script
 
The Xtext Grammar Language
The Xtext Grammar LanguageThe Xtext Grammar Language
The Xtext Grammar Language
 
Lodash js
Lodash jsLodash js
Lodash js
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
 
AutoIt for the rest of us - handout
AutoIt for the rest of us - handoutAutoIt for the rest of us - handout
AutoIt for the rest of us - handout
 
Javascript built in String Functions
Javascript built in String FunctionsJavascript built in String Functions
Javascript built in String Functions
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscore
 
Symfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 IntegrationSymfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 Integration
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
 
Kotlin on Android: Delegate with pleasure
Kotlin on Android: Delegate with pleasureKotlin on Android: Delegate with pleasure
Kotlin on Android: Delegate with pleasure
 
Scalding for Hadoop
Scalding for HadoopScalding for Hadoop
Scalding for Hadoop
 
Scala - en bedre Java?
Scala - en bedre Java?Scala - en bedre Java?
Scala - en bedre Java?
 
Functional es6
Functional es6Functional es6
Functional es6
 
Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...
Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...
Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...
 
Should I Use Scalding or Scoobi or Scrunch?
Should I Use Scalding or Scoobi or Scrunch? Should I Use Scalding or Scoobi or Scrunch?
Should I Use Scalding or Scoobi or Scrunch?
 

Similar to Handout - Introduction to Programming

Intro to Programming for Communicators - Hacks/Hackers ATX
Intro to Programming for Communicators - Hacks/Hackers ATXIntro to Programming for Communicators - Hacks/Hackers ATX
Intro to Programming for Communicators - Hacks/Hackers ATXCindy Royal
 
Intro to Programming for Communicators - Hacks/Hackers ATX
Intro to Programming for Communicators - Hacks/Hackers ATXIntro to Programming for Communicators - Hacks/Hackers ATX
Intro to Programming for Communicators - Hacks/Hackers ATXCindy Royal
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An IntroductionManvendra Singh
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript TutorialBui Kiet
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingRadoslav Georgiev
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoftch samaram
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypesVarun C M
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6Nitay Neeman
 
Ajax and JavaScript Bootcamp
Ajax and JavaScript BootcampAjax and JavaScript Bootcamp
Ajax and JavaScript BootcampAndreCharland
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Troy Miles
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScriptDan Phiffer
 
10. session 10 loops and arrays
10. session 10   loops and arrays10. session 10   loops and arrays
10. session 10 loops and arraysPhúc Đỗ
 
The Ring programming language version 1.7 book - Part 90 of 196
The Ring programming language version 1.7 book - Part 90 of 196The Ring programming language version 1.7 book - Part 90 of 196
The Ring programming language version 1.7 book - Part 90 of 196Mahmoud Samir Fayed
 

Similar to Handout - Introduction to Programming (20)

Javascript 101
Javascript 101Javascript 101
Javascript 101
 
Intro to Programming for Communicators - Hacks/Hackers ATX
Intro to Programming for Communicators - Hacks/Hackers ATXIntro to Programming for Communicators - Hacks/Hackers ATX
Intro to Programming for Communicators - Hacks/Hackers ATX
 
Intro to Programming for Communicators - Hacks/Hackers ATX
Intro to Programming for Communicators - Hacks/Hackers ATXIntro to Programming for Communicators - Hacks/Hackers ATX
Intro to Programming for Communicators - Hacks/Hackers ATX
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft Training
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
Javascript
JavascriptJavascript
Javascript
 
CSC PPT 13.pptx
CSC PPT 13.pptxCSC PPT 13.pptx
CSC PPT 13.pptx
 
JavaScript.pptx
JavaScript.pptxJavaScript.pptx
JavaScript.pptx
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6
 
Ajax and JavaScript Bootcamp
Ajax and JavaScript BootcampAjax and JavaScript Bootcamp
Ajax and JavaScript Bootcamp
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
Javascript
JavascriptJavascript
Javascript
 
10. session 10 loops and arrays
10. session 10   loops and arrays10. session 10   loops and arrays
10. session 10 loops and arrays
 
The Ring programming language version 1.7 book - Part 90 of 196
The Ring programming language version 1.7 book - Part 90 of 196The Ring programming language version 1.7 book - Part 90 of 196
The Ring programming language version 1.7 book - Part 90 of 196
 

More from Cindy Royal

PhDigital 2020: Web Development
PhDigital 2020: Web DevelopmentPhDigital 2020: Web Development
PhDigital 2020: Web DevelopmentCindy Royal
 
Redefining Doctoral Education: Preparing Future Faculty to Lead Emerging Med...
Redefining Doctoral Education:  Preparing Future Faculty to Lead Emerging Med...Redefining Doctoral Education:  Preparing Future Faculty to Lead Emerging Med...
Redefining Doctoral Education: Preparing Future Faculty to Lead Emerging Med...Cindy Royal
 
Product Management
Product ManagementProduct Management
Product ManagementCindy Royal
 
Digital Product Management
Digital Product ManagementDigital Product Management
Digital Product ManagementCindy Royal
 
Bending, Breaking and Blending the Academy
Bending, Breaking and Blending the AcademyBending, Breaking and Blending the Academy
Bending, Breaking and Blending the AcademyCindy Royal
 
Taking Control of Social Media For Your Career
Taking Control of Social Media For Your CareerTaking Control of Social Media For Your Career
Taking Control of Social Media For Your CareerCindy Royal
 
Bootstrap Web Development Framework
Bootstrap Web Development FrameworkBootstrap Web Development Framework
Bootstrap Web Development FrameworkCindy Royal
 
Web Development Intro
Web Development IntroWeb Development Intro
Web Development IntroCindy Royal
 
PhDigital Bootcamp: Web Development Concepts
PhDigital Bootcamp: Web Development ConceptsPhDigital Bootcamp: Web Development Concepts
PhDigital Bootcamp: Web Development ConceptsCindy Royal
 
PhDigital Bootcamp: Digital Product Management
PhDigital Bootcamp: Digital Product ManagementPhDigital Bootcamp: Digital Product Management
PhDigital Bootcamp: Digital Product ManagementCindy Royal
 
Digital and Social Certifications
Digital and Social CertificationsDigital and Social Certifications
Digital and Social CertificationsCindy Royal
 
MiLab Presentation 2018
MiLab Presentation 2018MiLab Presentation 2018
MiLab Presentation 2018Cindy Royal
 
Is Your Curriculum Digital Enough?
Is Your Curriculum Digital Enough?Is Your Curriculum Digital Enough?
Is Your Curriculum Digital Enough?Cindy Royal
 
Fundamentals of Digital/Online Media
Fundamentals of Digital/Online MediaFundamentals of Digital/Online Media
Fundamentals of Digital/Online MediaCindy Royal
 
Bringing Digital Into the Curriculum - AEJMC 2017
Bringing Digital Into the Curriculum - AEJMC 2017Bringing Digital Into the Curriculum - AEJMC 2017
Bringing Digital Into the Curriculum - AEJMC 2017Cindy Royal
 
Responsive Design
Responsive DesignResponsive Design
Responsive DesignCindy Royal
 
The World of Web Development - 2017
The World of Web Development - 2017The World of Web Development - 2017
The World of Web Development - 2017Cindy Royal
 
Why Should Communicators Learn to Code?
Why Should Communicators Learn to Code?Why Should Communicators Learn to Code?
Why Should Communicators Learn to Code?Cindy Royal
 
Engaging Audiences with Social Media
Engaging Audiences with Social MediaEngaging Audiences with Social Media
Engaging Audiences with Social MediaCindy Royal
 

More from Cindy Royal (20)

PhDigital 2020: Web Development
PhDigital 2020: Web DevelopmentPhDigital 2020: Web Development
PhDigital 2020: Web Development
 
Redefining Doctoral Education: Preparing Future Faculty to Lead Emerging Med...
Redefining Doctoral Education:  Preparing Future Faculty to Lead Emerging Med...Redefining Doctoral Education:  Preparing Future Faculty to Lead Emerging Med...
Redefining Doctoral Education: Preparing Future Faculty to Lead Emerging Med...
 
Web Development
Web DevelopmentWeb Development
Web Development
 
Product Management
Product ManagementProduct Management
Product Management
 
Digital Product Management
Digital Product ManagementDigital Product Management
Digital Product Management
 
Bending, Breaking and Blending the Academy
Bending, Breaking and Blending the AcademyBending, Breaking and Blending the Academy
Bending, Breaking and Blending the Academy
 
Taking Control of Social Media For Your Career
Taking Control of Social Media For Your CareerTaking Control of Social Media For Your Career
Taking Control of Social Media For Your Career
 
Bootstrap Web Development Framework
Bootstrap Web Development FrameworkBootstrap Web Development Framework
Bootstrap Web Development Framework
 
Web Development Intro
Web Development IntroWeb Development Intro
Web Development Intro
 
PhDigital Bootcamp: Web Development Concepts
PhDigital Bootcamp: Web Development ConceptsPhDigital Bootcamp: Web Development Concepts
PhDigital Bootcamp: Web Development Concepts
 
PhDigital Bootcamp: Digital Product Management
PhDigital Bootcamp: Digital Product ManagementPhDigital Bootcamp: Digital Product Management
PhDigital Bootcamp: Digital Product Management
 
Digital and Social Certifications
Digital and Social CertificationsDigital and Social Certifications
Digital and Social Certifications
 
MiLab Presentation 2018
MiLab Presentation 2018MiLab Presentation 2018
MiLab Presentation 2018
 
Is Your Curriculum Digital Enough?
Is Your Curriculum Digital Enough?Is Your Curriculum Digital Enough?
Is Your Curriculum Digital Enough?
 
Fundamentals of Digital/Online Media
Fundamentals of Digital/Online MediaFundamentals of Digital/Online Media
Fundamentals of Digital/Online Media
 
Bringing Digital Into the Curriculum - AEJMC 2017
Bringing Digital Into the Curriculum - AEJMC 2017Bringing Digital Into the Curriculum - AEJMC 2017
Bringing Digital Into the Curriculum - AEJMC 2017
 
Responsive Design
Responsive DesignResponsive Design
Responsive Design
 
The World of Web Development - 2017
The World of Web Development - 2017The World of Web Development - 2017
The World of Web Development - 2017
 
Why Should Communicators Learn to Code?
Why Should Communicators Learn to Code?Why Should Communicators Learn to Code?
Why Should Communicators Learn to Code?
 
Engaging Audiences with Social Media
Engaging Audiences with Social MediaEngaging Audiences with Social Media
Engaging Audiences with Social Media
 

Recently uploaded

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 

Recently uploaded (20)

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 

Handout - Introduction to Programming

  • 1. 1 CodeActually Dr. Cindy Royal Texas State University School of Journalism and Mass Communication Introduction to Programming for Communicators ¡ JavaScript is a scripting language commonly implemented as part of a web browser in order to create enhanced user interfaces and dynamic websites. ¡ JavaScript is not the same as Java. ¡ Can be run client side or server-­‐side (Node.js – a JavaScript environment). ¡ Foundation for code libraries like JQuery. For the first series of exercises, we’ll be practicing in Chrome’s console. This is an environment that let’s you run code and see the result. Later, we will be implementing JavaScript in html pages using JSFiddle. In Chrome, choose View, Developer Tools and click on the Console tab. Or Ctrl-­‐click on the screen and choose Inspect Element. Normally, these commands would be in a .js file or encapsulated in the <script> tag in an html document. But we are just practicing with concepts in this demonstration. Your First Program Write the string “Hello World!” console.log("Hello World!"); document.write("Hello World!"); Don’t worry if you see “undefined” in the console after the code returns. The console is attempting to determine the type that the code returns, and in most cases in our exercises that is “undefined.” console.log logs to the console. document.write writes to the document. Try them both. Objects, Properties and Methods For this exercise, we will mostly be using the console object to write code to the console. console.log(“info goes here”); Later we will use the document.write method to write to the html document. We do this by calling the document object and the write method. Basic JavaScript Syntax End lines with semicolon ; Put arguments/parameters in parentheses ( )
  • 2. 2 Period (.) between object and method or property. Strings in quotation marks " Unlike other languages, you do not have to declare a type when instantiating a variable. Some objects are built-­‐in (i.e. document, window), some can be defined. Data Types String, Number, Boolean, Array, Object, Null, Undefined -­‐ programming languages have syntax and functions that work with a variety of data types. We will mainly be concerned with strings and numbers, later adding booleans and arrays. Length Length is a string property that returns the length of the string. console.log("Hello World!".length); This returns a number that is the length of that string, including the space. Concatenation Use concatenation to join strings. The empty space between the quotation marks (" ") represents a space. The plus sign is the concatenation operator. console.log("Hello" + " " + "Cindy!"); Variables Use variables to store numbers and strings. The var prefix is optional. var name = "Cindy"; console.log("Hello" + " " + name); and var firstname = "Cindy"; var lastname = "Royal"; console.log(firstname + " " + lastname);
  • 3. 3 Math and numbers Operators and Math Within your script tag, try the following individually. You will see the different operators for math functions. console.log(3+4); console.log (3-4); console.log (3*4); console.log (3/4); console.log(3%4); The “%” operator is the modulo that shows the remainder of division calculation. Substrings I’m using these scripts to see what my JLo name would be, finding the first character of my first name and the first two characters of my last name. var firstname = "Cindy"; var lastname = "Royal"; console.log(firstname.substring(0,1) + lastname.substring(0,2)); or var first = "Cindy".substring(0,1); var last = "Royal".substring(0,2); console.log(first + last); Notice that we used a combination of variables and the substring method in two different ways to achieve the same result. Often in programming, there are multiple ways to solve a problem. Alerts and Prompts Alert -­‐ a general warning alert("Danger"); Confirm -­‐ answer yes or no before you can continue. confirm("Are you sure?");
  • 4. 4 Prompt -­‐ answer anything -­‐ creates variable prompt("What is your name?"); var name = prompt("What is your name?"); console.log("Hello " + name); Booleans and if statements Use booleans to test if something is true or false. Combine with an if/else statement to define different outcomes. Notice that the “if statements” actions are delineated with curly braces. You can also test for mathematical statements like greater than >, less than < or equal to ==. name="Cindy"; if(name.length==5){ console.log("Yes"); } else { console.log("No"); } or x=2; if(x>1) { console.log("Yes"); } else { console.log("No"); } Comparisons (= or ==) A single equal sign (=) indicates assignment, usually used to assign a value to a variable. If you are doing a test for comparison, then you use 2 equal signs (==). 2+2==4; var name="Cindy"; if(name=="Cindy";)...
  • 5. 5 Functions Functions allow you to define an operation and then use it later. Notice the statements in the function are enclosed in curly braces. Then we call the function using its name to execute it. There are two different ways to write a function. var hello = function () { var name = prompt("What is your name?"); console.log("Hello " + name); } hello(); or function hello() { var name = prompt("What is your name?"); console.log("Hello " + name); } hello();
  • 6. 6 Arguments You can add arguments in the parentheses of a function to pass information into it. var hello = function (a) { console.log("Hello " + a); } hello("Cindy"); or function hello(a) { console.log("Hello " + a); } hello("Cindy"); Loops Loops allow for iteration through a cycle. We will switch to document.write command to see the result in the browser window. The while loop is a statement that uses a variable as initializer, condition and iterator. var i=0; // initializer while (i<5) { //condition document.write("I am writing this five times"); i++; // iterator } Loops, continued The for loop reduces some of the coding by having three statements in the parentheses, separated by a semicolon; -­‐ an initializer, a condition to test and an iterator. for (var i=0; i<4; i++) { document.write("I am writing this 4 times<br />"); } Or if you want to get fancy, you can add the iterator to have a different number in each line. for (var i=0; i<4; i++) { document.write("This is time " + i + "<br />"); }
  • 7. 7 Arrays Arrays allow you to store a collection of information in a variable and then access it via its index number. Index numbers start with 0. Enclose elements of an array in square brackets. var favGroups = ["Old 97s", "Spoon", "Wilco"]; document.write(favGroups[1]); This accesses the item in the array in location 1. Notice that it isn’t the first item in the array. Arrays start with 0, so to access the first item, use favGroups[0]. You can use a loop to iterate through an array. Concatenate a break so the items appear on a different line. Your condition uses the length property of an array to determine how many items are in it. var i=0; var favGroups = ["Old 97s", "Spoon", "Wilco"]; while(i<favGroups.length){ document.write(favGroups[i] + "<br />"); i++; } Notice how we can add html items as a string. We are beginning to integrate html and JavaScript for interactivity. Objects Objects are similar to arrays except they store items in key/value pairs rather than accessing them by their index number. Instead of using square brackets, you use curly braces for objects. var bands; bands = { name: "Old 97s", city: "Dallas", genre: "alt-country" }; document.write(bands.name + ", " + bands.city + ", " + bands.genre);
  • 8. 8 We can use an array in conjunction with an object to add multiple elements to the object. var bands; bands = [ { name: "Old 97s", city: "Dallas", genre: "alt-country" }, { name: "Spoon", city: "Austin", genre: "Indie Rock" }, { name: "Wilco", city: "Chicago", genre: "alt-country" } ]; document.write(bands[1].name + ", " + bands[1].city + ", " + bands[1].genre); And we can loop through an object just like we did with an array. Your condition uses the length property of an object to determine how many items are in it. var bands; bands = [ { name: "Old 97s", city: "Dallas", genre: "alt-country" }, { name: "Spoon", city: "Austin", genre: "Indie Rock" },
  • 9. 9 { name: "Wilco", city: "Chicago", genre: "alt-country" } ]; for(var i=0; i<bands.length; i++) { document.write(bands[i].name + ", " + bands[i].city + ", " + bands[i].genre + "<br />"); } You will sometimes see data embedded in objects in JavaScript referred to as JSON (JavaScript Object Notation).
  • 10. Using JavaScript in an html document getElementById(); is a magical method that you can use to access parts of a Web page. We need to work with a web page, so that this function can manipulate the Document Object Model (DOM). The function below, when called, changes the innerHTML of the element with the id “first”. This is very powerful when combined with forms to ask a user for input to change something on a page. Let’s properly structure the document now to include the HTML5 doctype declaration, too. 10 <!DOCTYPE html> <html> <head> <title>My JavaScript</title> </head> <body> <p>Hello <span id="first">Cindy</span></p> <script> function nameChange() { document.getElementById('first').innerHTML = 'Jon'; } nameChange(); </script> </body> </html>
  • 11. Events An advanced use of JavaScript in an html document has to do with mouse events. An event is an interaction – onclick, onload, onmouseover, onmouseout. Simple: 11 <!DOCTYPE html> <html> <head> <title>My JavaScript</title> </head> <body> <h1 onclick="this.innerHTML='Good work!'">Click on this text!</h1> </body> </html> The “this” operator tells the code to operate on the current element. In a function: <!DOCTYPE html> <html> <head> <script> function changetext() { document.getElementById("new").innerHTML="You're a pro!"; } </script> </head> <body> <h1 id="new" onclick="changetext()">Click on this text!</h1> </body> </html> You will use events combined with getElementById() to create interactivity on your site.
  • 12. More advanced use of getElementById() with form This form requests your name, then it stores that info in a variable and presents it in the message below on the page. <!DOCTYPE html> <html> <head> <title>Fun With Forms</title> </head> <body> <form id="form1" action=" "/> <p>Name: <input type="text" id="newname" /></p> <input type="submit" value="Submit"> </form> <p>Hi <strong><span id="yourname">"Your Name Here"</span></strong>. Welcome to the site.</p> <script> document.getElementById("form1").onsubmit=function() { 12 var newName = document.forms["form1"]["newname"].value; document.getElementById("yourname").style.color = "red"; document.getElementById("yourname").innerHTML = newName; return false; // required to not refresh the page } </script> </body> </html> This code changes the innerHTML of the span tag in the html document to the text from the form. It also changes the color. We’ll get more practice with JavaScript in the charting exercise.
  • 13. Comments Developers use comments to leave notes in the code, provide instructions for other developers or to provide clues to certain techniques. It helps to organize code. Comments can also be used to temporarily remove and test code without having to delete it. With the script tag. 13 // This is a comment /* This is a multi-line comment */ Note: basic html comments are handled by <!-­‐-­‐ -­‐-­‐>. This would be used in html documents outside the <script> tag. Now you have a basic understanding of programming concepts. There are many ways to go from here. You can learn more about coding Web pages with HTML/CSS, so that you can integrate interactive concepts. Or you can move into the world of JQuery to learn how to take advantage of coding libraries.