JavaScript Basics
Bashar Al shboul
Adopted from Mendel
Rosenblum
WAPE Lecture Notes - JavaScript Basics 1
What is JavaScript?
From Wikipedia:
... high-level, dynamic, untyped, and interpreted programming language
... is prototype-based with first-class functions, …
... supporting object-oriented, imperative, and functional programming
... has an API for working with text, arrays, dates and regular expressions
● Not particularly similar to Java: More like C crossed with Self/Scheme
○ C-like statements with everything objects, closures, garbage collection, etc.
● Also known as ECMAScript
WAPE Lecture Notes - JavaScript Basics 2
Some thoughts about JavaScript
● Example of a scripting language
○ Interpreted, less declaring of things, just use them (popular today: e.g. python)
● Seems like it was designed in a rush
○ Some “Good Parts”, some not so good
○ Got a bad reputation
● Many programmers use a subset that avoids some common problems
● "use strict"; tweaks language to avoid some problematic parts
● Language being extended to enhance things: New ECMAScript every year!
○ Transpiling common so new features used: e.g ECMAScript Version N, TypeScript
● Code quality checkers (e.g. jslint, jshint, eslint) widely used
WAPE Lecture Notes - JavaScript Basics 3
Good news if you know C - JavaScript is similar
i = 3; if (i < 3) {
i = foobar(i);
i = i * 10 + 3 + (i / } else {
10);
while (i >= 0) i = i * .02;
{ sum += // }
i*i; i--; Comment
Most C operators work:
}
* / % + - ! >= <= > < &&
|| ?:
for (i = 0; i < 10; i++)
function foobar(i) { return
{
i;} continue/break/return
WAPE Lecture Notes - JavaScript Basics 4
}
JavaScript has dynamic typing
var i; // Need to define variable ('use strict';), note:
untyped
typeof i == 'undefined'// It does have a type of ‘undefined’
i = 32; // Now: typeof i == typeof 32 == 'number'
i = "foobar" // Now: typeof i == typeof 'foobar' ==
; 'string'
i = true; // Now typeof i == 'boolean'
● Variables have the type of the last thing assigned to it
● Primitive types: undefined, number, string, boolean, function, object
WAPE Lecture Notes - JavaScript Basics 5
Variable scoping with var: Lexical/static
scoping
Two scopes: Global and function local All var statements hoisted to top
of scope:
var globalVar;
function foo() {
function var x;
x = 2;
foo() {
// Same as:
var
localVar; function foo()
if (globalVar > 0) {
{ var localVar2 var
x = 2
= 2; x; localVar2
} declaration is
// localVar2 is valid hoisted here but
WAPE Lecture Notes - JavaScript Basics 6
here has value
Var scope problems
● Global variables are bad in browsers - Easy to get conflicts between modules
● Hoisting is JavaScript's default behavior of moving all declarations to the top of the current
scope (to the top of the current script or the current function).
● Hoisting can cause confusion in local scopes (e.g., access before value set)
function() {
[Link]('Val is:', val);
...
for(var i = 0; i < 10; i++) {
var val = "different string"; // Hoisted to func start
● Some JavaScript guides suggest always declaring all var at function start
● ES6 introduced non-hoisting, scoped let and const with explicit scopes
● Some coding environments ban var and use let or const instead
WAPE Lecture Notes - JavaScript Basics 7
Var scope problems
● Global variables are bad in browsers - Easy to get conflicts between modules
● Hoisting is JavaScript's default behavior of moving all declarations to the top of the current
scope (to the top of the current script or the current function).
● Hoisting can cause confusion in local scopes (e.g., access before value set)
function() {
[Link]('Val is:', val); // Syntax error
...
for(var i = 0; i < 10; i++) {
let val = "different string"; // Works
● Some JavaScript guides suggest always declaring all var at function start
● ES6 introduced non-hoisting, scoped let and const with explicit scopes
● Some coding environments ban var and use let or const instead
WAPE Lecture Notes - JavaScript Basics 8
number
type
number type is stored in floating point (i.e. double in
C)
MAX_INT = (253 - 1) = 9007199254740991
Some oddities: NaN, Infinity are numbers
1/0 == Infinity
[Link](-1) ==
NaN
Watch out:
//
(0.1 + 0.2) == 0.3 0.30000000000000004
bitwise operators (e.g. ~, &, |, ^, >>, <<, >>>) are
is false
32bit! WAPE Lecture Notes - JavaScript Basics 9
string
type
string type is variable length (no char type)
let foo = 'This is a test'; // can use "This is a
test" [Link] // 14
+ is string concat operator
foo = foo + 'XXX'; // This is a testXXX
Lots of useful methods: indexOf(), charAt(), match(), search(),
replace(), toUpperCase(), toLowerCase(), slice(),
substr(), …
'foo'.toUpperCase() // 'FOO'
WAPE Lecture Notes - JavaScript Basics 10
boolean
type
● Either true or false
● Language classifies values as either truthy or falsy
○ Used when a value is converted to a boolean e.g. if (foo) { … )
● Falsy:
false, 0, "", null, undefined, and NaN
● Truthy:
Not falsy (all objects, non-empty strings, non-zero
numbers, functions, etc.)
WAPE Lecture Notes - JavaScript Basics 11
undefined and
null
● undefined - does not have a value assign
let x; // x has a value of undefined
x = undefined; // It can be explicitly store
typeof x == 'undefined'
● null - a value that represents whatever the user wants it to
Use to return special condition (e.g. no value)
typeof null == ‘object’
● Both are falsy but not equal:
● null == undefined; true
● null !== undefined; false
WAPE Lecture Notes - JavaScript Basics 12
Equality Operator
• The triple equals (===) not only checks the value, but the type
if( '5' !== 5 ){
return false
}else{
return true;
}
• != will only check value regardless of operands type
• !== is used to compare both value & type of 2 operands that are being
compared to each other.
WAPE Lecture Notes - JavaScript Basics 1
3
function
type
var foobar = function // Same as function
foobar(x) { if (x <= 1) { foobar(x)
return 1;
}
return x*foobar(x-1);
}
typeof foobar == ‘function’; [Link] == 'foobar'
● Function definitions are hoisted (i.e. can use before definition)
● Can be called with a different number arguments than definition
○ Array arguments variable (e.g. arguments[0] is first
argument)
○ Unspecified arguments have value undefined
● All functions return a value (default is undefined)
WAPE Lecture Notes - JavaScript Basics 14
First class function
• A programming language is said to have First-class functions when
functions in that language are treated like any other variable
• A function can be passed as an argument to other functions, can be
returned by another function and can be assigned as a value to a variable.
• We assigned an Anonymous Function in a Variable, then we used that
variable to invoke the function by adding parentheses () at the end
WAPE Lecture Notes - JavaScript Basics 1
5
First class function example
let aFuncVar = function (x) {
[Link]('Func called with',
x); return x+1;
};
myFunc(aFuncVar
);
function myFunc(routine) { // passed as a param
[Link]('Called with', [Link]()); Output
Called with function (x) {
let retVal = routine(10); [Link]('Func called with',
x);
[Link]('retVal', retVal); return x+1;
return retVal; }
Func called with 10
} WAPE Lecture Notes - JavaScript Basics retVal 11 14
object type
● Object is an unordered collection of name-value pairs called properties
let foo = {};
let bar = {name: "Alice", age: 23, state: "California"};
● Name can be any string: let x = { "": "empty", "---":
"dashes"}
● Referenced either like a structure or like a hash table with string keys:
[Link] or bar["name"]
x["---"] // have to use hash format for illegal names
[Link] == undefined
● Global scope is an object in browser (i.e. window[prop])
WAPE Lecture Notes - JavaScript Basics 17
Properties can be added, removed, enumerated
● To add, just assign to the property:
let foo = {};
[Link] = // [Link] returns
"Fred"; "Fred"
● To remove use delete:
let foo = {name: "Fred"};
delete [Link]; // foo is now an empty object
● To enumerate use [Link]():
[Link]({name: "Alice", age: 23}) = ["name",
"age"] WAPE Lecture Notes - JavaScript Basics 18
Array
s let anArr = [1,2,3];
Are special objects: typeof anArr == 'object'
Indexed by non-negative integers: (anArr[0] == 1)
Can be sparse and polymorphic: anArr[5]='FooBar'; //[1,2,3,,,'FooBar']
Oddity:
- Can store properties like objects, add properties (e.g. [Link] = 'Foo’)
- Some properties have implications, update properties directly (e.g. [Link]
= 0;)
Have many methods: [Link] == 3
push, pop, shift, unshift, sort, reverse, splice
WAPE Lecture Notes - JavaScript Basics 19
Dates
let date = new Date();
Are special objects: typeof date == 'object'
The number of milliseconds since midnight January 1, 1970 UTC.
All dates are internally stored in UTC.
• All dates are internally stored in UTC. Timezone needed to convert.
• Not good for fixed dates (e.g. birthdays). Timezone conversion might shift the date
unintentionally.
Many methods for returning and setting the data object. For example:
[Link]() = 1452359316314
[Link]() = '2016-01-09T17:08:36.314Z'
[Link]() = '1/9/2016, 9:08:36 AM'
WAPE Lecture Notes - JavaScript Basics 20
Regular Expressions
let re = /ab+c/; or let re2 = new RegExp("ab+c");
Defines a pattern that can be searched for in a string
String Object " " : search(), match(), replace(), and split()
RegExp Object: exec() and test()
Uses:
Searching: Does this string have a pattern I’m interested in?
Parsing: Interpret this string as a program and return its components
WAPE Lecture Notes - JavaScript Basics 21
Regular Expressions
[ ] Square brackets specify a set of characters you wish to match.
[^abc] means any character except a or b or c ((invert) the character set by using
caret ^ symbol at the start of a square-bracket.)
[^0-9] means any non-digit character.
. A period matches any single character (except newline '\n').
^ The caret symbol ^ is used to check if a string starts with a certain character.
$ The dollar symbol $ is used to check if a string ends with a certain character.
* The star symbol * matches zero or more occurrences of the pattern left to it.
+ The plus symbol + matches one or more occurrences of the pattern left to it.
? The question mark symbol ? matches zero or one occurrence of the pattern left to it.
\d Matches any decimal digit. Equivalent to [0-9]
\s Matches where a string contains any whitespace character. Equivalent to [ \t\
n\r\f\v]
WAPE Lecture Notes - JavaScript Basics 22
Regular Expressions by example - search/test
/ // Returns true if string str has the substr
HALT/.test(str); HALT
/halt/
/[Hh]alt // Same but
[A-Z]/.test(str); //ignore
Returnscase
true if str either “Halt L” or
[Link](str);
“halt L”
'XXX abbbbbbc'.search(/ // Returns 4 (position of ‘a’)
ab+c/);
'XXX ac'.search(/ab+c/); // Returns -1, no match
'XXX ac'.search(/ab*c/); // Returns 4
'12e34'.search(/[^\d]/); // Returns
2 // Returns
'foo: bar;'.search(/...\s*:\s*...\ 0
s*;/);
WAPE Lecture Notes - JavaScript Basics 23
Regular Expressions - exec/match/replace
let str = "This has 'quoted' words like 'this'"; let re = /'[^']*'/g;
[Link](str); // Returns ["'quoted'", index: 9, input: …
[Link](str); // Returns ["'this'", index: 29, input: …
[Link](str); // Returns null
[Link](/'[^']*'/g); // Returns ["'quoted'", "'this'"]
[Link](/'[^']*'/g, 'XXX'); // Returns:
'This has XXX words with XXX.'
exec() returns an array containing all the matched groups. It executes a search for a match in
a specified string. If it finds a match, it returns an array. Otherwise, it returns null.
/g used to find all the occurrences of the pattern instead of stopping after the first match i.e it
performs global match.
Exceptions -
try/catch
● Error reporting frequently done with exceptions
Example:
If we try to call a function that does not exist such as
nonExistentFunction();
Terminates execution with error:
Uncaught ReferenceError:
nonExistentFunction is not defined
Instead, an Exception go up stack: Catch exceptions with try/catch
try {
nonExistentFunction();
} catch (err) { // typeof err 'object’
[Link]("Error call func", [Link], [Link]);
}
WAPE Lecture Notes - JavaScript Basics 25
Exceptions -
throw/finally
● Raise exceptions with throw statement
try {
throw "Help!";
} catch (errstr) { // errstr ===
"Help!" [Link]('Got
exception', errstr);
} finally {
// This block is executed after
try/catch
}
● Conventions are to throw sub-classes of Error
object WAPE Lecture Notes - JavaScript Basics 26
Getting JavaScript into a web page
● By including a separate file:
<script type="text/javascript" src="[Link]"></script>
● Inline in the HTML:
<script type="text/javascript">
//<![CDATA[
Javascript goes here...
//]]>
</script>
WAPE Lecture Notes - JavaScript Basics 27