Chapter 5 JS
Chapter 5 JS
Wollo University
Outline
Kombolcha Institute of Technology
College of Informatics 2
CS380 CS380
1
27-Jan-20
CS380 CS380
2
27-Jan-20
similarities:
both are interpreted, not compiled
both are relaxed about syntax, rules, and types
CS380 CS380
JS <3
CS380 CS380
3
27-Jan-20
CS380 CS380
4
27-Jan-20
5
27-Jan-20
CS380 CS380
function changeText() {
//grab or initialize text here
Attribute Property or style object
// font styles added by JS:
color color text.style.fontSize = "13pt";
text.style.fontFamily = "Comic Sans MS";
padding padding text.style.color = "red"; // or pink?
} JS
background-color backgroundColor
border-top-width borderTopWidth
Font size fontSize
Font famiy fontFamily
CS380 CS380
6
27-Jan-20
variables are declared with the var keyword (case integers and real numbers are the same type (no int
sensitive) vs. double)
types are not specified, but JS does have types same operators: + - * / % ++ -- = += -= *= /=
("loosely typed") %=
Number, Boolean, String, Array, Object, similar precedence to Java
Function, Null, Undefined many operators auto-convert types: "2" * 3 is 6
can find out a variable's type by calling typeof
CS380 CS380
identical to Java's comment syntax methods: abs, ceil, cos, floor, log,
max, min, pow, random, round, sin,
recall: 4 comment syntaxes
sqrt, tan
HTML: <!-- comment -->
properties: E, PI
CSS/JS/PHP: /* comment */
Java/JS/PHP: // comment
PHP: # comment
CS380 CS380
7
27-Jan-20
exist === and !== are strict equality tests; checks both
null : exists, but was specifically assigned an type and value
empty or null value "5.0" === 5 is false
Why does JavaScript have both of these?
CS380 CS380
CS380 CS380
8
27-Jan-20
var s1 = "hello"; do {
var s2 = ""; statements;
for (var i = 0; i < s.length; i++) { } while (condition);
s2 += s1.charAt(i) + s1.charAt(i); JS
}
// s2 stores "hheelllloo" JS break and continue keywords also behave as in
Java
CS380 CS380
CS380 CS380
9
27-Jan-20
escape sequences behave as in Java: \' \" \& \n \t var s = "the quick brown fox";
var a = s.split(" "); // ["the", "quick", "brown", "fox"]
\\ a.reverse(); // ["fox", "brown", "quick", "the"]
s = a.join("!"); // "fox!brown!quick!the"
converting between numbers and Strings: JS
var count = 10;
var s1 = "" + count; // "10"
var s2 = count + " bananas, ah ah ah!"; // "10 bananas, ah split breaks apart a string into an array using a
ah ah!"
var n1 = parseInt("42 is the answer"); // 42 delimiter
var n2 = parseFloat("booyah"); // NaN JS
can also be used with regular expressions (seen later)
accessing the letters of a String: join merges an array into a single string, placing a
var firstLetter = s[0]; // fails in IE
var firstLetter = s.charAt(0); // does work in IE
delimiter between them
var lastLetter = s.charAt(s.length - 1); JS
CS380
10
27-Jan-20
CS380
11