var a = [1, 2, 3];
var b = [...a, 4, 5, 6]; // b = [1,2,3,4,5,6]
var c = [...a] ; // array copy
var obj = { prop1: 1; prop2: "2"; }
var objcopy = { ...obj }; // object cloning
var str = "hello";
var helloarray = [ ...str]; // helloarray = ['h','e','l','l','o']
// calling a function with an array parameter:
const f = (arg1, arg2) => {}
const a = [1, 2]
f(...a)
Deconstructing
a = [1, 2, 3, 4, 5, 6];
[first, ,third]=a; // first=1 and third=3
const student = {
firstName: "Forest";
lastName: " Forest";
age: 41
}
const { firstName: name, age: ageval } = student
// name will be "Forest" and ageval will be 41
const { lastName, age } = student
// lastName will be "Forest" and age will be 41
The strict mode
- the default running mode of javascript in browser is a sloppy mode: non-critical errors are passed over, optimization is harder to achieve
- strict mode introduces some restrictions to the javascript engine:
- eliminates some JavaScript silent errors by changing them to throw errors
- fixes mistakes that make your code harder to optimize by javascript engines
- prohibits the usage of some symbols maked as keywords in future versions of ECMAScript
Apply strict mode
- strict mode can be applied to a whole script or to a function (not to a block)
- to invoke strict mode, one needs to specify at the beginning of the script or function:
'use strict';
- concatenating strict mode scripts with non-strict mode scripts can be tricky
Strict mode mistakes converted to errors
'use strict';
mistypeVariable = 7; // if no global variable 'mistypeVariable' exists
// (defined with "var"), this line throws ReferenceError
// Assignment to a non-writable global
var undefined = 5; // throws a TypeError
var Infinity = 5; // throws a TypeError
var o = { p: 1, p: 2 }; // syntax error (redefinition of p)
// reserved words: implements, interface, let, package, private,
// protected, public, static, and yield
Javascript modules
- as the javascript code run in the browser becomes larger and larger, module usage becomes important
- module files can be *.js or *.mjs
- it's a good idea to serve modules from an http server (not from the local file system, file://) so that you don't run into CORS issues
- a module can export var, let, const, functions, classes – they all need to be in the global context
- a javascript code can import every exported symbol from a module or just some of them
- modules are imported into the scope of a single js script, they are not available in the global scope
Exporting symbols from a module
Importing symbols from a module into a javascript file
Importing into module object
import * as Module1 from './modules/mod1.js';
import * as Module2 from './modules/mod1.js';
...
// calling functions from mod1.js
Module1.function1();
Module1.function2();
// calling functions from mod2.js
Module2.function1();
Module2.function2();
Dynamic module loading
import('./modules/myModule.js') .then(
(module) => {
// Do something with the module.
// call functions
});
Events
- Javascript is an event-based language
- Event: mouse click, key pressed, element loosing focus etc.
- when an event is triggered by the browser a predefined or user-defined (in Javascript) event handler takes control
- event handlers are associated to a tag:
- <TAG eventHandler="Javascript code">
- <script type="text/javascript">
function evHandle(x) { ... }
</script>
<TAG eventHandler="evHandle(this)">
- <script type="text/javascript">
obj.eventHandler="Javascript code";
</script>
Javascript and HTML
- Js scripts can be used in HTML documents in 4 ways:
- as instructions or functions written inside a <SCRIPT> tag:
<script type="text/javascript">
... JavaScript statements...
</script>
- Js code written in a separate javascript file:
<script src="common.js"></script>
- using a Js expression as the value of an html attribute:
<hr width="&{barWidth};%" align="left">
<h4>&{myTitle};</h4>
JavaScript entities start with "&" and end with ";" and are enclosed in "{}"
- as an event handler:
<input type="button" value="Press Me" onClick="func()">
Good way of including .js in .html file
- the following line makes the browser run the js code in script.js only after the HTML document is completely loaded:
<script src="script.js" defer></script>
- this is useful when:
const button = document.querySelector("#button");
button.addEventListener('click', someFunction);
If this script is placed in <head>, the browser throws an error
because the <button id="button"> is not loaded yet, "button" constant is null.
Pop-up boxes
- alert("...text...") : displays text and the Ok button
- confirm("...text...") : displays text and returns true if the Ok button is clicked and false if the Cancel button is clicked
- prompt("text", "default value"): the user can enter an input value and then click Ok (return the value) or Cancel (return null)
Document Object Model (DOM)
DOM (Document Object Model)
- is a standardized (by W3C) hierarchical model of an HTML or XML document
- DOM can be used for navigating in the document structure, modify the document structure (add, delete, modify child elements etc.) and also modifying attributes of an element
- each tag is a DOM object
- it has an API which can be used in Javascript
- Javascript + DOM is sometimes called DHTML (Dynamic HTML)
Hierarchical DOM structure
Copyright: Birger Eriksson; Wikipedia
DOM Browser Objects
- Window object
- Navigator object
- Screen object
- History object
- Location object
DOM document objects
- Document object
- Anchor object
- Area object
- Base object
- Body object
- Button object
- Event object
- Form object
- Frame object
- Frameset object
- IFrame object
- Image object
- Input Button object
- Input Checkbox object
- Input File object
Document object collections (selection)
| Collection | Description |
| forms[] | Returns a reference to all Form objects in the document |
| images[] | Returns a reference to all Image objects in the document |
| links[] | Returns a reference to all Area and Link objects in the document |
| anchors[] | Returns a reference to all Anchor objects in the document |
Document object properties (selection)
| Property | Description |
| body | Gives direct access to the <body> element |
| cookie | Sets or returns all cookies associated with the current document |
| domain | Returns the domain name for the current document |
| lastModified | Returns the date and time a document was last modified |
| referrer | Returns the URL of the document that loaded the current document |
| title | Returns the title of the current document |
| URL | Returns the URL of the current document |
Document object methods (selection)
| Method | Description |
| close() | Closes an output stream opened with the document.open() method, and displays the collected data |
| getElementById() | Returns a reference to the first object with the specified id |
| getElementsByName() | Returns a collection of objects with the specified name |
| getElementsByTagName() | Returns a collection of objects with the specified tagname |
| open() | Opens a stream to collect the output from any document.write() or document.writeln() methods |
| write() | Writes HTML expressions or JavaScript code to a document |
| writeln() | Identical to the write() method, with the addition of writing a new line character after each expression |
The Element Object. Properties
- a DOM Element represents an HTML tag
- .attributes - returns a map of all attributes of this elem.
- .children – returns a collection of children of this elem.
- .classList – returns all classes of this element
- .className – set/get the class attribute of this elem.
- .clientHeight, .clientWidth - returns height/width including padding
- .firstChild - returns first child node
- .firstElementChild – returns first child element (ignores text and comments)
- .innerHTML, .innerText – set/get the content of this elem.
- .id – set/get the ID attribute of this element
The Element Object. Properties (2)
- .lastChild - returns the last child node of this elem.
- .lastElementChild - returns the last child element of this elem. (ignores text and comments)
- .nextSibling,.previousSibling - returns the next/prev node at the same level
- .nextElementSibling,.previousElementSibling – returns the next/prev element at the same level (ignores text and comments)
- .parentNode - returns the parent node of this element
- .parentElement – returns the parent element of this element (ingnores text and comments)
- .style – set/get the style attribute of this element
The Element Object. Methods
- addEventListener(), removeEventListener() – adds/removes an event listener for this elem.
- appendChild(), removeChild() – append/remove a child to this element
- click() – simulates a mouse click on this elem.
- getAttribute(),setAttribute() – get/set attribute
- getElementsByTagName() – returns children by tag name
- getElementsByClassName() – returns children by class name
- insertBefore() – insert a new child node before existing child node of this element
- remove() – remove this element
- querySelector() - returns the first child that matches a selector
- querySelectorAll() – return all children that match a selector
Creating & removing elements (tags) dynamically
var p = document.createElement("p"); // create "p" tag
var text = document.createTextNode("text content");
p.appendChild(text); // append text to tag "p"
p.innerHTML = "other text"; // set a new content text
var p1 = p.cloneNode(); // create copy of p
p.insertBefore(p1); // add another element before
p.removeChild(p.firstChild); // remove first child of p
p.remove(); // remove p (the element itself)
Modifying elements (tags)
var section = document.querySelector("section");
section.setAttribute("class", "red-section");
section.style.background = "red";
section.innerHTML = "<p>test</p>";
section.innerText = "test";
Asynchronous programming
-
var timeoutID = window.setTimeout(func, delay, [param1, param2, ...])
Calls function "funct" with the specified parameters after "delay" miliseconds have passed.
-
window.clearTimeout(timeoutID);
Clears the timeout (async function is no longer called).
Asynchronous programming (promises)
const myFirstPromise = new Promise(function (resolve, reject) {
// do something asynch which eventually calls either:
// resolve(someValue); // fulfilled
// or
// reject("failure reason"); // rejected
});
The executor function is executed immediately by the Promise implementation, passing resolve and reject functions (the executor is called before the Promise constructor even returns the created object); the resolve and reject functions are provided by the Javascript engine. The resolve and reject functions, when called, resolve or reject the promise, respectively. The executor normally initiates some asynchronous work, and then, once that completes, either calls the resolve function to resolve the promise or else rejects it if an error occurred.
If an error is thrown in the executor function, the promise is rejected. The return value of the executor is ignored.
Getting the returned result from a Promise
// Promises can not return anything, they just pass results to callbacks (which are specified with .then())
const p = new Promise(function(resolve,reject) {
// the asynchronous word - just a console.log()
console.log("Doing some work...");
resolve("Done");
});
// without .then() you can not get the returned result from the Promise!
// we assume the Promise p is always resolved
p.then(function(result) {
console.log(result); // just print the returned result of the Promise
})
Javascript and browser compatibility
- browser compatibility is and issue even outside javascript (html, css) → different browser show tags differently (i.e. have default styles) → the need to reduce browser inconsistencies (CSS reset or reboot packages)
- with javascript/ECMAScript, some browser implement a version of ECMAScript, other browser implement other ECMAScript versions → the need to use polyfills (js libraries that extend the functionality of the browser): Core-js, Polyfill.io and transpilers (e.g. Babel – takes a higher ECMAScript version code and converts it into a lower ECMAScript version code)
Javascript quirks
Javascript can be a very
powerful language, a
messy one, a language
full of drama ...
Here is a small list of javascript quirks (larger list is here: https://dev.to/mkrl/javascript-quirks-in-one-image-from-the-internet-52m7):
0.5+0.1==0.6 → true
0.2+0.1==0.3 → false
typeof(NaN) → number
3+"1" → "31"
10-"1" → 9
true===1 → false
true==1 → true
[ ]+[ ] → ""
Browser API, Web API, Js libraries, Js frameworks
- Browser API – a set of javascript functions, objects & properties exposed by the browser; e.g. DOM; a list of browser APIs developed by w3c.org is here: https://www.w3.org/standards/techs/js#w3c_all
- Web API – a server-side API usually exposed through HTTP request-response; the response is usually a JSON expression
- Js library – one or more js files providing custom functions & objects that enhance the functionality of the javascript language; e.g. jQuery
- Js framework – a js library plus html & css code used to write an entire web application from scratch; inversion of control – key difference between libraries and frameworks: when calling a method from a library, the developer is in control; with frameworks control is inverted – the framework calls developer's code; e.g. Angular
Js debugging tools
- Firefox's Web Console and Chrome's Inspector
- JsFiddle (https://jsfiddle.net/)
- CodePen (https://codepen.io)