Introduction
- HTML gives the web page structure and purpose
- CSS makes it looks aesthetic with styling
JS makes the page dynamic and interactive
A lightweight, interpreted programming language.
it run instantly as a soon it run instantly, it is interpreted and dynamic. it is popularPrograms written in JavaScript are called scripts.
JavaScript allows you to implement complex interaction on Web pages. you add dynamic interaction with javascript.
It is the third layer of standard web technologies (HTML, CSS, JS).
JavaScript is different from Java programming language.
the relationship between HTML, CSS and javascript is because they are standard of building a website
it used .js file extension.
Uses of JavaScript
- adds interactivity to web pages
- run codes in response to certain events
- javascript has a powerful application programming interface(API) hence access to numerous complex features e.g get location, mapping, 2d graphics.
- it is everywhere it can be run anywhere
Execution in Js
- to run it, it can be run by a browser with javascript virtual machine to run js, the jvm can be in a browser(cos all browsers come with a jvm where it is chrome, Safari, mozilla, edge), mobile phone, a server. for chrome, opera and edge they have v8 machine because the v8 is maintained by chrome, for firefox their jvm is spiderMonkey, for internet explorer which is no longer in use theirs is called chakra, for apple we have squirrelfish.
How to run javascript
- Internal js / inline js to run javascript internally
- external js is tp add js in another file and reference it
in the script tag
<script src="app.js"></script>
the order is important - to debug you use a developer console to check the debugging we have some section in the dev tools, element, network, console, sources, performance, memory.
A statement carry out an action
alert("click me")
comments in javascript thare human readable text that does not rendered on the page, it is ignored by the interpreter
*// single line
/ / multi- line comments *
- variable is a name storage for a value or data
let firstName = "Risisng"
let surname = "heloo"
Uses of JavaScript
- Adds interactivity to web pages
- Run codes in response to certain events
- JavaScript has a powerful Application Programming Interface (APIs), hence access to numerous complex features
- What is even more exciting however is the functionality built on top of the client-side JavaScript language. So-called Application Programming Interfaces (APIs) provide you with extra superpowers to use in your JavaScript code.
APIs are ready-made sets of code building blocks that allow a developer to implement programs that would otherwise be hard or impossible to implement. They do the same thing for programming that ready-made furniture kits do for home building.
There are two types of APIs available:1.Browser APIs: Built and shipped with Browsers
2.Third party APIs: Not built into the browser by default, and you generally have to grab their code and information from somewhere on the Web. For example: Google maps API, Twitter API
JavaScript can run on:
Browsers, using the JavaScript Virtual Machine (JVM).
Servers, using runtimes like Nodejs
Any devices that have the Javascript engine
JS Execution
- JavaScript can execute not only in the browser, but also on the server, or actually on any device that has a special program called the JavaScript engine.
- The browser has an embedded engine sometimes called a “JavaScript virtual machine”. Different engines have different “names” for their JVM.
The terms above are good to remember because they are used in developer articles on the internet. We’ll use them too. For instance, if “a feature X is supported by V8”, then it probably works in Chrome, Opera and Edge.
Different platforms have different “names” for their JVMV8 – in Chrome, Opera and Edge.
SpiderMonkey – in Firefox.
Chakra” for IE
Nitro” and “SquirrelFish” for Safari, etc.
Embedding JS
- JavaScript is applied to your HTML page in a similar manner to CSS. Whereas CSS uses
<link>
elements to apply external stylesheets and<style>
elements to apply internal stylesheets to HTML, JavaScript only needs one friend in the world of HTML — the<script>
element.
Adding JavaScript to your Webpage
- Internal JavaScript: JS code added inside HTML files
- External JavaScript: External JS code linked in HTML file
- Internal Javascript
- Write and run JS inline HTML by saving the file and loading in the browser.
- Order matters, so if you add the script before the button, you get an error. Show an example here
- Show an example of the “DOMContentLoaded” event. Order does not matter here, as script code is executed after HTML content is loaded.
External Javascript
- This is generally a good thing in terms of organizing your code and making it reusable across multiple HTML files. Plus, the HTML is easier to read without huge chunks of script dumped in it.
- Note the defer option? I does the same thing as the “DOMContentLoaded”
- Order matters when loading scripts. Show examples.
Statements are syntax constructs and commands that perform actions.
We’ve already seen a statement,
alert(‘Hello, world!’)
, which shows the message “Hello, world!”We can have as many statements in our code as we want. Statements can be separated with a semicolon.
A semicolon may be omitted in most cases when a line break exists.
JavaScript interprets the line break as an “implicit” semicolon. This is called an automatic semicolon insertion.
Comments
- Comments are used to describe code.
- As time goes on, programs become more and more complex. It becomes necessary to add comments which describe what the code does and why.
- Comments can be put into any place of a script. They don’t affect its execution because the engine simply ignores them.
Variables
- A variable is a “named storage” for values or data
- Use real-life analogy of a named ingredients in a kitchen
- JavaScript application needs to work with information. E.g Catalogue list holding shopping items, Chat application holding messages, names etc
- Create a variable using the let and const keyword. We’ll take about their difference later.
- Can declare multiple variables in single line separated by comma
- Talk about var and its availability in older script. Discourage it’s usage
Variables (Naming conventions)
- The name must contain only letters, digits, or the symbols *$ and _ *. Required
- The first character must not be a digit. Required
- Use camelCase when variables contain multiple words Optional Case matters: Variables named apple and AppLE are two different variables.
- Reserved Names/Keyword cannot be used. E.g let let = 5; let return = 5;
Variables (const)
- Variables declared with const do not change and cannot be re-assigned
- It is a convention in JS to CAPITALIZE const variable names
-
Separate multiple words with under_score
Variables (let)
Variables declared with let can change and be re-assigned
Variable names should be descriptive and it’s intention should be clear
It is recommended to use camelCase for long variables
A variable name should have a clean, and meaning obvious.
Variable naming is one of the most important and complex skills in programming.
Some good-to-follow rules are:Use human-readable names like userName or shoppingCart.
Rarely use abbreviations or short names like a, b, cMake names maximally descriptive and concise. Examples of bad names are data and value..
Agree on terms within your team and in your own mind. If a site visitor is called a “user” then we should name related variables currentUser or newUser instead of currentVisitor or newManInTown.
Data Types
- A value in JavaScript is always of a certain type. e.g, string, number.
- There are eight (8) basic data types in JavaScript, these are:
number
bigInt
string
boolean
null
undefined
object
symbol
We can put any type in a variable. For example, a variable can at one moment be a string and then store a number: let message = “hello”; message = 123456;
Programming languages that allow such things, such as JavaScript, are called “dynamically typed”, meaning that there exist data types, but variables are not bound to any of them.
Data types (number)
- The number type represents both integer (without a decimal) and floating point numbers( with decimal). are referred to as number and not differentiated
- The following operations work on numbers: multiplication *, division /, addition +, subtraction -.
- There are “special numeric values” which also belong to this data type: Infinity, -Infinity and NaN.
Infinity represents the mathematical Infinity ∞. e.g divide by 0
NaN represents a computational error. It is a result of an incorrect or an undefined mathematical operation, for instance: console.log(“name” / 2)NaN is sticky. Any further mathematical operation on NaN returns NaN
So, if there’s a NaN somewhere in a mathematical expression, it propagates to the whole result (there’s only one exception to that: NaN ** 0 is 1).
Doing maths is “safe” in JavaScript. We can do anything: divide by zero, treat non-numeric strings as numbers, etc. The script will never stop with a fatal error (“die”). At worst, we’ll get NaN as the result.
Data types (BigInt)
- The bigInt type represents extremely large or small integers which cannot be represented by the number type.
- The maximum and minimum size for a number type is (253-1) and -(253-1)
- This number type is enough for many purpose, so the bigInt type is rarely used.
- A BigInt is created by adding n to the end of a number or using the BigInt constructor
//Numbers
let size_in_meters = 20
let size_in_inches = 2.1024
let maxSize = Infinity
let minSize = -Infinity
let not_a_number = NaN
let sum = 20 + 23.1; let difference = 20 - 10;
let multiplication_result = 20 * 10; let division_result = 20 / 2;
//BigInt
let very_big_number = 872765678901234567890123567890134567890n;
let another_big_number = BigInt(872765678901234567890123567890134567890)
Data types (Boolean)-P
- -The boolean type has only two values: true and false.
- This type is commonly used to store yes/no values: true means “yes, correct”, and false means “no, incorrect”.
- Boolean values are mostly gotten from comparisons:
Data types (null)-P
- The value null represents the intentional absence of a value
- The null type is a special value which represents “nothing”, “emptiness” or “value unknown”.
- Note that type of null is object for legacy reasons
- An unassigned variable is automatically set to type null
- Use null to assign an “empty” or “unknown” value to a variable
Data types (undefined)-P
- The value undefined means a value is not assigned
- A declared variable without assigned values becomes undefined by default
- Show example of type of undefined
Data types (object)- NP
- Objects are one of the most important data type in JavaScript
- Objects are used to store keyed-value pair collections of data and more complex entities.
- All other types are called “primitive” because their values can contain only a single value
- Objects are associative arrays with several special features. They store properties (key-value pairs), where:
- You can retrieve values using dot notation or with square brackets
- Objects are store any valid JavaScript type including objects themselves
- delete a property: delete obj.prop.
let user = {};
let user = new Object();
user.age = 20
user["emailVerify"] = false
delete user.emailVerify;
to call the entire object
console.log(Object.values(user)) // it print all values
console.log(Object.keys(user)) // it print all values
you can also have imbedded array
Data types (String)
- A String type is used to represent and manipulate a sequence of characters.
- A string type must be surrounded by quotes or backticks.
- Double and single quotes are “simple” quotes. There’s practically no difference between them in JavaScript.
- Backticks are “extended functionality” quotes. They allow us to embed variables and expressions into a string by wrapping them in ${…}
- Other quotes don’t have this embedding functionality.
- Strings are special types, and therefore have extra functionalities built on it.
- You can call methods on strings to do special things like the examples below
- You can use special characters in strings, like the new line character (n)
- Other special characters are ‘, “, , t, u{1F60D}. Show some examples in console
- /n, //, /r, -> special character
- Access single characters in strings using subseting a[0]
- Strings are immutable, you can’t change a character
- Get substrings with slice
- function and method are called to perform specific task
Basic Operator
Terminologies
- An operator is a reserved syntax consisting of punctuation or alphanumeric characters that carries out built-in functionality. e.g addition operator (“+“), subtraction operator (“–“).
- An operator can be unary or binary. e.g +
- An operand – is what operators are applied to. e.g the values that is act on
types of operator
operator can be unary, binary or ternary
- unary acts on single operand
- binary acts on 2 operand
- ternary acts on 3 operand
Math operators
Mathematical operation
The following math operations are supported in JavaScript:
- Addition +,
- Subtraction -,
- Multiplication * asterick,
- Division / backwardlash,
- Remainder % modulus,
- Exponentiation ** raised to power
- Remember If an expression has more than one operator, the execution order is defined by their precedence, or, in other words, the default priority order of operators.
binary + is applied to strings, it merges (concatenates) them:
We know many operators from school. They are things like addition +, multiplication *, subtraction -, and so on. Show examples
Remember If an expression has more than one operator, the execution order is defined by their precedence, or, in other words, the default priority order of operators.
Parentheses override any precedence, so if we’re not satisfied with the default order, we can use them to change it. For example, write (1 + 2) * 2.
Let’s meet features of JavaScript operators that are beyond school arithmetics. So operators like addition works for strings. Show example
if the binary + is applied to strings, it merges (concatenates) them:
Next, let’s talk about JavaScript-specific operators, not covered by school arithmetic.
Comparison operators
This is used to check if two number are equal or not they return boolean values either true or false
Comparison operators are used to apply boolean logic to operands. E.g
- Greater than: a > b
- Less than: a < b
- Greater or equals: a >= b
- Less than or equals: a <= b
- Equals: a == b,
- Strict Equality a === b e.g 0 === false
Not equals: a != b
All comparison operators return a boolean value
To see whether a string is greater than another, JavaScript uses the so-called “dictionary” or “lexicographical” order. In other words, strings are compared letter-by-letter.
Please note the double equality sign == means the equality test, while a single one a = b means an assignment.
To see whether a string is greater than another, JavaScript uses the so-called “dictionary” or “lexicographical” order. In other words, strings are compared letter-by-letter.
When comparing values of different types, JavaScript converts the values to numbers. alert( ‘2’ > 1 )
For boolean values, true becomes 1 and false becomes 0.
A regular equality check == has a problem. It cannot differentiate 0 from false: 0 == false // true, ” == false.
These are JavaScript false values. Use a strict equality check instead. (0 === false ); // false, because the types are different
Other operators
The assignment operator (“=”) is used to assign values to a variable
The increment (“++”) and decrement (“–“) operators
Bitwise operators : AND ( & ), OR ( | ), XOR ( ^ ), NOT ( ~ ), LEFT SHIFT ( << ), RIGHT SHIFT ( >> ), etc
Assignment = is also an operator. It is listed in the precedence table with the very low priority.
Bitwise operators are used very rarely, when we need to fiddle with numbers on the very lowest (bitwise) level.
Let’s note that an assignment = is also an operator. It is listed in the precedence table with the very low priority of 2. That’s why, when we assign a variable, like x = 2 * 2 + 1, the calculations are done first and then the = is evaluated, storing the result in x.
Increasing or decreasing a number by one is among the most common numerical operations. So, there are special operators for it:
-
Bitwise operators are used very rarely, when we need to fiddle with numbers on the very lowest (bitwise) level. We won’t need these operators any time soon, as web development has little use of them, but in some special areas, such as cryptography, they are useful. You can read the Bitwise Operators chapter on MDN when a need arises.
Conditional branching (if)
let day = "Monday";
if(day == "Monday"){
alert("Monday")
}
OR
if(day == "Monday") alert("Monday")
- Sometimes, we need to perform different actions based on different conditions. To do that, we can use the if statement and the conditional operator
- The if(…) statement evaluates a condition and, if the result is true, executes a block of code.
- We recommend wrapping your code block with curly braces {} every time you use an if statement, even if there is only one statement to execute. Doing so improves readability.
- The if (…) statement evaluates the expression in its parentheses and converts the result to a boolean. if (0) { // 0 is falsy..} works because 0 is falsy
Conditional branching (if-else)
- The else clause may contain an optional block if code that evaluates when the condition is falsy
Conditional branching (else-if)
- Multiple else-if clause can be chained to test numerous conditions
- The final else is optional. When all else fails, it gets executed
Conditional operator ( ? )
- The conditional operator (? ) called the ternary operator can be used to assign values based on a condition
- The operator is represented by a question mark ?. Sometimes it’s called “ternary”, because the operator has three operands. It is actually the one and only operator in JavaScript which has that many.
Conditional branching (switch)
- A switch statement can replace multiple if checks. It gives a cleaner way of comparing a value with multiple variants. It has the following syntax:
- The switch has one or more case blocks and an optional default.
- The case check is a strict equality
- If the equality is found, switch starts to execute the code starting from the corresponding case, until the nearest break (or until the end of switch).
- If no case is matched then the default code is executed (if it exists).
Logical operators
- Logical operators available in JavaScript are: || (OR), && (AND), ! (NOT)
- Although they are called “logical”, they can be applied to values of any type, not only boolean. Their result can also be of any type.
- OR==> If any of its arguments are true, it returns true, otherwise it returns false. Show examples with if statements
- If an operand is not a boolean, it’s converted to a boolean for the evaluation. For instance, the number 1 is treated as true, the number 0 as false: if (1 || 0) {…}
Loops
Loops are used to perform repeated actions based on a condition.
In JavaScript there many types of loops:
- The “while” loop
- The “do…while” loop
- The “for” loop
- The for…of loop
- The for…in loop
Loops ( while )
- The while loop has the following syntax
- While the condition is truthy, the code in the while loop body is executed.
- A single execution of the loop body is called an iteration. The loop in the example above makes three iterations.
- If i++ was missing from the example above, the loop would repeat (in theory) forever. In practice, the browser provides ways to stop such loops, and in server-side JavaScript, we can kill the process.
- Any expression or variable can be a loop condition, not just comparisons: the condition is evaluated and converted to a boolean.
Loops ( do…while )
The do…while loop has the following syntax
This is similar to while loop. The condition check is just moved below the loop body using the do..while syntax:
This means the code is run at least once before the loop start.
Loops ( do…while )
- The do…while loop has the following syntax
- This is similar to while loop. The condition check is just moved below the loop body using the do..while syntax:
- This means the code is run at least once before the loop start.
Loops ( for )
- The for loop has the following syntax
- The for loop is more complex, but it’s also the most commonly used loop.
- If you are new to loops, it could help to go back to the example and reproduce how it runs step-by-step on a piece of paper.
- The “counter” variable i is declared right in the loop. This is called an “inline” variable declaration. Such variables are visible only inside the loop.
- we can force the exit at any time using the special break directive.
- The continue directive is a “lighter version” of break. It doesn’t stop the whole loop. Instead, it stops the current iteration and forces the loop to start a new one (if the condition allows).
Loops ( for…of )
- The for…of loop is used to loop over iterable properties of an object. It has the following syntax
- The values of an iterable object can be iterated over, meaning they can counted. E.g Arrays, Maps, Set, Strings (We will talk deeply about these in Data Structure section)
- On each iteration a value of a different property is assigned to variable. variable may be declared with const, let.
Loops ( for…in )
- The for…in has the following syntax
- The for…in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.
- Given that for…in is built for iterating object properties, not recommended for use with arrays, and options like Array.prototype.forEach() and for…of exist, what might be the use of for…in at all?
- It may be most practically used for debugging purposes, being an easy way to check the properties of an object
Functions
- Functions are the main “building blocks” of the program. They allow the code to be called many times without repetition.
- You’ve seen lots of built-in functions like: alert, console.log, prompt, etc
- Quite often we need to perform a similar action in many places of the script. For example, we need to show a nice-looking message when a visitor logs in, logs out and maybe somewhere else.
- Functions are the main “building blocks” of the program. They allow the code to be called many times without repetition.
Functions Variables
- Local variables: These are variables declared inside a function is only visible inside that function.
- Outer variables: These are variables declared outside a function.
- The function has full access to the outer variable. It can modify it as well.
- An outer variable is only used if there’s no local one. If a same-named variable is declared inside the function then it shadows the outer one.
- Variables declared outside of any function, such as the outer userName in the code above, are called global.
- Global variables are visible from any function (unless shadowed by locals). It’s a good practice to minimize the use of global variables.
Functions Parameters
- Parameters are data passed to a function. These are passed in the function’s parenthesis ( ).
- We can pass arbitrary data to functions using parameters.
- When the function is called with arguments, the given values are copied to local variables. Then the function uses them.
- A parameter is the variable listed inside the parentheses in the function declaration (it’s a declaration time term)
- An argument is the value that is passed to the function when it is called (it’s a call time term).
- We declare functions listing their parameters, then call them passing arguments.
- If a function is called, but an argument is not provided, then the corresponding value becomes undefined.
- We can specify the so-called “default” (to use if omitted) value for a parameter in the function declaration, using =:. e.g function showMessage(from, text = “no text given”)
Functions Returns
- A function can return a value back into the calling code as the result.
- The directive return can be in any place of the function. When the execution reaches it, the function stops, and the value is returned to the calling code (assigned to result above).
- There may be many occurrences of return in a single function. For instance, an if..else block
- It is possible to use return without a value. That causes the function to exit immediately.
- If a function does not return a value, it is the same as if it returns undefined:
- If we want the returned multiple results, then wrap them in parenthesis
Functions Tips
- Functions are actions. So their name is usually a verb. e.g getUser, calculatePercent, addInterest, etc
- A function should do exactly what is suggested by its name, no more.
- Functions should be short and do exactly one thing. If that thing is big, maybe it’s worth it to split the function into a few smaller functions
- Two independent actions usually deserve two functions, even if they are usually called together
- A function is similar to a comment. That is, it should be self descriptive from it’s name and usage
Function Expression
- There is another syntax for creating a function that is called a Function Expression. It allows us to create a new function in the middle of any expression.
- The syntax that we used before is called a Function Declaration.
Callback functions
- Functions are like values, and they can be assigned, as well as passed around just like variables
- In practice, such functions are quite useful
- The arguments showFullName and showUserName of displayUser are called callback functions or just callbacks.
- The idea is that we pass a function and expect it to be “called back” later if necessary. In our case, showFullName becomes the callback for display type “full”, and showUserName as opposite.
Arrow Functions
- There’s another very simple and concise syntax for creating functions, that’s often better than Function Expressions.
- It’s called “arrow functions”, because it looks like this
- Arrow functions can be used in the same way as Function Expressions.
- Arrow functions may appear unfamiliar and not very readable at first, but that quickly changes as the eyes get used to the structure.
- They are very convenient for simple one-line actions
Scopes & Closures
- Scope in JavaScript refers to the current context of code, which determines the accessibility of variables to JavaScript. The two types of scope are local and global:
- Global variables are those declared outside of a block
- Local variables are those declared inside of a block
- A closure is a function that remembers its outer variables and can access them. In JS all functions are naturally closures
- All functions and Objects have access to a Global scope.
- If a variable is declared inside a code block {…}, it’s only visible inside that block.
Arrays
- Arrays are used to store ordered collections.
- There are two syntaxes for creating an empty array:
- Almost all the time, the second syntax is used. We can supply initial elements in the brackets:
- Array elements are numbered, starting with zero. We can get an element by its number in square brackets:
- An array can store elements of any type. Objects, functions, etc
Array Method
- Array methods are functions we can call on an array
- There are lots of methods built into Arrays. See full list here
- You can loop over arrays with for, for…of, forEach
- The length property automatically updates when we modify the array. To be precise, it is actually not the count of values in the array, but the greatest numeric index plus one.
- Arrays can have items that are also arrays. We can use it for multidimensional arrays, for example to store matrices:
- Arrays can have items that are also arrays. We can use it for multidimensional arrays, for example to store matrices:
- Other popular array methods are map, slice, and splice
Sets
- A Set is a special type collection – “set of values” (without keys), where each value may occur only once.
- Set has the following methods and properties:
- set.add(value) – adds a new value and returns the set
- set.delete(value) – removes the value.
- set.clear() – removes everything from the set.
- set.has(value) – returns true if the value exists, false otherwise.
- set.size – returns the set element count.
- The main feature is that repeated calls of set.add(value) with the same value don’t do anything. That’s the reason why each value appears in a Set only once.
- For example, we have visitors coming, and we’d like to remember everyone. But repeated visits should not lead to duplicates. A visitor must be “counted” only once. Set is just the right thing for that:
- We can loop over a set either with for..of or using forEach
Destructuring assignment
- Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes that’s more convenient.
- Destructuring also works great with complex functions that have a lot of parameters, default values, and so on. Soon we’ll see that.
- It’s called “destructuring assignment,” because it “destructurizes” by copying items into variables. But the array itself is not modified. let firstName = arr[0];
- Unwanted elements of the array can also be thrown away via an extra comma: let [firstName, , title] = [“Julius”, “Caesar”, “Consul”, “of the Roman Republic”]; In the code above, the second element of the array is skipped, the third one is assigned to title, and the rest of the array items is also skipped (as there are no variables for them).
- We can use it with any iterable, not only arrays: let [a, b, c] = “abc”; // [“a”, “b”, “c”]
- The order of destructuring in objects does not matter
- If we have a complex object with many properties, we can extract only what we need.
- If an object or an array contain other nested objects and arrays, we can use more complex left-side patterns to extract deeper portions.
Dom & Dom Manipulation
Browser specification
- Web browsers give a means to control web pages.
- There’s a “root” object called window. It has two roles:
- First, it is a global object for JavaScript code, as described in the chapter Global object.
- Second, it represents the “browser window” and provides methods to control it.
For instance, here we use it as a global object: alert(window.innerHeight); // inner window height
DOM
- Document Object Model, or DOM for short, represents all web page content as objects that can be modified.
- The document object is the main “entry point” to the page. We can change or create anything on the page using it.
- Properties and methods are described in the specification: DOM Living Standard.
- An HTML/XML document is represented inside the browser as the DOM tree.
DOM Tree
All HTML tag in a page is an object. Nested tags are “children” of the enclosing one. The text inside a tag is an object as well.
The Dom tree is a large object representing all page tags. You can see the Dom tree of page by inspecting the page in the developer console
DOM Tree
The backbone of an HTML document is tags.
For example, document.body is the object representing the
DOM nodes have properties and methods that allow us to travel between them, modify them, move around the page, and more. We’ll get down to them in the next chapters.
- The DOM allows us to do anything with elements and their contents, but first we need to reach the corresponding DOM object.
- All operations on the DOM start with the document object. That’s the main “entry point” to DOM. From it we can access any node.
DOM Navigation
- The topmost tree nodes are available directly as document properties: = document.documentElement
- = document.body
- Child nodes (or children) – elements that are direct children. In other words, they are nested exactly in the given one. For instance, and are children of element.
- Descendants – all elements that are nested in the given one, including children, their children and so on.
- The childNodes collection lists all child nodes, including text nodes. Show example of listing child nodes
- Searching
- There are additional searching methods for that. These are:
- document.getElementById or just id
- querySelectorAll: returns all elements inside elem matching the given CSS selector.
- querySelector: The call to elem.querySelector(css) returns the first element for the given CSS selector
- elem.getElementsByClassName: returns elements that have the given CSS class.
- elem.getElementsByTagName: looks for elements with the given tag and returns the collection of them. The tag parameter can also be a star “*” for “any tags”.
- The id must be unique. There can be only one element in the document with the given id. If there are multiple elements with the same id, then the behavior of methods that use it is unpredictable
- Only document.getElementById, not anyElem.getElementById
- This method querySelectorAll is indeed powerful, because any CSS selector can be used.
- The call to elem.querySelector(css) returns the first element for the given CSS selector. In other words, the result is the same as elem.querySelectorAll(css)[0], but the latter is looking for all elements and picking one, while elem.querySelector just looks for one. So it’s faster and also shorter to write.
DOM modification
- DOM modification is the key to creating “live” pages.
- To create DOM nodes, there are two methods:
- document.createElement(tag): Creates a new element node with the given tag:
- document.createTextNode(text): Creates a new text node with the given text:
- You can insert into the DOM using : document.body.append(div). There are other variants like prepend, before, after, replaceWith. See
- To remove a node, there’s a method node.remove().
- The id must be unique. There can be only one element in the document with the given id. If there are multiple elements with the same id, then the behavior of methods that use it is unpredictable
- Only document.getElementById, not anyElem.getElementById
- This method querySelectorAll is indeed powerful, because any CSS selector can be used.
- The call to elem.querySelector(css) returns the first element for the given CSS selector. In other words, the result is the same as elem.querySelectorAll(css)[0], but the latter is looking for all elements and picking one, while elem.querySelector just looks for one. So it’s faster and also shorter to write.
Dom Events & Events Handlers
- An event is a signal that something has happened. All DOM nodes generate such signals (but events are not limited to DOM).
- The following events can be tracked in the DOM:
- Mouse events: E.g click, mouseover, mouseup
- Keyboard events: E.g keydown, keyup
- Form element events: E.g submit, focus
- Document events: E.g DOMContentLoaded
- CSS events: E.g transitions
- Almost all the time, the second syntax is used. We can supply initial elements in the brackets:
- Array elements are numbered, starting with zero. We can get an element by its number in square brackets:
- An array can store elements of any type. Objects, functions, etc
- To react on events we can assign a handler – a function that runs in case of an event.
- We can set event handlers using:
- HTML Attributes: A handler can be set in HTML with an attribute named on.
- DOM property: We can assign a handler using a DOM property on.
- Methods event listeners. Explained in next slide
Event Handlers
Handlers are a way to run JavaScript code in case of user actions. There
are several ways to assign a handler. Let’s see them, starting from the simplest one.
For instance, to assign a click handler for an input, we can use onclick, like here: On mouse click, the code inside onclick runs.
Please note that inside onclick we use single quotes, because the attribute itself is in double quotes. If we forget that the code is inside the attribute and use double quotes inside, like this: onclick=”alert(“Click!”)”, then it won’t work right.
An HTML-attribute is not a convenient place to write a lot of code, so we’d better create a JavaScript function and call it there.
As we know, HTML attribute names are not case-sensitive, so ONCLICK works as well as onClick and onCLICK… But usually attributes are lowercased: onclick.
If the handler is assigned using an HTML-attribute then the browser reads it, creates a new function from the attribute content and writes it to the DOM property.
Event Listeners, Event Object
- Listeners can be attached to Dom elements, and will fire if the event happens
- You can use addEventListener to assign multiple event handlers to an element
- removeEventListener can be used to remove an event listener from an element
Event Listeners
- Using event handlers, you cannot attach more than one handler to an attribute. The fundamental problem of the aforementioned ways to assign handlers – we can’t assign multiple handlers to one event.
- Developers of web standards understood that long ago and suggested an alternative way of managing handlers using special methods addEventListener and removeEventListener. They are free of such a problem.
- When an event happens, the browser creates an event object, puts details into it and passes it as an argument to the handler.
- Some properties of the event object are: event.id, event.type, event.name etc. See full list here
Event Object
- To properly handle an event we’d want to know more about what’s happened. Not just a “click” or a “keydown”, but what were the pointer coordinates? Which key was pressed? And so on.
- When an event happens, the browser creates an event object, puts details into it and passes it as an argument to the handler.
When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.
Bubbling is convenient. Don’t stop it without a real need: obvious and architecturally well thought out.
To stop bubbling, use the method event.stopPropagation().
Almost all events bubble. One exception is the focus event.
Event Bubbling
To properly handle an event we’d want to know more about what’s happened. Not just a “click” or a “keydown”, but what were the pointer coordinates? Which key was pressed? And so on.
When an event happens, the browser creates an event object, puts details into it and parses it as an argument to the handler.
Callback
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
This execution may be immediate as in a synchronous callback, or it might happen at a later point in time as in an asynchronous callback.
What if the script loading fails? Our callback should be able to react on that.
Multiple asynchronous call back can result in the callback hell.
Callbacks
- Many functions are provided by JavaScript host environments that allow you to schedule asynchronous actions. In other words, actions that we initiate now, but they finish later. For instance, one such function is the setTimeout function.
Luckily, there are other ways to avoid such pyramids. One of the best ways is to use “promises”, described in the next slide.
The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
A Promise object returns a promise to supply the resulting value at some point in the future. So we can wait for it to keep the promise
A promise can be in any of these state:
pending: initial state, neither fulfilled nor rejected.
fulfilled: meaning that the operation was completed successfully.
rejected: meaning that the operation failed.
Promise
- A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action’s eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.
- The methods promise.then(), promise.catch(), and promise.finally() are used to associate further action with a promise that becomes settled.
- Consuming functions can be registered (subscribed) using methods .then, .catch and .finally.
Consuming a Promise
- A Promise object serves as a link between the executor (the “producing code” or “singer”) and the consuming functions (the “fans”), which will receive the result or error. Consuming functions can be registered (subscribed) using methods .then, .catch and .finally.
- The first argument of .then is a function that runs when the promise is resolved, and receives the result.
- The call .finally(f) is similar to .then(f, f) in the sense that f always runs when the promise is settled: be it resolve or reject.
- A finally handler has no arguments. In finally we don’t know whether the promise is successful or not. That’s all right, as our task is usually to perform “general” finalizing procedures.
Async/Await
- async/await are special syntax to work with promises in a more comfortable fashion.
- The word “async” before a function means one simple thing: a function always returns a promise. Other values are wrapped in a resolved promise automatically.
- The keyword await makes JavaScript wait until that promise settles and returns its result.
- async/await
- await only works inside an async function. If we try to use await in a non-async function, there would be a syntax error:
- Show example of converting the chapter Promises chaining and rewrite it using async/await:
- If a promise resolves normally, then await promise returns the result. But in the case of a rejection, it throws the error, just as if there were a throw statement at that line. So handle errors with try..catch
- When we use async/await, we rarely need .then, because await handles the waiting for us. And we can use a regular try..catch instead of .catch. That’s usually (but not always) more convenient.
- But at the top level of the code, when we’re outside any async function, we’re syntactically unable to use await, so it’s a normal practice to add .then/catch to handle the final result or falling-through error, like in the line (*) of the example above.
object-oriented programming (OOP)
- Object-oriented programming (OOP) is a programming paradigm based on the concept of “objects”, which can contain data and code: data in the form of fields (often known as attributes or properties), and code, in the form of procedures (often known as methods). (Wikipedia)
- This approach to programming is well-suited for programs that are large, complex and actively updated or maintained.
- OOP uses the concept of reusable templates (classes) which encapsulate actions (methods), and features (properties) in them.
Structure of OOP
- The structure, or building blocks, of object-oriented programming include the following:
- Classes: These are user-defined data types that act as the blueprint for individual objects, attributes and methods.
- Objects: These are instances of a class created with specifically defined data.
- Methods: These are functions that are defined inside a class that describe the behaviors of an object.
- Attributes: These are properties defined in the class template and represent the state of an object.
- Objects can correspond to real-world objects or an abstract entity. When class is defined initially, the description is the only object that is defined.
- Each method contained in class definitions starts with a reference to an instance object. Additionally, the subroutines contained in an object are called instance methods. Programmers use methods for reusability or keeping functionality encapsulated inside one object at a time.
- Objects will have data stored in the attributes field. Class attributes belong to the class itself.
Principles of OOP
- Object-oriented programming is based on the following principles:
- Encapsulation: Important information is contained inside an object and only select information is exposed
- Abstraction: Reveal important features, hide unnecessary details
- Inheritance: Classes can reuse, or extend code from other classes
- Encapsulation. This principle states that all important information is contained inside an object and only select information is exposed. The implementation and state of each object are privately held inside a defined class. Other objects do not have access to this class or the authority to make changes. They are only able to call a list of public functions or methods. This characteristic of data hiding provides greater program security and avoids unintended data corruption.
- Abstraction. Objects only reveal internal mechanisms that are relevant for the use of other objects, hiding any unnecessary implementation code. The derived class can have its functionality extended. This concept can help developers more easily make additional changes or additions over time.
- Inheritance. Classes can reuse code from other classes. Relationships and subclasses between objects can be assigned, enabling developers to reuse common logic while still maintaining a unique hierarchy. This property of OOP forces a more thorough data analysis, reduces development time and ensures a higher level of accuracy .
Benefits of OOP
- Benefits of OOP include:
- Modularity. Encapsulation enables objects to be self-contained, making troubleshooting and collaborative development easier.
- Reusability. Code can be reused through inheritance.
- Maintainability. Programs become easy to maintain and improve
- Security. Using encapsulation and abstraction, complex code is hidden
- Modularity. Encapsulation enables objects to be self-contained, making troubleshooting and collaborative development easier.
- Reusability. Code can be reused through inheritance, meaning a team does not have to write the same code multiple times.
- Productivity. Programmers can construct new programs quicker through the use of multiple libraries and reusable code.
- Easily upgradable and scalable. Programmers can implement system functionalities independently.
- Interface descriptions. Descriptions of external systems are simple, due to message passing techniques that are used for objects communication.
- Security. Using encapsulation and abstraction, complex code is hidden, software maintenance is easier and internet protocols are protected.
- Flexibility. Polymorphism enables a single function to adapt to the class it is placed in. Different objects can also pass through the same interface.
Inheritance
Please click on this link to access the resource folder for this lesson.
The following platforms allows you to write and run JavaScript without installing anything
- CodeSandBox
- CodePen
- JSFiddle
- Replit
Top comments (0)