Introduction to JavaScript
How to write content for a webpage using HTML
How to add styles to a webpage using CSS
and linking a CSS
file to an
HTML
file
How to inspect the HTML
and CSS
of web pages in the browser
Now that we know how to add content and styles to a web page, lets explore how to add responsive behavior
These slides will introduce the basics of the JavaScript language:
Soon, we'll use these building blocks to dynamically update what you see on a web page in response to clicks, text input, timers, etc.
Client-side script: Code runs in browser after page is sent back from server. Often, this code manipulates the page or responds to user actions.
You don't need to have a server running to run client-side code - you can get started programming in JavaScript (our client-side scripting language) right away in your browser of choice!
A lightweight programming language ("scripting language")
Created in 1995 by Brendan Elch (original prototype created in 10 days and called LiveScript)
Used to make web pages interactive:
A web standard (but not supported identically by all browsers )
NOT related to Java other than name and some syntactic similarities...
Can be used in the browser, Adobe Acrobat, Adobe Photoshop, embedded computers, the Unix terminal, etc. (we will be using it in the browser)
Interpreted, not compiled (huh?)
More relaxed syntax and rules
JavaScript's key construct is the function rather than the object/class.
Contained within a web page and integrates with its HTML/CSS
content
<script>
<script src="filename"></script>
<script src="example.js"></script>
The script
tag should be placed in the HTML
page's
head
.
Note: Before HTML5, it was required to use a
type="text/javascript"
in the script
tag. In HTML5, this is
recommended against, since it's a
redundant MIME type.
All JavaScript code used in the page should be stored in a separate .js
file
JS code can be placed directly in the HTML
file's body
or
head
(like CSS
), but this is poor code quality. You should always separate content,
presentation, and behavior
Here's an example.html linked to this example.js - feel free to use these to practice with!
As an interpreted programming language, JS is great to interact with a line at a time (similar to Python, but very different than Java). Where do you start?
The easiest way to dive in is with the browser's Console tab in the same inspector tool you've used to inspect your HTML/CSS.
Until we learn functions to interact with the HTML DOM with JS, we recommend experimenting with the following code examples using this console to get comfortable with the fundamental syntax and behavior of the language. Try the recommended practice problems along the way!
alert
alert("message");
alert("IE6 detected. Suck-mode enabled.");
A JS command that pops up a dialog box with a message - not ideal in practice, but a good debugging tool when first learning JS
console.log
Used to output values to the browser console (can view in your browser's dev tools under "Console").
Often preferred over alert
to debug JS programs.
console.log("message");
console.log("The answer is: " + 42);
// single-line comment
/* multi-line comment */
Identical to Java's comment syntax
Recall: 3 comment syntaxes
HTML: <!-- comment -->
CSS/Java/JS: /* comment */
Java/JS: // comment
For functions and program files, we'll use JSDoc commenting, which will be introduced when we learn how to write JS functions (next lecture).
Practice:
commentSyntax
,
commentary
let name = expression;
let level = 23;
let accuracyRate = 0.99;
let name = "Pikachu";
Variables are declared with the let
keyword (case-sensitive). You may also see var
used instead of let
- this is an older convention, and you should use let
in this class.
Types are not specified, but JS does have types ("loosely-typed")
Number
, Boolean
, String
,
Array
, Object
, Function
, Null
,
Undefined
If you've programmed in a statically-typed language like Java, you will recall that when declaring variables, you must specify their type which must always stay the same.
boolean isValid = "hello!"; // error
In a dynamically-typed language like JavaScript, you don't need to specify the
type (just use let
or const
) and you may change the type the variable refers to later in execution.
let isValid = true; // no error
isValid = "hello!";
isValid = 1;
This may seem to imply fewer errors in JS, but it's not uncommon to run into subtle (silent) bugs in your JS programs as a result!
Since ECMA6, JavaScript has a special keyword to declare "constant" values. You should
use these over the let
keyword for variables that are not intended to ever
be updated (similar to constants in Java).
Use UPPER_CASING
naming conventions to
denote const
in JS.
let month = 12;
month = 1; // no error
const COOLEST_CLASS = "CSE154";
COOLEST_CLASS = "clazz"; // error
These can help avoid some of the bugs
mentioned on the previous slide (an error occurs when trying to reassign a
const
).
let enrollment = 99;
let medianGrade = 2.8;
let credits = 5 + 4 + (2 * 3);
Integers and real numbers are the same type (no int
vs.
double
). All numbers in JS are floating point numbers.
Same operators: + - * / % ++ -- = += -= *= /= %=
Similar precedence to Java
Many operators auto-convert types: "2" * 3
is 6
let nickName = "Sparky O'Sparkz"; // "Sparky O'Sparks"
let fName = nickName.substring(0, s.indexOf(" ")); // "Sparky"
let len = nickName.length; // 15
let name = 'Pikachu'; // can use "" or ''
Methods:
charAt
,
charCodeAt
,
fromCharCode
,
indexOf
,
lastIndexOf
,
replace
,
split
,
substring
,
toLowerCase
,
toUpperCase
Escape sequences behave as in Java: \' \" \& \n \t \\
To convert between Numbers and Strings:
let count = 10; // 10
let stringedCount = "" + count; // "10"
let puppyCount = count + " puppies, yay!"; // "10 puppies, yay!"
let magicNum = parseInt("42 is the answer"); // 42
let mystery = parseFloat("Am I a number?"); // NaN
To access characters of a String s
, use s[index]
or
s.charAt(index)
:
let firstLetter = puppyCount[0]; // "1"
let fourthLetter = puppyCount.charAt(3); // "p"
let lastLetter = puppyCount.charAt(puppyCount.length - 1); // "!"
While Strings in JS are fairly similar to those you'd use in Java, there are a few special cases that you should be aware of.
length
is a property (not a method, as it is in Java)+
: 1 + 1
is 2
, but "1" +
1
and 1 + "1"
are both "11"
!
Practice: repeat
, containsTwice
let rand1to10 = Math.floor(Math.random() * 10 + 1);
let three = Math.floor(Math.PI);
Methods: abs
,
ceil
,
cos
,
floor
,
log
,
max
,
min
,
pow
,
random
,
round
,
sin
,
sqrt
,
tan
Properties: E
, PI
for loop
(same as Java)for (initialization; condition; update) {
statements;
}
let sum = 0;
for (let i = 0; i < 100; i++) {
sum = sum + i; // same as sum += i;
}
let s1 = "It's a-me, Mario!";
let s2 = "";
for (let i = 0; i < s.length; i++) {
s2 += s1[i] + s1[i];
}
// s2 stores "IItt''ss aa--mmee,, MMaarriioo!!"
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
Identical structure to Java's if/else
statements
JavaScript allows almost anything as a condition
Practice:
rockPaperScissors
while (condition) {
statements;
}
do {
statements;
} while (condition);
break
and continue
keywords also behave as in Java but do not
use them in this class!
Practice:
loopMystery6
Relational: > < >= <=
Logical: && || !
Equality: == != === !==
5 < "7"
42 == 42.0
"5.0" == 5
===
and !==
are strict equality tests; checks both
type and value: "5.0" === 5
is false
. It's
usually a good idea to use ===
instead of ==
.154 === 154.0
evaluate to?Helpful JavaScript equality table!
let iLikeJS = true;
let ieIsGood = "IE6" > 0; // false
if ("web dev is great") { /* true */ }
if (0) { /* false */ }
if (1) { /* true */ }
Any value can be used as a Boolean
false
, 0
, NaN
,
""
, null
, and undefined
Understanding what is "falsey" vs. "truthy" takes patience and practice.
When in doubt, check in the browser console!
null
and undefined
let foo = null;
let bar = 9;
let baz;
/* At this point in the code,
* foo is null
* bar is 9
* baz is undefined
*/
undefined
: declared but has not yet been assigned a value
null
: exists, but was specifically assigned an empty value or
null
. Expresses intentional a lack of identification.
A good motivating overview of
null
vs.
undefined
let name = []; // empty array
let names = [value, value, ..., value]; // pre-filled
names[index] = value; // store element
let types = ["Electric", "Water", "Fire"];
let pokemon = []; // []
pokemon[0] = "Pikachu"; // ["Pikachu"]
pokemon[1] = "Squirtle"; // ["Pikachu", "Sqiurtle"]
pokemon[3] = "Magikarp"; // ["Pikachu", "Sqiurtle", undefined, "Magikarp"]
pokemon[3] = "Gyarados"; // ["Pikachu", "Sqiurtle", undefined, "Gyarados"]
Two ways to initialize an array
length
property (grows as needed when elements are added)
let a = ["Mario", "Luigi"]; // [Mario, Luigi]
a.push("Koopatroopa"); // [Mario, Luigi, Koopatroopa]
a.unshift("Bowser"); // [Bowser, Mario, Luigi, Koopatroopa]
a.pop(); // [Bowser, Mario, Luigi]
a.shift(); // [Mario, Luigi]
a.sort(); // [Luigi, Mario]
Array serves as many data structures: list, queue, stack, ...
Methods: concat
,
join
,
pop
,
push
,
reverse
,
shift
,
slice
,
sort
,
splice
,
toString
,
unshift
push
and pop
add/remove from backshift
and unshift
add/remove from frontshift
and pop
return the element that is removed
Practice:
findMin
,
switchPairs
split
and join
let s = "the quick brown fox";
let a = s.split(" "); // ["the", "quick", "brown", "fox"]
a.reverse(); // ["fox", "brown", "quick", "the"]
s = a.join("!"); // "fox!brown!quick!the"
split
breaks apart a String into an array using a delimiter
let a = s.split(/[ \t]+/);
join
merges an array into a single String, placing a delimiter between
them
As you write JS programs, you may will run into some silent
bugs resulting from odd typing behavior in JS. Automatic type conversion, or coersion,
is a common, often perplexing, source of JS bugs (even for experienced JS programmers).
Why does it happen? JS was designed to "work" as intuitively as possible without requiring the strict types.
Why is this important to be aware of? You'll be writing programs which use variables and conditional logic. Knowing what is considered truthy/false and how types are evaluated (at a high level) can make you a much happier JS developer (some practice)
Examples of some "less-intuitive" evaluations:
2 < 1 < 2;
// true
0 + "1" + 2;
// "012"
[] + [];
// ""
"1" / null;
// Infinity
Java | JS | Python | |
---|---|---|---|
Compiled vs. Interpreted | Compiled | Interpreted | Interpreted |
Typing | Strong | Loose | Loose |
Variable Declaration | Must be declared before use | Does not need to be declared before use | Does not need to be declared before use |
Key Construct | Classes (OOP) | Function | Function |
Review programming basics: using variables, arrays, loops, if-statements, and functions
Go over some JavaScript tutorials - there are many great ones!
Practice! We now have JavaScript problems on Practice-It (80+ problems) and its sister site CodeStepByStep (200+ problems).
Check out cool examples of JavaScript on the web!