JavaScript Overview
- JavaScript is an object-oriented, dynamically typed scripting language.
- Primarily a client-side scripting language.
- Variables are objects with properties and methods.
- Functions are also objects (unlike Java, C#, and C++).
- Dynamically typed: variables can be easily converted between data types.
Client-Side Scripting
- Refers to the client machine (browser) running code locally.
- The client machine downloads and executes JavaScript code.
Advantages:
- Reduces server load by off-loading processing to the client.
- Improves user experience by providing faster responses to user events.
- Enables interaction with downloaded HTML, creating a desktop-like experience.
Disadvantages:
- No guarantee that JavaScript is enabled; required functionality must be redundantly implemented on the server.
- JavaScript-heavy applications can be complex to debug and maintain.
- JavaScript is not fault-tolerant; invalid JavaScript code can halt execution.
- Newer JavaScript features may not be supported in all browsers.
JavaScript History
- Introduced by Netscape in 1996.
- Submitted to Ecma International in 1997.
- ECMAScript is both a superset and subset of JavaScript.
- ES6 introduced classes, iterators, arrow functions, and promises.
- The latest version is ES11 (ES2020).
JavaScript and Web 2.0
- A request is made.
- The server performs minimal processing and returns basic HTML with JavaScript file references.
- Requests are made for JavaScript files.
- JavaScript files are returned.
- JavaScript executes and makes asynchronous requests for data from web APIs.
- Web APIs access server-based resources like databases.
- Web APIs return data in JSON format.
- JavaScript continually updates the page based on received data and user actions.
JavaScript in Contemporary Software Development
- Expanded role beyond the browser.
- Used in server-side runtime environments like Node.js.
- MongoDB uses JavaScript as its query language.
- Used in Adobe Creative Suite and OpenOffice for end-user scripting.
JavaScript Placement
- Similar to CSS, JavaScript can be inline, embedded, or external.
- Inline JavaScript: within HTML element attributes.
- Embedded JavaScript: within
<script> elements. - Recommended: place JavaScript in external files using the
<script> tag.
Users without JavaScript
- Users may disable JavaScript for various reasons (search engines, extensions, accessibility).
- The
<noscript> element allows displaying content to users without JavaScript enabled.
Variables and Data Types
- Dynamically typed: no need to declare the type of a variable.
- Use
var, const, or let keywords to declare variables. - Assignment can occur at declaration or runtime.
JavaScript Output
alert(): Displays content in a browser-controlled pop-up/modal window.prompt(): Displays a message and an input field in a modal window.confirm(): Displays a question in a modal window with OK and Cancel buttons.document.write(): Outputs content (as markup) directly to the HTML document.console.log(): Displays content in the browser’s JavaScript console.document.write() is not trustworthy; use JavaScript DOM methods instead.
Data Types
- Reference types (objects).
- Primitive types (non-object, simple types).
- JavaScript allows using primitive types as if they are objects.
Primitive Types:
- Boolean:
true or false. - Number: Double-precision 64-bit floating-point value.
- String: A sequence of characters delimited by single or double quotes.
- Null: Only one value:
null. - Undefined: Only one value:
undefined. Assigned to uninitialized variables (different from null). - Symbol: New to ES2015, represents a unique value that can be used as a key value.
Primitive vs. Reference Types
- Primitive variables contain the value directly in memory.
- Object variables contain a reference/pointer to the memory block with the object's content.
Let vs. Const
let: Allows reassignment of values.const: Does not allow reassignment of values after initialization.const variables can still have their properties or array elements changed.
Built-In Objects
- Arrays, functions, and built-in objects are readily available.
- Common built-in objects:
Object, Function, Boolean, Error, Number, Math, Date, String, RegExp. - Browser environment objects:
document, console, window. - Example:
letdef=newDate();
letabc=def.toString();
Concatenation
- Combine string literals with variables using the
+ operator. - Alternative: template literals.
- Example:
const country = "France";
const city = "Paris";
const population = 67;
const count = 2;
let msg = city + " is the capital of " + country;
msg += " Population of " + country + " is " + population;
let msg2 = population + count;
console.log(msg); //Paris is the capital of France Population of France is 67
console.log(msg2); // 69
Conditionals
- Similar syntax to PHP, Java, or C++.
- Condition in
() brackets, body in {} blocks. - Optional
else if statements, with an else at the end. - Comparator operators:
<, >, ==, <=, >=, !=, !==, ===.
Switch Statement
- Similar to a series of
if...else statements. - Conditional operator (ternary operator) is an alternative.
- Example:
switch (artType) {
case "PT": output = "Painting"; break;
case "SC": output = "Sculpture"; break;
default: output = "Other";
}
// equivalent if-else
if (artType == "PT") {
output = "Painting";
} else if (artType == "SC") {
output = "Sculpture";
} else {
output = "Other";
}
Conditional (Ternary) Operator
- Syntax:
condition ? valueIfTrue : valueIfFalse - Examples:
foo = (y==4) ? "y is 4" : "y is not 4";
let tip = isLargeGroup ? 0.25 : 0.15;
let price = isChild? 5: isSenior ? 7 : 9;
Truthy and Falsy
- Every value in JavaScript has an inherent Boolean value.
- Truthy: translates to
true. - Falsy: translates to
false. - Falsy values:
false, null, "", '', 0, NaN, and undefined.
While and Do…While Loops
- Execute nested statements repeatedly as long as the
while expression is true. - While loops initialize a loop control variable before the loop, use it in the condition, and modify it within the loop.
- Example:
let count = 0;
while (count < 10) {
// do something
// ...
count++;
}
count = 0;
do {
// do something
// ...
count++;
} while (count < 10);
For Loops
- Combine initialization, condition, and post-loop operation into one statement.
for (initialization; condition; postLoopOperation) { ... }
Infinite Loop Note
- Infinite loops can lock the browser.
- Browsers may terminate long-running scripts.
Try…Catch
- Catches runtime errors (exceptions).
- Prevents disruption of regular program execution.
- Example:
try {
nonexistantfunction("hello");
} catch(err) {
alert ("An exception was caught:" + err);
}
- Can be used to throw your own error messages.
Arrays
- Commonly used data structures.
- Two ways to define an array:
- Array literal notation:
constname=[value1,value2,…]; - Array() constructor:
constname=newArray(value1,value2,…);
Array Example
const years = [1855, 1648, 1420];
const countries = ["Canada", "France", "Germany", "Nigeria", "Thailand", "United States"];
const twoWeeks = [
["Mon","Tue","Wed","Thu","Fri"],
["Mon","Tue","Wed","Thu","Fri"]
];
const mess = [53, "Canada", true, 1420];
Iterating an Array using For…Of
- ES6 introduced the
for...of loop for iterating through arrays. - Example:
// iterating through an array
for (let yr of years) {
console.log(yr);
}
//functionally equivalent to
for (let i = 0; i < years.length; i++) {
let yr = years[i];
console.log(yr);
}
Array Destructuring
- Extracting array elements into individual variables.
- Example:
const league = ["Liverpool", "Man City", "Arsenal", "Chelsea"];
// old-fashioned way
let first = league[0];
let second = league[1];
let third = league[2];
// array destructuring
let [first,second,third] = league;
Objects
- Collections of named values (properties).
- Not created from classes (prototype-based language).
- New objects are created from existing prototype objects.
Object Creation Using Object Literal Notation
- Most common way to create objects.
- Represented by key-value pairs separated by colons, with commas separating pairs.
- Access properties using dot notation or square bracket notation.
- Example:
const objName = {
name1: value1,
name2: value2,
// ...
nameN: valueN
};
objName.name1
objName["name1"]
Object Creation Using Object Constructor
- Another way to create objects.
- Example:
// first create an empty object
const objName = new Object();
// then define properties for this object
objName.name1 = value1;
objName.name2 = value2;
- Object literal notation is generally preferred.
Objects Containing Other Content
- Accessing nested objects:
country.captial.name
Object Destructuring
- Extracting object properties into individual variables.
- Example:
const photo = {
id: 1,
title: "Central Library",
location: {
country: "Canada",
city: "Calgary"
}
};
let id = photo.id;
let title = photo["title"];
let country = photo.location.country;
let city = photo.location["city"];
// Equivalent assignments using object destructuring
let { id,title } = photo;
let { country,city } = photo.location;
// Combined
let { id, title, location: {country,city} } = photo;
Spread
- Copies contents from one array into another.
- Uses the spread syntax (
...). - Example:
const foo = { name:"Bob", ...photo.location, iso:"CA" };
// Is equivalent to:
const foo = { name:"Bob", country:"Canada", city:"Calgary", iso:"CA"};
- It's a shallow copy: primitive values are copied, but for object references, only the references are copied.
JSON
- JavaScript Object Notation.
- Language-independent data interchange format (like XML).
- Property names are enclosed in quotes.
- Example:
// this is just a string though it looks like an object literal
const text = '{ "name1" : "value1", "name2" : "value2", "name3" : "value3" }';
JSON object
- Turning a JSON string into a JavaScript object using
JSON.parse(). - Example:
// this turns the JSON string into an object
const anObj = JSON.parse(text);
// displays "value1"
console.log(anObj.name1);
JSON in Contemporary Web Development
- Frequently encountered in web development.
- Used for data exchange between web applications.
Functions
- Defined using the
function keyword, function name, and optional parameters. - Do not require a return type or parameter type specifications.
Declaring and Calling Functions
function subtotal(price,quantity) {
return price * quantity;
}
let result = subtotal(10,2);
Function Expressions
- Functions can be created using function expressions.
- Anonymous functions are commonly used.
- Example:
// defines a function using an anonymous function expression
const calculateSubtotal = function (price,quantity) {
return price * quantity;
};
// invokes the function
let result = calculateSubtotal(10,2);
// define another function
const warn = function(msg) {
alert(msg);
};
// now invoke that function
warn("This doesn't return anything");
Default Parameters
- Specifying default values for function parameters.
- Example:
function foo(a=10,b=0) {
return a+b;
}
let bar = foo(3); // bar will be equal to 3
Rest Parameters
- Function that accepts an arbitrary number of arguments.
- The rest operator is
.... - Example:
function concatenate(...args) {
let s = "";
for (let a of args)
s += a + " ";
return s;
}
let girls = concatenate("fatima","hema","jane","alilah");
let boys = concatenate("jamal","nasir");
console.log(girls); // "fatima hema jane alilah“
console.log(boys); // "jamal nasir“
Nested Functions
- Functions defined within other functions
- Example:
function calculateTotal(price,quantity) {
let subtotal = price * quantity;
return subtotal + calculateTax(subtotal);
// this function is nested
function calculateTax(subtotal) {
let taxRate = 0.05;
return subtotal * taxRate;
}
}
Hoisting in JavaScript
- Function declarations are hoisted to the beginning of their current scope.
- Assignments are NOT hoisted.
Callback Functions
- A function passed as an argument to another function.
- Example:
Objects and Functions Together
- Objects have properties that are functions.
this keyword refers to the object.- Example:
const order ={
salesDate : "May 5, 2016",
product : {
price: 500.00,
brand: "Acer",
output: function () {
return this.brand + ' $' + this.price;
}
},
customer : {
name: "Sue Smith",
address: "123 Somewhere St",
output: function () {return this.name + ', ' + this.address; }
}
};
alert(order.product.output());
alert(order.customer.output());
Contextual Meaning of the This Keyword
this is normally contextual and sometimes requires a full understanding of the current state.
Function Constructors
- Similar to creating instances of objects in class-based languages.
- Use the
new keyword before the function name. - Example:
// function constructor
function Customer(name,address,city) {
this.name = name;
this.address = address;
this.city = city;
this.output = function () {
return this.name + " " + this.address + " " + this.city;
};
}
// create instances of object using function constructor
const cust1 = new Customer("Sue", "123 Somewhere", "Calgary");
alert(cust1.output());
const cust2 = new Customer("Fred", "32 Nowhere St", "Seattle");
alert(cust2.output());
What Happens with a Constructor Call of a Function
Arrow Syntax
- Concise syntax for anonymous functions.
- Solution to
this scope problems in callback functions. - Example:
const taxRate = function () {
return 0.05;
};
// Arrow function version
const taxRate = () => 0.05;
Array Syntax overview
Changes to “This” in Arrow Functions
- Arrow functions do not have their own
this value. this within an arrow function is that of the enclosing lexical context.- Allows using
this in a way more familiar to object-oriented programming.
Scope in JavaScript
- The context in which code is being executed.
- Four scopes: function scope (local scope), block scope, module scope, global scope.
Block Scope
- Variables defined with
let or const within a block are only available within that block. - If declared with
var within a block, it will be available outside the block.
Global Scope
- Available everywhere.
- Can cause namespace conflicts.
- If a new identifier with the same name exists, it replaces the old one.
Function/Local Scope
Closures in JavaScript
- Scope in JavaScript is sometimes referred to as lexical scope.
- The ending bracket of a function is said to close the scope of that function.
- A closure is an object consisting of the scope environment in which the function is created; that is, a closure is a function that has an implicitly permanent link between itself and its scope chain.