JavaScript Lecture
SDSLabs
We are not covering every detail from the ground up
about JavaScript, since that would be too boring
Here we will focus on
what makes this
language special
What is JavaScript?
WHAT IS JAVASCRIPT USED FOR?
- Dynamically load content from the server without interfering the current page
- Manipulate HTML elements in a document
- Play music and videos on the web page
- Awesome animations
- Make simple games for the web
Basic Concepts
About Variables
A variable is a named
container for a value
The name that refers to a variable
is sometime called an identifier
Definition
var x;
var y = "Hello JS!";
var z;
x
z
These red boxes are variables, and each of them has a name (identifier)
undefined
"Hello JS!"
undefined
y
Any JavaScript value can be contained within these boxes
var x;
var y = "Hello JS!";
var z;
z = false;
z = 101;
x
z
undefined
"Hello JS!"
101
y
We can assign another value to a variable later after its creation
Reserved Words
Some keywords can not be used as variable names:
null true false break do instanceof typeof
case else new var catch finally return void
continue for switch while debugger function
this with default if throw delete in try
class enum extends super const export import
implements let private public yield
interface package protected static
We don't need to remember them all. Just be aware of the
possible cause for some SyntaxError exceptions in our program.
Basic Concepts
About Values & Types
A value represents the most
basic data we can deal with
Definition
A type is a set of data values,
and there are exactly 6 types
Type
value
:: {
}
v1
v2
v3
,
,
...
,
undefined
Undefined
null
Null
Boolean
true
false
Number
.33
-3.14
NaN
7e-2
011
(IEEE754 64-bit doubles)
There are 5 primitive (non-Object) types
String
""
"\n"
"Hello world!"
"哈囉。"
"\""
(Any finite ordered sequence of 16-bit unsigned integers)
'w Single Quotes'
Any value here is called a primitive value
0x101
-Infinity
And then there is the "Object" type
Object
Any value of this type is a reference to some “object”;
sometimes we would simply call such value an object
ref:0x2f4b90
"a str val"
x
y
1234
addr: 0x2f4b90
true
foo
bar
addr: 0x183da5
ref:0x48264e
ref:0x183da5
Definition
An object is a
collection of properties
A property is a
named container for a value
The name of a property is called a key;
thus, an object can be considered as
a collection of key-value pairs.
There are similar concepts in other programming languages,
e.g., Map, Dictionary, Associative Array, Symbol Table, Hash Table, ...
Definition
Add/Get/Set/Remove A Property
We can dynamically modify an object after its creation
var obj = {
"1": "Hello",
"3": "Good",
x : "JavaScript",
foo: 101,
bar: true
};
obj["2"] = "World"; // *1 Add & Set
obj["1"]; // *2 Get -> "Hello"
obj[2]; // *3 Get -> "World"
obj[3]; // *4 Get -> "Good"
obj.foo = 202; // *5 Set
Don't Forget Any Value Of The
Object Type Is Actually A “Reference”
var x = { a: 100 };
var y = { a: 100 };
100
a
addr: 0x440892
ref:0x440892
x
100
a
addr: 0x3c980c
ref:0x3c980c
y
Similar to the “pointer” / “address” concept
in programming languages like C or C++
Don't Forget Any Value Of The
Object Type Is Actually A “Reference”
var x = { a: 100 };
var y = { a: 100 };
var z = y;
x === y; // false
y === z; // true
100
a
addr: 0x440892
x
100
a
addr: 0x3c980c
y
z
ref:0x440892
ref:0x3c980c
ref:0x3c980c
Don't Forget Any Value Of The
Object Type Is Actually A “Reference”
var x = { a: 100 };
var y = { a: 100 };
var z = y;
x === y; // false
y === z; // true
z.a = 200;
100
a
addr: 0x440892
x
200
a
addr: 0x3c980c
y
z
ref:0x440892
ref:0x3c980c
ref:0x3c980c
Don't Forget Any Value Of The
Object Type Is Actually A “Reference”
var x = { a: 100 };
var y = { a: 100 };
var z = y;
x === y; // false
y === z; // true
z.a = 200;
x.a; // 100
y.a; // 200
z.a; // 200
100
a
addr: 0x440892
x
200
a
addr: 0x3c980c
y
z
ref:0x440892
ref:0x3c980c
ref:0x3c980c
Basic Concepts
About Functions
Definition
A function is an object
that is callable
var a = 7;
var sayhi = function (name) {
var a = "Hello " + name;
console.log(a);
return a;
};
Function Expression
Any function in JavaScript is first-class, which can be assigned
to a variable or passed as an ordinary value to another function.
Function Invocation
A pair of parentheses invokes the preceding function;
the values of zero or more arguments are passed in.
Each time a function is called/invoked, it has its own variable scope
with local variables and arguments filled with corresponding values
var a = 7;
var sayhi = function (name) {
var a = "Hello " + name;
console.log(a);
return a;
};
sayhi("J"); // "Hello J"
a; // 7
Function Not Returning A Value
A function does not necessarily
need to return a value explicitly.
When that is the case, the “undefined” value is returned.
var f = function () {
return;
};
var g = function () {
};
var foo = f();
foo; // undefined
g(); // undefined
// The cat object has three properties
// cat.age, cat.meow, and cat.sleep
var cat = {
age: 3,
meow: function () {}
};
cat.sleep = function () {};
// We would say that cat.meow and
// cat.sleep are "methods" of cat
Methods of An Object
Some Objects Are
Called “Arrays”
var w = [
"test",
1234,
{},
[],
"hi"
];
w[4]; // "hi"
Array Initialiser (Array Literal)
The notation using a pair of square brackets
to create/initialize a JavaScript Array object.
var w = new Array(5);
w[0] = "test";
w[1] = 1234;
w[2] = new Object();
w[3] = new Array();
w[4] = "hi";
w[4]; // "hi"
The code on the left-hand side has exactly the
same result as the one on the right-hand side
Append New Elements To An Array
var arr = [ "test", 1234, {}, [], "hi" ];
arr.push("sixth"); // 6
arr.length; // 6
arr[5]; // "sixth"
arr[7] = 012; // 10
arr.length; // 8
arr[6]; // undefined
arr[7]; // 10
arr[8]; // undefined
arr.length; // 8
There is a method “push” for all Array objects.
Or you can just assign a value to the corresponding slot.
Enumerate All Elements In An Array (1/3)
var arr = [ "test", 1234, {}, [], "hi" ];
for (var i = 0; i < arr.length; i += 1) {
console.log(arr[i]);
}
There is a special property “length” for any Array object.
NOTE: A “For-loop” is not always recommanded
for enumerating all elements in an array, because...
Enumerate All Elements In An Array (2/3)
var arr = [ "test", 1234, {}, [], "hi" ];
arr.forEach(function (val /*, i, arr*/) {
console.log(val);
});
// undefined
There is a special method “forEach” for any Array object.
The “forEach” method is much nicer...
Enumerate All Elements In An Array (3/3)
var arr = [ "test", 1234, {}, [], "hi" ];
arr.map(function (val /*, i, arr*/) {
return typeof val;
});
// [ "string",
// "number",
// "object",
// "object",
// "string" ]
There is a special method “map” for any Array object.
We even have functional “map”, “every”, “some”, ... See the notes for more info
Calling Object.keys( ... ) gives you all enumerable “keys” in an object
How You Can Enumerate An “Object”
var obj = { a: "test", b: 1234, c: "hi" };
Object.keys(obj); // [ "a", "b", "c" ]
( true ).toString(); // "true"
( false ).toString(); // "false"
( 3.14 ).toString(); // "3.14"
( 3.14 ).toFixed(); // "3"
( "Hello" ).length; // 5
( "Hello" ).toUpperCase(); // "HELLO"
( "HELLO" ).slice(1, -1); // "ELL"
( "Hello world" ).split("o"); // [ "Hell", " w", "rld" ]
Where do those properties and methods come?
Let's play with some primitive values...
Note: Check the code snippets for more about “String” values
Values,
Expressions,
Operators,
Statements,
Control Flow
Canvas API
The Canvas API provides a means for drawing graphics via JavaScript and the HTML<canvas> element. Among other things, it can be used for animation, game graphics, data visualization, photo manipulation, and real-time video processing.
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'green';
ctx.fillRect(10, 10, 150, 100);
![](https://s3.amazonaws.com/media-p.slid.es/uploads/831137/images/5738360/download.png)
window.requestAnimationFrame(callback);
Most of the syntax in JavaScript is the same as
in programming languages like C, C++, and Java
Refer to MDN Reference when you encounter any problem
Find An Idea
To Work On
To Write Code For
It's Your Turn
Copy of Lecture on JavaScript
By kps
Copy of Lecture on JavaScript
A concise and accurate JavaScript tutorial/notes written for those entering the JavaScript world for the first time but already have experience with other languages
- 72