Slides - Web Programming

CE419
Web Programming
Session 5: JavaScript
1
What is JavaScript?
•
JavaScript is a dynamic programming language.
•
Introduced in 1995 as a way to add programs to web
pages in the Netscape Navigator browser.
•
It has made modern web applications possible.
•
Has almost nothing to do with Java.
•
ECMAScript.
2
What is JavaScript?
•
Client-side
•
•
Interact with user, control the browser, communicate
asynchronously, alter the displayed document.
Server-side
•
Node.js
Welcome to JavaScript!
•
JavaScript is case-sensitive.
•
Each statement is optionally ended with a semicolon .
•
Syntax is very similar to C and Java.
Values, Types, and Operators
•
Numbers: 13, 16.59, 1.23e8.
•
Arithmetic operations: *, /, -, +, %
•
(18 - 5) % 4 * 2 / 2
console.log(15 / 2);
7.5
Infinity & NaN
console.log(Infinity * -2);
console.log(10 / 0);
-Infinity
Infinity
console.log(0 / 0);
NaN
console.log(Infinity - Infinity);
NaN
Values, Types, and Operators
•
Strings
"This is a string."
'This is a \'string\', too.'
console.log('100' + "250");
100250
•
Booleans: true and false (null, undefined, 0, NaN, '', are
false, the rest is true).
•
Comparisons: >, <, <=, >=, ==, !=
console.log('100' != "250");
console.log(NaN == NaN);
true
false
Values, Types, and Operators
•
Logical operators: ||, &&, !
console.log(!(3 == 4 || 10 >= 2));
•
false
Conditional operator
console.log(5 > 2 ? 'foo' : 'bar');
foo
Values, Types, and Operators
•
null & undefined
•
denote the absence of a meaningful value.
•
The difference in meaning between undefined and null
is an accident of JavaScript’s design, and it doesn’t
matter most of the time.
console.log(console.log('1'));
1
undefined
Automatic Type Conversion
•
JavaScript goes out of its way to accept almost any
program you give it.
console.log(8 * null)
console.log("5" - 1)
console.log("5" + 1)
console.log("five" * 2)
console.log(false == 0)
console.log('1' == 1)
console.log(true == [1])
console.log([[]] == 0)
0
4
51
NaN
true
true
true
true
Automatic Type Conversion
console.log(null == undefined);
console.log(null == 0);
true
false
JavaScript Equality table
https://dorey.github.io/JavaScript-Equality-Table/
Automatic Type Conversion
•
When you don't want automatic type conversion, use
=== and !==.
console.log(false === 0);
console.log('1' === 1);
false
false
•
Rule of thumb: Always use 3 equals unless you have a
good reason to use 2.
Short-circuiting
console.log(null || "user")
console.log("Karl" || "user")
"user"
"Karl"
Playtime!
alert('Knock, knock.');
var who = prompt("Who's there?");
var res = confirm("Do you like JS?")
Program Structure
•
Variables
var myAge = 21;
var box;
console.log(box);
•
undefined
Every time you forget to put var, a kitten dies horribly.
•
Local vs. Global
Program Structure
if (num < 10) {
alert("Small");
}
else if (num < 100) {
alert("Medium");
}
else {
alert("Large");
}
var number = 0;
while (number <= 12) {
console.log(number);
number = number + 2;
}
do {
var name = prompt("Who are you?");
} while (!name);
var result = 1;
for (var i = 0; i < 10; i = i + 1)
result = result * 2;
Program Structure
switch (weather) {
case "rainy":
console.log("bring an umbrella.");
break;
case "sunny":
console.log("Dress lightly.");
case "cloudy":
console.log("Go outside.");
break;
default:
console.log("Unknown weather");
break;
}
Comments
// this is a comment
/* this is a long comment. years ago I
was walking down the street when I saw
a programming beating himself with a
book. I looked at the cover and I saw
that it was a JS book. I asked him why
and he said that he is tired of this
stupid language… */
Functions
var square = function(x) {
return x * x;
};
console.log(square(12));
144
•
JavaScript is flexible with arguments.
•
All arguments can be accessed using arguments
pseudo-array:
Functions & Scopes
var x = "outside";
var f1 = function() {
var x = "inside f1";
};
f1();
console.log(x);
var f2 = function() {
x = "inside f2";
};
f2();
console.log(x);
outside
inside f2
Nested Scopes
var landscape = function() {
var result = "";
var flat = function(size) {
for (var count = 0; count < size; count++)
result += "_";
};
var mountain = function(size) {
result += "/";
for (var count = 0; count < size; count++)
result += "'";
result += "\\";
};
};
flat(3);
mountain(4);
flat(6);
mountain(1);
flat(1);
return result;
___/''''\______/'\_
Declaration Notation
function square(x) {
return x * x;
};
console.log(square(12));
console.log("The future says:", future());
function future() {
return "We STILL have no flying cars.";
}
Closure
•
A closure is the local variables for a function — kept
alive after the function has returned, or
•
A closure is a stack-frame which is not deallocated
when the function returns.
function sayHello2(name) {
var text = 'Hello ' + name; // Local variable
var sayAlert = function() { alert(text); }
return sayAlert;
}
say2 = sayHello2('Bob');
say2();
Closure
•
A closure is the local variables for a function — kept
alive after the function has returned, or
•
A closure is a stack-frame which is not deallocated
when the function returns.
function sayHello2(name) {
var text = 'Hello ' + name; // Local variable
var sayAlert = function() { alert(text); }
return sayAlert;
}
say2 = sayHello2('Bob');
say2();
Closure
function say() {
var num = 20;
var sayAlert = function() { alert(num); }
num++;
return sayAlert;
}
var sayNumber = say();
sayNumber();
21
Showtime!
Let's see closure in action!
27
Arrays
var myList = [2, 3, false, "sadjad", 11];
console.log(myList.length);
myList[myList.length] = 'newItem';
myList.push('newerItem');
for(var i = 0; i < myList.length; i++) {
console.log(myList[i]);
}
for(var i in myList) {
console.log(i);
}
•
A lot of methods are available: concat, indexOf, join,
lastIndexOf, pop, push, reverse, sort, shift, slice, etc.
Object-Oriented Programming with JavaScript
•
JavaScript is object-oriented to its core, with powerful,
flexible OOP capabilities.
•
JavaScript is a prototype-based language which
contains no class statement, such as is found in C++ or
Java.
•
Instead, JavaScript uses functions as classes.
The Class & Objects
var Person = function () {};
var person1 = new Person();
var person2 = new Person();
var Person = function (firstName) {
this.firstName = firstName;
console.log('Person instantiated');
};
var person1 = new Person('Alice');
var person2 = new Person('Bob');
console.log('person1 is ' + person1.firstName);
console.log('person2 is ' + person2.firstName);
The Class & Objects
var Person = function (firstName) {
this.firstName = firstName;
console.log('Person instantiated');
};
Person.prototype.sayHello = function() {
console.log(this.firstName);
}
var person1 = new Person('Alice');
person1.sayHello();
console.log(Person.prototype);
{ sayHello: [Function] }
Objects
var obj = {
firstName: "Sadjad",
lastName: "Fouladi",
age: 25,
email: "[email protected]",
sayHello: function() {
console.log("Hi, " + this.firstName);
}
};
obj.sayHello();
console.log(obj.firstName);
console.log(obj['lastName']);
x = Object.create(obj);
x.firstName = "Milad";
Hi, Sadjad!
Sadjad
Fouladi
Showtime!
Let's see objects in action!
33
References
•
http://eloquentjavascript.net/
•
http://htmldog.com/guides/javascript/
•
https://developer.mozilla.org/en-US/docs/Web/
JavaScript/Introduction_to_Object-Oriented_JavaScript
Thank you.
Any questions?
35