JavaScript
OUTLINE
- About JS
- Data Types (Primitive vs Reference)
- Operators & Flow Control
- DOM Events and Manipulation
- jQuery
1 About JS
1.1 JS HISTORY
- 1995: Mocha was invented by Brendan Eich from Netscape in 10 days.
- 1996: Mocha—>LiveScript—>JavaScript. JavaScript to Java is like Carpet to Car; JavaScript has almost nothing to do with Java.
- 1997: ECMAScript1 was released (ECMA is the standard, JS is the language in practice)
- 2009: ES5 was released
- 2015: ES6 was released, biggest update ever.
- 2022: ES13 was released
1.2 JS COMPATIBILITY
- Backwards-compatible (doesn’t remove old features)
- ES5 JS can run in modern browsers that support ES 6+
-
ES6+ JS can’t run in older browsers
-
Development: execute JS in a modern browser that supports ES6+
-
Production: convert ES6+ back to ES5 for cross-browser compatibility using Babel (a JS transpiler)
1.3 ES6 COMPATIBILITY TABLE
1.4 ECMASCRIPT VS JAVASCRIPT
- ECMAScript: a standardized specification for a scripting language (language syntax & semantics)
- JavaScript: a high-level programming language that conforms to ECMAScript
- just-in-time compilation
- dynamic typing
- first-class functions
- multi-paradigm programming (how you design solutions)
- imperative: clearly defined sequence of instructions
- declarative: a set of expectations without specifying how it should be done
- functional: apply and compose functions
- object-oriented: uses prototypes
1.5 JUST-IN-TIME (JIT) COMPILATION
- Ahead-of-time (AOT) compilation: before runtime, convert the program entirely into machine code, write it to a binary file, execute this file.
- Interpretation: during runtime, interpreter parses the source code and directly executes instructions line by line.
- Just-In-Time (JIT) compilation: during runtime, entire code is converted into machine code, then executed immediately, which allows for runtime optimizations
1.6 JS ENGINE
- JavaScript engine: a software program that optimizes and executes JavaScript code.
- V8: Google Chrome, Node.js
- SpiderMonkey: Mozilla Firefox
- JavaScriptCore: Safari
- Chakra: Internet Explorer, Microsoft Edge
1.7 HOW TO RUN JAVASCRIPT
- In browsers:
- Import a
<script>
in HTML file at the end of</body>
to download & execute the script after loading the DOM. -
For chrome, open Chrome dev tools and click the ‘console’ tab to view outputs.
-
Outside of the browser:
- Node.js
1.8 REPL
-
Read-Eval-Print-Loop (REPL): a programming language environment that accepts user input (statements, expressions…) and outputs the result to the console after execution.
-
Can test basic syntax and operations
2 Data Types (Primitive vs Reference)
2.1 PRIMITIVE DATA TYPES
- Dynamic typing: types are not specified when declaring variables; they are assigned based on the value at runtime.
- 7 Primitive Data Types
-
string, number, boolean, undefined, null, symbol (ES6), bigint (ES11, 2020)
-
Immutability: the structure or data cannot be changed.
-
typeof: a unary operator that takes 1 operand and evaluates to a string that represents its data type.
2.2 COERCION & CONVERSION
- Coercion: when a value’s data type is implicitly changed to another data type
- Happens on operations between values of different data types.
-
ex: ’5’ + 9, true + 9
-
Conversion (typecasting): when a value’s data type is explicitly changed to another data type
- String()
- Boolean(), !!
- Number(), +
2.3 NUMBER, STRING, BOOLEAN
- Numbers, strings, and booleans are either primitive data types or objects.
- You’ll probably never need to create them as objects using “new ___”.
2.4 STRINGS
- String: a sequence of characters
-
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
-
Access characters:
- string[index]
-
string.charAt(index)
-
String properties/methods:
- string.length: returns the length of the string as a number
- string.slice(start, end?): returns a substring based on the specified indices
- string.split(separator?): returns an array of substrings from splitting the string at all occurrences of separator
- string.replaceAll(str1, str2): replace all occurrences of str1 with str2
- string.trim(): removes whitespace from both ends of a string
- string.includes(): return true/false based on whether the string has the specified characters
2.5 TEMPLATE LITERALS
-
Template literals/template strings (
${}
): (ES6) string literals that are delimited with back-ticks and allow expressions for dynamic values -
“+” can be used to concatenate strings, but we can do the same with template literals.
var name = "Hello World";
var combinedStr = 'My name is ' + name;
console.log(combinedStr);
console.log(`My name is ${name}`);
2.6 EXPRESSION VS STATEMENT
- Expression: code that can be evaluated and returns a value
-
1+1, ‘hello’+’world’, 3<4, ‘hi’,100
-
Statement: an instruction that performs a specific action
-
var num = 0
-
Template Literals can only accept expressions.
3 Operators & Flow Control
2.7 OPERATORS
-
Mathematical: +, +=, ++ -, -=, -- , =, ** /, /= %, %=
-
Comparison: >, <, >=, <=, ==, ===
-
Boolean:
! : negates the boolean value
&& : true when left and right are true, otherwise false
|| : false when left and right are false, otherwise true
-
Falsy values: 0, empty string (’’, “”,``), undefined, null, NaN
-
Short-circuiting: when evaluating a boolean expression with (&& ||) from left to right, the right operand is evaluated only if the left operand is not enough to determine the final value.
- When an argument is considered ‘enough’, it becomes the final value.
3.1 == VS ===
- ==: a comparison operator that converts the operands to the same type before the comparison.
- empty string => 0
-
string with no numeric value => NaN
-
===: a strict-equality comparison operator that returns false if the operands are not the same type.
console.log(5 == '5'); // true (because '5' is converted to a number)
console.log(5 === '5'); // false (because number and string are different types)
console.log(0 == ''); // true (empty string is converted to 0)
console.log(0 === ''); // false (different types: number vs. string)
console.log(null == undefined); // true (both are loosely considered "empty values")
console.log(null === undefined); // false (different types)
console.log('hello' == NaN); // false (string that is not numeric becomes NaN, and NaN is never equal to anything)
console.log('hello' === NaN); // false (different types)
console.log([] == 0); // true (empty array is converted to an empty string, then to 0)
console.log([] === 0); // false (different types: array vs. number)
3.2 Flow Control
- if else, ternary
- switch
- while
- for loop
3.3 REFERENCE DATA TYPES
- There is 1 reference data type: Object
- Object: mutable keyed collection of properties; they store a collection of data instead of a single value.
-
ex: Functions, Array, Map, Set, …
-
Data property: associates keys to values
-
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures
3.4 Object
- Objects can be created by using the Object() constructor or the object literal syntax ({}).
var obj1 = {
name: 'Object 1',
id: 'NJ',
greeting: function(){
console.log('hi there');
}
};
var obj2 = new Object({
name: 'Object 2',
id: 1,
greeting: function(){
console.log('hi there';)
},
});
-
Iterating through an Object
-
for … in …
- Object.keys(), Object.values(), Object.entries()
for (var key in obj3){
console.log(`key: ${key},
obje3[key]:`, obj3[key]);
}
// Convert object keys, values, or both into an array that can be iterated
// With this, we can use for ... of ..., .forEach();
console.log("Object.keys(obj3)=", Object.keys(obj3));
console.log("Object.values(obj3)=", Object.values(obj3));
console.log("Object.entries(obj3)=", Object.entries(obj3));
3.5 PRIMITIVE VS REFERENCE TYPES
- Primitive types
- size in memory is fixed
- stored on the stack
-
manipulate the actual value stored in a variable
-
Reference
- size in memory is dynamic
- stored on the heap
-
manipulate the reference to that object in memory
- ex: passing objects as arguments to a function and manipulating it will affect the original object
-
Shallow copy: storing the reference of an object in another variable (both old and new point to same object in memory)
- Deep copy: each of the old object’s properties are individually copied into a new object (different objects in memory)
3.6 Function
-
Function: a special object that can be invoked to execute code that performs a specific task.
-
return: unary operator that ends execution of the function and gives a specified value or undefined back to the function
-
caller: If no explicit “return”, it returns undefined.
-
3 Ways to Declare a Function
-
Function declaration
- Function expression
-
Arrow function (ES6)
-
First-class function: function that is treated like other variables
-
assigned to variables, passed as arguments to a function, returned from a function
-
Higher-order function: function that takes in functions as arguments or returns functions
Pure function: function that only depends on its inputs and does not change anything outside of its scope
- If given the same inputs, it will always have the same result.
3.7 Array
-
Array: a special object that stores an ordered list of values that are accessed by a 0-based index and has a length property
-
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
-
Create an array: [item1, item2, item3, …]
-
new Array(item1, item2, item3, …)
-
Access elements: arr[index]
-
arr.push(): add element to the end, return the number of elements in the new array
arr.unshift(): add element to the beginning, return the number of elements in the new array
arr.pop(): remove element from the end, return the element removed
arr.shift(): remove element from the beginning, return the element removed
arr.slice(start?, end?): return a new subarray from the starting to the ending index of the original array
arr.splice(start, deleteCount?, item1?, …, itemN?): remove a specified number of elements from the original array starting at some index
and add item1 … itemN, return the removed subarray
arr.join(separator?): return a string that is the concatenation of all elements, separated by the separator or comma if none specified
arr.includes(): return true/false based on whether the arr has the specified element
3.8 ARRAY METHODS
- These are all higher-order functions that take a function as an input. This input function specifies
how to operate on every element.
- arr.map(): return a new array of transformed elements using the original array
arr.filter(): return a new array of elements that match the filter conditions
arr.sort(): sorts the original array in place and returns a reference to it
- localeCompare() for sorting strings
arr.find(): returns the first element that matches the search conditions
arr.reduce(): returns a single value that accumulated
arr.some(): returns true/false if one element matches the conditions
arr.every(): returns true/false if all elements match the conditions
3.9 ITERATING THROUGH ARRAYS
for (var i = 0; i < arr3.length; i++){
console.log(arr3[i]);
}
for (var num of arr3){
console.log(num);
}
// SYNTAX: arr.forEach(num, index, arr) => {})
arr3.forEach((num, index) => console.log(`${index}th element is ${num}.`));
// Not what you're expecting, so don't use "in" to iterate arrays, only for objects
for (var num in arr3){
console.log(num);
}
3.10 MAP
-
Map: a special object that lets you store unique key-value pairs and remembers the insertion order of your keys
-
Create: new Map()
Access: map.get(key)
- map.size: returns the size
map.set(key, value): sets a new key-value pair, returns the updated map
map.has(key): returns true/false based on whether the key exists in the map
map.delete(key): deletes a key-value pair based on the key, returns true if it did or false if it didn’t exist
map.forEach((value, key, …) => {}): iterate through the map key/values
3.10.1 OBJECT VS MAP
3.10.2 OBJECT VS MAP ORDER
3.11 Set
-
Set: a special object that lets you store a unique, unordered list of values of any type.
-
Create a set: new Set()
Access: iterate to find it
- set.size: returns the size
set.add(value): adds value to the end, returns the updated set
set.has(value): returns true/false based on whether the value exists in the set
set.delete(value): deletes a value, returns true if it did or false if it didn’t exist
set.forEach(value => {})
3.11.1 ARRAY VS SET
3.11.2 WEB API
- Web APIs: a set of functions/objects built into a browser that you can access with JS
- DOM
- Fetch, XMLHttpRequest
-
Storage
-
https://developer.mozilla.org/en-US/docs/Web/API
4 DOM Events and Manipulation
4.1 DOM
- Document Object Model (DOM): a programming interface for web documents that has a tree structure, where HTML elements are represented as nodes containing objects.
- Use JS to manipulate the DOM (modify its structure, style, and contents) based on user interactions.
- ex: create HTML elements when the user clicks a button
4.2 DOM MANIPULATION
- Use JS to select an HTML element in the DOM.
- Register event handlers on that element (ex: user clicks).
- When the event is triggered, you have access to that element.
- Read the element properties.
- parent, children, sibling elements, value, text contents, id, class, other attributes
- Do some logic with those properties.
- ex: create/remove/append elements, change the contents, change the styling, hide an element
4.3 SELECTING ELEMENTS
- Query selectors: selects HTML elements using CSS selectors (#, .class, tag)
- document.querySelector(): returns the first element within the document that matches the specified selector(s) or null.
-
document.querySelectorAll(): returns all elements that match the specified selector as a NodeList
-
document.getElementBy___:
- document.getElementById(): returns the DOM element that matches this ID
- document.getElementsByTagName(), document.getElementsByClassName()
- returns elements as HTMLCollection
4.4 NODE LIST VS HTML COLLECTION
-
NodeList: static, does not recognize when new nodes are added to the DOM via JS
-
HTMLCollection: live, will recognize when new nodes are added to the DOM via JS
-
May cause bugs.
4.5 DOM EVENT
- DOM Event: actions or occurrences on the webpage that your code listens for and responds to using event handlers
- element.addEventListener(eventType, function)
- element.removeEventListener(eventType, function)
- Some event types
- click: when the user clicks on an element
- focus: when an element is in focus
- blur: when an element is not in focus
- keypress: when the user presses a key
- submit: when a form is submitted
4.6 EVENT INTERFACE
- Event: an object with properties that describe DOM events
-
Automatically passed to event handlers.
-
event.target: a reference to the DOM element to which the event was originally dispatched.
-
Access this property to read or manipulate DOM elements
-
Event Propagation: how events travel throughout the DOM and trigger event handlers.
- Events pass through every DOM node until it reaches the final phase or is stopped by your code.
- Phases: (1) capturing (2) target (3) bubbling
4.7 EVENT PROPAGATION
- (1) Capturing: event travels from the root down into the target element
- (2) Target: event has reached the target element
- (3) Bubbling: event “bubbles up” and travels outward
- Stopping propagation
- event.stopPropagation(): stops current event’s propagation
- event.stopImmediatePropagation(): stops other handlers for the current event from being called
4.8 EVENT DELEGATION
- Event Delegation: an optimization technique for when you have multiple event handlers that do the same thing.
- If many sibling elements have the same event handler logic, instead of binding the handler to each individual element, bind it once to their parent element.
- The event handler is triggered when it bubbles up from the target element and out to the parent.
- Check event.target in the handler.
4.9 PREVENT DEFAULT
- Some elements have default actions that occur when the event is dispatched.
- The “submit” event on a
-
The “click” event on an marks it with a check.
-
event.preventDefault(): used in the event handler to prevent the default actions
- Not all events are cancelable. Use the cancelable property to find out if an event is cancelable.
4.10 CREATE AND REMOVE ELEMENTS
-
document.createElement(tagName, options?): creates the HTML element specified by tagName document.createTextNode(): creates a Text node with the specified text. Node.appendChild(): appends a node as the last child to some node.
-
Node.removeChild(child): removes a specified child node from the selected element.
- If there is any reference to the removed child, it will still exist in memory.
- Node.remove(): remove the targeted element
4.11 EXERCISE
- Given an array [‘Apple’, ’Banana’, ‘Orange’], display its elements in an unordered list on the webpage.
- Implement an “Add” feature, where users can type a fruit name
and click a button to add it to the list.
- The fruit name is from the text .
- The button says “Add” and has click functionality.