Week 5 Flashcards

1
Q

What are the datatypes in JavaScript?

A

Number, bigInt (values larger than -253 or 253), boolean, string, undefined, null, array (stores list of variables under a single variable), and object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is Javascript?

A

Javascript is the most commonly used client-side language. It is a high-level, multi-paradigm, interpreted programming language used to create dynamic webpages. The browser interprets Javascript code in it and executes it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Can JavaScript code be run on servers as the backend program for an application?

A

Although JavaScript originated as a scripting language that runs in the browser, the Node.js runtime environment does allow JavaScript code to be run on servers as the backend program for an application.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What does it mean to say JavaScript is a high level language?

A

It abstracts away many implementation details that relate to computer hardware - like allocating memory or garbage collection of objects.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What does it mean to say JavaScript is multi-paradigm?

A

It supports many programming paradigms like procedural, object-oriented, and functional programming.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the official name for JavaScript?

A

ECMAScript

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

In HTML, where is JavaScript code written?

A

In HTML, JavaScript code is written inside the and tags. You can place any number of scripts in an HTML document. Scripts can be placed in the , or in the section of an HTML page, or in both.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is “internal JavaScript”?

A

When the JavaScript is code placed anywhere within the HTML page using tags

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is “external JavaScript”?

A

When JavaScript code is placed in a separate file from the HTML code. These files are saved with the “. js” extension and imported into the HTML page using the src attribute. The src attribute specifies the URL/path of an external JavaScript file. (Eg: )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Is JavaScript case sensitive?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How are statements separated in JavaScript?

A

Every statement in JavaScript is separated using a semicolon (;). JavaScript ignores multiple spaces and tabs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are JavaScript Literals?

A

Literals are the fixed values, they can be numbers, strings, boolean values, etc. The number type stores integer, float, and hexadecimal value. Strings are text, enclosed within single or double quotes (‘ or “). If numbers, characters, or words are enclosed with single or double quotes, then they are considered strings.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are JavaScript keywords?

A

Keywords are tokens that have special meaning in JavaScript. The keywords supported by JavaScript are break, case, catch, continue, do, else, finally, for, function, if, in, new, return, switch, this, throw, try, typeof, var, void, while, etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are JavaScript variables and how are they declared?

A

Variables are used to store data values. It uses the var keyword to declare variables. An equal sign (=) is used to assign values to variables. Variable names are identifiers that should not be a JavaScript keyword. They start only with the alphabet, underscores (_) or dollar ($). They cannot start with a number and also there shouldn’t be spaces in-between.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What are the Arithmetic Operators in JavaScript and what do they mean?

A
\+ addition
 - subtraction
 * multiplication
 / division
% calculates remainder in a quotient
\++ increment
-- decrement
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What are the Comparison Operators and what do they mean?

A

== “equals” - checks value NOT variable type - returns true or false boolean
=== “equals” - checks value AND variable type - returns true or false boolean
!= “not equal”
> greater than
< less than
>= greater than or equal to
<= less than or equal to

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What are the Logical Operators and what do they mean?

A

&& and
|| or
! not

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What are the Assignment Operators and what do they mean?

A
= is equal to
\+= increment and is equal to
-= decrement and is equal to
*= multiply and is equal to
/= divide and is equal to 
%= divides and assigns remainder to the variable
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is the Ternary Operator and what does it mean?

A

< condition > ? < value1 > : < value2 >;

Javascript operator that takes 3 operands. First a condition followed by a ?, then an expression to execute if the condition is true followed by a :, and finally an expression to execute if the condition is false. Frequently used as an alternative to an if…else statement

Ex.
function getFee(isMember) {
  return (isMember ? '$2.00' : '$10.00');
}
console.log(getFee(true));
// expected output: "$2.00"
console.log(getFee(false));
// expected output: "$10.00"
console.log(getFee(null));
// expected output: "$10.00"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What are the Control Flow statements in JavaScript?

A
if/else
for
for-in
for-of
while
do-while
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the difference between for-in and for-of in JavaScript?

A

for-in allows iteration over the keys of an object

for-of allows iteration over an array or array-like object

Ex.
let person = {
  name: 'Bob',
  age: 25
};

for (let prop in person) {
console.log(person[prop]); // prints ‘Bob’ and then 25
}

let people = [
{
  name: 'Alice',
  age: 30
},
{
  name: 'Charlie',
  age: 29
}
]

for (let pers of people) {
console.log(pers.name); // prints ‘Alice’ then ‘Charlie’
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What are the advantages and disadvantages of JavaScript as compared to other programming languages?

A

Advantages

  • Is a dynamically-typed language. JavaScript does not declare types before declaring or assigning a variable. Variables can hold the value of any data type at any point in time.
  • JavaScript can run on a server or on a browser. Java and C# would have to be compiled to WebAssembly in order to run on modern-day browsers.
  • JavaScript is a multi-paradigm language, meaning we can solve our problems in a variety of ways, functionally, object-oriented, or event-driven. With Java and C#, while many of those paradigms have support in the language, Object-oriented solutions are preferred. In JavaScript, functions are first-class variables, meaning that they are treated like any other variable and can be passed as arguments to other functions.
  • JavaScript utilizes prototype-based objects. Java and C# utilize class-based objects. In ES6, JavaScript introduced class-based syntax which allows us to interface with our prototypes in a similar manner to Java and C#. However, OOP in JavaScript is accomplished very differently than in these other languages.

Disadvantages

  • Due to being a dynamically-typed language, there is no static type checking available which could lead to issues with functions return a value of multiple types
  • JavaScript is single-threaded and runs off of an event-loop. Java and C# support multi-threading.
  • Due to using prototypes, an “overridden” method is merely shadowed on the prototype and is therefore still accessible.
  • JavaScript has no concept of method/function overloading.
  • Encapsulation is possible in JavaScript but there are no access modifiers and is not as simple as in other languages.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is a function in JavaScript?

A

A group of reusable code which can be called anywhere in the program. All functions are passed by value meaning the value of any variable passed to a function is copied into the argument of the function. Any changes you make to the argument will not be reflected in the variable outside of the function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is an anonymous function in JavaScript?

A

An anonymous function is a function that is declared without any identifier to refer to it. It is an expression that the variable holds a function.

Ex.

var x = function (a, b) {return a * b};

Ex.

var anon = function() {
  alert('I am anonymous');
};
var prd = function (a, b) {
    return a * b;

};
anon();
alert(“prd = “ + prd(2,4));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What is a Self-Invoking Function (IIFE Function)?

A

A self-invoking function is an anonymous function that is invoked immediately after its definition. It is also known as the IIFE (Immediately Invoked Function Expression) function. It holds an anonymous function inside a set of parentheses (), which does the execution.

Ex.

(function(){
    // do this right now
    console.log("Look at me, I'm running");
})();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What is a Callback Function and why are they useful?

A

A callback function is a function that gets executed after another function completes the execution.

It helps us develop asynchronous JavaScript code and keeps us safe from problems and errors. JavaScript usually runs the code in sequential order (from top to bottom). If there is a case that code runs after some other execution, which is not happening in a sequence, this is called asynchronous programming.

All functions in JavaScript are objects and a JavaScript function can be passed another function as an argument.

Ex.
function funcOne(x) { alert("x = " + x); }
function funcTwo(y, callback) {
    callback(y);		
}

funcTwo(2, funcOne);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What is a Closure?

A

A closure is a function that remembers and accesses the variables and arguments of its outer function even after the function return. The closure able to access the variables defined between its curly brackets, the outer function’s variables and the global variables.

Ex.
function greeting() {
    var message = 'Hi';
    function sayHi() {
        console.log(message);
    }
    return sayHi;
}
let hi = greeting();
hi(); // prints "hi" in the console.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What is Hoisting?

A

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. In JavaScript, variable declarations made with var and function declarations made with the function keyword are hoisted - or moved - to the top of the scope in which they are declared when the JavaScript interpreter parses the code. This means that variables and functions can be used before they are even declared.

Ex - Hoisting of Variables

	//line 1
	x = 1; 
	document.getElementById("p1").innerHTML = x ;
	var x;

Ex - Hoisting of Functions
alert(Sum(5, 5)); // output: 10

function Sum(val1, val2)
{
    return val1 + val2;
}

Ex - Hoisting Functions Before Variables
alert(UseMe); // displays the UseMe Function definition

var UseMe = “UseMe Variable”;

function UseMe()
{            
    alert("UseMe function called");
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What is the difference between “==” and “===” in JavaScript?

A

== is used for comparison between two variables irrespective of the data type of variable.

=== is used for comparison between two variables but this will check strict type, which means it will check datatype and compare two values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What is Type Coercion in JavaScript? What are the different types of Type Coercion?

A

Type coercion is the process of converting a value from one data type to another data type.

Explicit type coercion - We can explicitly convert the datatype of the variable. For example: Number(‘3’), String (123), Boolean(2)

Implicit type coercion - JavaScript is a loosely-typed language, values can also be converted between different types automatically. It usually happens when you apply operators to values of different types. For example: ‘3’ * ‘2’, 2/’5’, 123 + ‘’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What is Falsy in JavaScript?

A

In JavaScript, any expressions or value that results in boolean false value, are considered as Falsy. The falsy values/expressions in javascript are:

Boolean false is false.
Any empty string will be evaluated to false.
Any undefined variable will be equal to false.
Any null variable will be equal to false.
Any numerical expression with result in NaN (not a number) will be equal to false.
Any numerical expression with result in zero will be equal to false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What is Truthy in JavaScript?

A

In JavaScript, any expression or value that results in boolean true value, are considered as Truthy. Any expression or value that is not falsy is considered truthy.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What is Variable Scope?

A

The Variable scope defines the lifetime and visibility of a variable. Each variable is associated with a scope. The variable can be accessed only within its scope.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What is a Global Scope variable?

A

Variables defined outside any function, block, or module have global scope. The global scope variables are accessed everywhere in the application. The global variable’s lifetime is throughout the application. We can declare the global variables in a browser using the global window object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What is a Function Scope Variable?

A

The variable declared in a function is only visible inside that function. var is the keyword to define variable for a function-scope accessibility. These variables cannot be accessed or modified.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

What is a Block Scope Variable?

A

Block scope is the scope of the variables declared inside the {} (curly brackets). In ES6, const and let keywords allow developers to declare variables in the block scope, which means those variables exist only within the corresponding block.

Ex.
function func(){
    if(true){
        var fruit1 = 'apple';        //exist in function scope
        const fruit2 = 'banana';     //exist in block scope
        let fruit3 = 'strawberry';   //exist in block scope
}
console.log(fruit1);
console.log(fruit2);    // results error - due to it exist in block scope
console.log(fruit3);    // results error - due to it exist in block scope }

foo();

Result

apple

error: fruit2 is not defined
error: fruit3 is not defined

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

What is a Lexical Scope variable?

A

Lexical scope means that a variable defined outside a function can access the inside of another function defined after the variable declaration. The inner functions are lexically bound to the execution context of their outer functions.

Ex
function func1(){
    var animal1 = "Lion";   //exist in Lexical scope
function func2(){    //Inner Function

    var animal2 = "Tiger"; //exist in function scope

    console. log(animal1);
    console. log(animal2);

}
func2();
console.log(animal2); // results error - due to it exist in function scope }

foo1();

Result

Lion
Tiger
error: animal2 is not defined

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

What is “Strict” mode?

A

JavaScript is a loosely typed scripting language. JavaScript allows strictness of code by using “use strict”; statement at the top of JavaScript code or in a function. The strict mode in JavaScript does not allow us to use undefined variables, reserved keywords as variable or function name, duplicate properties of an object, duplicate parameters of the function, assign values to read-only properties, Modifying arguments object, and Deleting an undeletable property. Strict mode can be applied to function level in order to implement strictness only in that particular function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

What is the “this” keyword and how does it behave in different contexts?

A

The this keyword is a reference variable that refers to the current object.

  • this alone: refers to a global Object.
  • this in a function: refers to the Global object [object Window].
  • this in Event Handlers: refers to the HTML element that received the event
  • this in Object Method Binding: refers to the object.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

How can Encapsulation be achieved in JavaScript?

A

Encapsulation means hiding information or data. The simplest way to create encapsulation in JavaScript is using closures. A closure can be created as a function with private state. When creating many closures sharing the same private state, we create an object.

EX.

const Book = function(t, a) {
   let title = t; 
   let author = a; 
   return {
      summary : function() { 
        console.log(`${title} written by ${author}.`);
      } 
   }
}
const book1 = new Book('Hippie', 'Paulo Coelho');
book1.summary(); // Returns Hippie written by Paulo Coelho.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

How is Inheritance achieved in JavaScript?

A

All JavaScript objects inherit properties and methods from a prototype. All JavaScript objects have a prototype. Browsers implement prototypes through the __proto__ property. In JavaScript, all functions are also objects, which means that they can have properties. Any time you create a function, it will automatically have a property called prototype. Thus, Functions also have a prototype property. When we call a function with new, it sets the returned object’s __proto__ property equal to the function’s prototype property. This is the key to inheritance. Inheritance in JavaScript is implemented through the prototype chain. Every normally created object, array, and function has a prototype chain of __proto__ properties ending with Object.prototype at the top.

Ex.

let animal = {
  eats: true
walk() {
    alert("Animal walk");
  }
};
let rabbit = {
  jumps: true
  \_\_proto\_\_: animal	// sets animal to be a prototype of rabbit.
};
// we can find both properties in rabbit now:
alert( rabbit.eats ); // true 
alert( rabbit.jumps ); // true
// walk is taken from the prototype
rabbit.walk(); // Animal walk

In the above example, when alert tries to read property rabbit.eats, it’s not in rabbit but JavaScript follows the prototype reference and finds it in animal.Also the walk() method is automatically taken from the prototype.

42
Q

What is JSON?

A

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.

43
Q

What is a JSON Object?

A

JSON Object is a set of key/value pairs enclosed within curly braces. A key is a string enclosed in quotation marks. A value can be a string, number, boolean expression, array, or object. A key value pair follows a specific syntax, with the key followed by a colon followed by the value. Key/value pairs are separated by comma. (“name” : “Andy”). We can store multiple JSON Objects in arrays.

EX - Single JSON object
var Book = {
"id": 110,	‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬
"language": "Python",
"author": ["John", "Ben"]
};

EX - JSON objects in array

var student =[

     { 
        "id":"01", 
        "name": "Tom", 
        "lastname": "Price" 
     }, 
     { 
        "id":"02", 
        "name": "Nick", 
        "lastname": "Thameson" 
     } 
  ] ;
44
Q

What are some applications of JSON?

A
  • Used to transmit data between the server and web application
  • JSON format helps transmit and serialize all types of structured data.
  • Allows us to perform asynchronous data calls without the need to do a page refresh.
  • Web services and Restful APIs use the JSON format to get public data.
45
Q

What is an array in JavaScript?

A

An array is a variable that allows the programmer to store more than one value. Arrays in JavaScript are objects and thus consist of key/value pairs and inherit from the Array prototype. Like objects, array values can consist of JavaScript primitives, or other JavaScript objects, including arrays and functions. Arrays in JavaScript are dynamic meaning they can be resized as needed.

46
Q

What does the splice() method do?

A

Allows us to remove a number of elements at a specific index. It can also allow us to replace those elements with something else. splice() returns an array containing all the values removed from the array.

47
Q

What does the pop() method do?

A

The pop() method removes and returns the last element in an array

48
Q

What does the shift() method do?

A

shift() method removes and returns the first element in an array.

49
Q

What does the sort() method do?

A

The sort() method will sort an array “in-place”. This means that the array will be modified and the original array will be sorted. The sort() method can take in a function that will compare objects and sort them to your preference. If no callback function is provided, each element is converted to a string and sorted in ascending order.

50
Q

What do the indexOf() & lastIndexOf() methods do?

A

The indexOf() method returns the first index at which an element is present. lastIndexOf() returns the last index at which an element is present. If the element can’t be found in the list, both will return the value -1.

51
Q

What do the find() & findIndex() methods do?

A

The find() method returns the first element in an array for which the callback function returns a truthy value. The findIndex() method does the same but returns that element’s index.

52
Q

What does the filter() method do?

A

The filter() function takes a callback function and creates a new array that is the made up of elements for which the callback function returns a truthy value. This can be useful in situations where you wish to perform an operation on only a subset of elements in an array. The original array is not modified.

53
Q

What does the map() method do?

A

The map() function takes a callback function and creates a new array that is the result of calling the function on each element of the array. The original array is not modified.

54
Q

What does the reduce() method do?

A

The reduce() function takes a callback function and returns a single value that is the result of calling the function for each value in the array.

55
Q

Why do we use Timing Events?

A

In JavaScript we make use of timing events when we are looking to automate tasks or run tasks after waiting a specific length. There are two key timing event methods in JavaScript and both are functions of the window object. These methods are setTimeout() and setInterval().

56
Q

What does the setTimeout() function do?

A

The setTimeout() function has the following signature:

window.setTimeout(callbackFunction, milliseconds)

This function executes the given callback function after waiting a specified number of milliseconds.

If you are waiting on a setTimeout() to execute and then change your mind, you can do so with the clearTimeout() function. This function has the following signature:

window.clearTimeout(timeoutVariable)

If the callback function has not been executed when clearTimeout is called, the execution will be cancelled. For this to work, however, we need the timeoutVariable, which is the return value of the setTimeout() function.

57
Q

What does the setInterval() function do?

A

setInterval() executes a function every on predefined intervals

window.setInterval(callbackFunction, milliseconds)

setInterval() will execute it’s callback repeatedly with an interval or pause in milliseconds between executions. Like setTimeout(), if we wish to cancel the execution, we can use the function clearInterval().

window.clearInterval(intervalVariable)

58
Q

What is an Error in JavaScript?

A

When things go wrong in JavaScript, the result usually involves the creation of an error object. There are two ways an error object can be created:

1) Runtime error: An error that is created as a result of something wrong with the code, such as a SyntaxError or ReferenceError.
2) User-defined error: An error built as part of your code to represent a problem that can occur. Errors can have many fields depending on the implementation, however the standard defines an error as having a name and message field.

59
Q

How can Errors be handled in JavaScript?

A

1) Try..Catch Block
A try block allows you to execute code. If that code would cause an error to occur, code execution would switch to an attached catch block so that you can handle the error.

2) Throw
If you define your own error, you’ll have to throw the error so that it can be handled. A throw statement causes the thrown object to be sent to an attached catch block. If there is no catch block, this will cause your code to cease execution entirely.

3)Custom Errors
If you’re going to be throwing your own errors, it would be best to make your own error object, so that it has a descriptive name.

EX - Prototype
function MyError(message) {
    this.name = 'MyError';
    this.message = message;
}
MyError.prototype = new Error;
try {
    throw new MyError('My message');
} catch(error) {
    console.log(error.name);
    console.log(error.message);
}
EX - Class
class MyError extends Error {
    constructor(message) {
        super(message);
        this.name = 'MyError';
    }
}
try {
    throw new MyError('My message');
} catch(error) {
    console.log(error.name);
    console.log(error.message);
}
60
Q

What is DOM in JavaScript?

A

The Document Object Model (DOM) is a programming API for HTML and XML documents. It enables Javascript to access and manipulate the elements and styles of a website. The browser creates a tree-like hierarchical representation of the HTML document, that tree-like structure is known as DOM Structure or a DOM tree. Each HTML element in the DOM tree is an object. The positions of the elements in the DOM tree are nodes.The tags are element nodes. Attributes in the elements are attribute nodes. The text inside elements is a text node. It may not have children and is always a leaf of the tree. The root of the DOM tree is a element, which is known as a document object.

61
Q

How can you query the DOM?

A

getElementById() - used to select an element based on its unique ID

getElementsByClassName() - used to select all the elements having specific class names. This method returns an array-like object of all child elements which have all of the given class names.

getElementsByTagName() - used to select HTML elements by tag name. This method also returns an array-like object of all child elements with the given tag name.\

querySelector() - finds the first element that matches a CSS selector

querySelectorAll() - finds all elements that match a CSS selector.

62
Q

How can you traverse the DOM?

A

The document object is the root of every node in the DOM. The topmost tree nodes are associated with document properties:

document. documentElement property - refers the DOM node of the tag.
document. head property - refers the DOM node of the tag.
document. body property - refers the DOM node of the tag.

The parent of any node is the node that is one level above in the DOM tree. There are two properties to get the parent — parentNode and parentElement.

parentElement property returns the “element” parent
parentNode returns “any node” parent. With the one exception of document.documentElement

The children of a node are the nodes that are one level below it.

childNodes property - returns a list of child nodes, including text nodes.
firstChild property - give access to the first child node.
lastChild property - give access to the last child node.

Siblings are nodes that are children of the same parent. The siblings of a node are any node on the same tree level in the DOM.

previousElementSibling property - give access to the previous sibling Node, i.e. the node that immediately precedes the specified node.
nextElementSibling property - give access to the next sibling vode, i.e. the node that immediately precedes or follows the specified node.

63
Q

How can you manipulate the DOM?

A

We can add, remove, replace, and copy any element into a DOM tree.

The createElement() method is used to create a new element and attach it to the DOM tree.

The replaceChild() method is used to remove an element from the DOM tree and insert a new one in its place.

The removeChild() method is used to remove an element from the DOM tree.

The appendChild() method is used to add a node to the end of the list of child nodes of a specified parent node.

The insertBefore() method is used to insert a node before another node as a child node of a parent node.

The textContent property is used to get and set a text content inside a particular node.

The innerHTML property to get the text and inner HTML elements inside a the particular element and the setting will replace the existing text and inner tags inside an element with the new content.

The cloneNode() method is used to clone an element. The cloneNode() method accepts an optional parameter. If the parameter value is true, then the original node and all of its descendants are cloned. If the parameter value is false, only the original node will be cloned.

getAttribute(attribute_name) method - Used to get the value of an attribute on a specified element

setAttribute(attribute_name, attribute_value) method - Used to set a value of an attribute on a specified element

removeAttribute(attribute_name) method - Used to remove an attribute with a specified name from an element

hasAttribute(attribute_name) method - Used to check an element has a specified attribute or not.

64
Q

What is the difference betweent the innerHTML property and the textContent property?

A

The innerHTML property returns the text and inner HTML elements. The textContent property returns only the text Content.

65
Q

What is an Event in JavaScript?

A

Events occur when user interaction takes place on a web page, such as when the end-user clicked a link or button, pressed a key on the keyboard, moved the mouse pointer, submits a form, etc. The browser also triggers events, such as the page load and unload events.

When an event occurs, we use a JavaScript event handler (or an event listener) to detect them and perform a specific task.

66
Q

What are some commonly used JavaScript Events?

A

onclick - This is a click event occurs when a user clicks the element on a web page.

ondblclick - This is a click event occurs when a user double clicks the element on a web page.

onload - This is a load event occurs when the browser has finished loading the page.

onunload - This is a load event occurs when a user closes the document.

onresize - This is a load event occurs when the browser window is minimized or maximized.

onmouseover - This is a mouse event occurs when the user moves the mouse over an HTML element.

onmouseout - This is a mouse event occurs when the user moves the mouse away from an HTML element.

onkeydown - This is a keyboard event occurs when the user presses down a key on the keyboard.

onkeyup - This is a keyboard event occurs when the user releases a key on the keyboard.

onfocus - This is a form-input event occurs when the user gives focus to an element on a web page.

onblur - This is a form-input event occurs when the user takes the focus away from a form element or a window.

onchange - This is a form-input event that occurs when a user changes the value of a form element.

onsubmit - This is a form-input event that occurs when the user submits a form on a web page.

67
Q

What is an EventListener in JavaScript?

A

An event listener is a function in JavaScript that waits for an event to occur. The addEventListener() function is an inbuilt function in JavaScript used to handle the event.

The Syntax of addEventListener() function: element.addEventListener(event, function, useCapture)

Where,

event - Specifies the name of the event.
function - Specifies the function to run when the event occurs
useCapture - It is an optional parameter takes a boolean value. If the parameter value is true then the event handler is executed in the capturing phase. If the parameter value is false then the event handler is executed in the bubbling phase.

The removeEventListener() method is used to remove an event handler that has been attached with the addEventListener() method.

68
Q

What is Event Bubbling?

A

In Event Bubbling, the event propagates from the target element to its parents, then all its ancestors that are on the way to top. Bubbling follows the Bottom to Top approach. Child -> Parent -> Grandparent

69
Q

What is Event Capturing?

A

In Event Capturing, the event propagates from the top element to the target element. Capturing follows the Top to Bottom approach. Grandparent -> Parent -> Child

70
Q

What is an Event Target?

A

Event Target is the target element that has generated the event in the DOM. The event.target is used to access the target element.

71
Q

How can we stop Event Propagation?

A

event.stopPropagation() method

It used to stop the event to travel to the bottom to top i.e. Event Bubbling. If you want to stop the event flow from event target to top element in DOM, we use event.stopPropagation() method.

event.stopImmediatePropagation() method

If an element has multiple event handlers on a single event, then even if one of them stops the bubbling, the other ones still execute. The event.stopPropagation() stops event bubbling but all other handlers will run. To stop the bubbling and prevent handlers on the current element from running, we use event.stopImmediatePropagation() method.

72
Q

What is the Event Object in JavaScript?

A

In JavaScript, events are represented by an Event Object. These objects all derive from the Event prototype, meaning that all events in JavaScript share certain properties.

73
Q

What are some common properties and methods that all JavaScript events share?

A

bubbles: a boolean value. A true value indicates that the event is bubbling, false indicates that it is capturing.

currentTarget: a reference to the DOM element whose event listener triggered this specific event. This is different from the event that initially triggered the event, as a single event can trigger multiple event listeners through propagation.

preventDefault(): Cancels the event, preventing the default action that would normally occur.

stopPropagation(): Prevents the event from propagating further.

target: a reference to the DOM element which triggered the event.

timeStamp: the time of the event in milliseconds

type: the type of the triggered event.

74
Q

What is the MouseEvent?

A

One of the first events most people encounter is the click event. That event along with several others, creates a MouseEvent. The MouseEvent has many properties that have to do with the state of the machine when the MouseEvent occured, such as the coordinates of the mouse relative to the window (clientX and clientY), the coordinates of the mouse relative to the last event (movementX and movementY), the coordinates of the mouse relative to the target element (offsetX and offsetY), the coordinates of the mouse relative to the screen (screenX and screenY), whether the alt, ctrl, or shift keys were depressed when the event was triggered (altKey, ctrlKey and shiftKey), and which mouse button was pressed (button, buttons, and which)

75
Q

What is the Keyboard Event?

A

The KeyboardEvent is often encountered when trying to add additional functionality to a webform. For example, you may wish to submit a form when the return key is pressed. For this, you have to have a KeyboardEvent that checks the key, keyCode, or which properties to determine whether or not the return key was the key that was pressed. Like the MouseEvent, we also have the altKey, ctrlKey, and shiftKey fields to determine if those buttons were pressed at the time of the event. Finally, we have a repeat property that determines if a key is being held down.

76
Q

What is AJAX?

A

AJAX stands for Asynchronous JavaScript And XML. Ajax describes the process of exchanging data from a web server asynchronously with the help of XML, HTML, CSS, and JavaScript. It just loads the data from the server and selectively updates some webpage parts without refreshing the page. Ajax uses the browser’s built-in XMLHttpRequest (XHR) object to send and receive data to and from a web server asynchronously, in the background, without blocking the page or interfering with the user’s experience.

77
Q

What is the AJAX workflow?

A

Ajax workflow starts from the client-side, on the browser. The steps involved in Ajax communication are as follows:

1 - A client event occurs on a webpage. (for example, the user clicks a button)
2 - JavaScript creates an XMLHttpRequest object.
3 - The XMLHttpRequest object makes an asynchronous request to the server.
4 - The server process the received HttpRequest.
5 - The server creates a response and sends data back to the browser.
6 - Browser process the returned data using JavaScript.
7 - The page content updated by JavaScript.

78
Q

What is the XMLHttpRequest Object?

A

An XMLHttpRequest (XHR) object used to make HTTP requests to the server and receive data in response.

79
Q

How can we send a request to a server using AJAX?

A

To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object.

open(method, URL, async)
method — Specifies the HTTP request method to use, such as “GET”, “POST”, etc.,

URL - Specifies the location of the server

async - Specifies whether the request should be handled asynchronously or not. If “true” then the script processing carries without waiting for a response. If “false” then the script waits for a response.

send() - Sends the request to the server. It accepts an optional parameter that allows us to specify the request’s body (used for POST).

In the GET method, the data is sent as URL parameters. In the POST method, the data is sent to the server as a part of the HTTP request body, which is not visible in the URL.

80
Q

How is a server response returned?

A

The Server Response returned in the form of responseText, responseXML, status, or statusText.

responseText - Returns the response as a string.

responseXML - Returns the response as XML.

status - Returns the status as a number (For example, 200: “OK”, 403: “Forbidden”,404: “Page not found”)

statusText -Returns the status as a string (e.g., “Not Found” or “OK”).

81
Q

What is the readyState property and what are the different readyStates?

A

The readyState property defines the status of the XMLHttpRequest:

readyState = 0 : Not intialized
readyState = 1 : Connection established
readyState = 2 : request received
readyState = 3 : processing request
readyState = 4 : request finished and response is ready
82
Q

How is JSON request payload sent in AJAX?

A

In JavaScript, to send a request using JSON data, we need to serialize our JSON object into a string. The JSON.stringify() method is used to convert an object to a string. Then, the server receives the string and processes the request.

EX
var data = {"name" : "Matt"};
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/demo", true);
//Use stringify() method to get string
xmlhttp.send( JSON.stringify( data ) );
83
Q

How are JSON response objects received in AJAX?

A

If the response from the server is string/text, we need to parse them into a JSON object. The JSON.parse() method converts a JSON string representation to a JSON object.

EX
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        //Use parse() method to convert JSON string to JSON object
        var responseJsonObj = JSON.parse(this.responseText);
    console.log( responseJsonObj.name );
    console.log( responseJsonObj.age );
} };

xmlhttp. open(“GET”, “/demo”, true);
xmlhttp. send();

84
Q

How are XML responses received in AJAX?

A

We normally wish to parse our response from JSON. Sometimes we might be dealing with an older server and we need to parse XML data. The responseXML field contains the data as a read-only Document Object Model.

EX
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var responseXml = this.responseXML;
    console.log( responseXml.getElementsByTagName('myTag') )
} };

xmlhttp. open(“GET”, “/demo”, true);
xmlhttp. send();

85
Q

What is the Fetch API?

A

The Fetch API provides a fetch() method defined on the window object. This method is used to send requests and returns a Promise that is retrieved from the response.

The syntax for the fetch() method: let promise = fetch(URL, [options])

86
Q

What is a Promise as it relates to the Fetch API?

A

A Promise object represents a value that may not be available now but, will be resolved in the future. It allows us to write asynchronous code.

The browser requests the server and returns a promise as a response. When the request is unable to make the HTTP-request due to network problems or the response has failure (HTTP-status code is 404 or 500), then the Fetch API rejects the Promise object.

When we get a response successfully from the server, the promise object is returned in the Response Body.

87
Q

What are the methods used to access the response body in various formats when using the Fetch API and what do they do?

A

response. text() – read the response and return as text.
response. json() – parse the response as JSON.
response. formData() – return the response as FormData object.
response. blob() – return the response as Blob (binary data with type).
response. arrayBuffer() – return the response as ArrayBuffer(low-level representation of binary data).

88
Q

What are other keywords associated with the fetch() method and the Fetch API?

A

We also use the async and await keyword with the fetch() method. The async keyword is added to functions to tell them to return a promise rather than directly returning the value. The await keyword only works inside async functions, used to pause the code on that line until promise gets complete.

async -An async function is a function that operates asynchronously via the event loop, returns a Promise object implicitly. async ensures that the function returns a promise.

await - The await keyword is only valid inside async functions. await makes JavaScript wait until that promise settles and returns its result.

89
Q

What is a Response Header?

A

The response headers are available in a Map-like headers object in response.headers.

They are used to get individual headers by name or to iterate over them.

90
Q

How are Request Headers set in the fetch() method?

A

To set a request header inside the fetch method, we can use the headers attribute.

EX
let response = fetch(protectedUrl, {
  headers: {
    Authentication: 'secret'
  }
});
91
Q

How can we make a POST request using the Fetch API?

A

To make a POST request, we need to mention the HTTP method (method)and request the body (body) inside the fetch method. The request body can be string, FormData object, or blob. If the request body is a string, then Content-Type header is set to text/plain; charset=UTF-8. If the request body is a JSON, then Content-Type header is set to application/json; charset=UTF-8. We don’t set Content-Type manually for blob object.

EX
async function asyncFunc() {
  let user = {
    name: 'John',
    surname: 'Smith'
  };
  // url is a server location 
  let response = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=utf-8'
    },
    body: JSON.stringify(user)
  });
  let result = await response.json();
  alert(result.message);
}

asyncFunc();

92
Q

How can we handle errors using the Fetch API?

A

The Fetch API generates a promise, meaning that if the request fails, it will cause the promise to enter the reject state. To handle this, we need to either surround our await instruction with a try…catch block or to append a catch() callback to our promise.

EX - try...catch block
async function asyncFunc() {
  let user = {
    name: 'John',
    surname: 'Smith'
  };
  // url is a server location 
  let response = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=utf-8'
    },
    body: JSON.stringify(user)
  });
  try {
    let result = await response.json();
    alert(result.message);
  } catch (error) {
    console.error(error);
  }
}

asyncFunc();

EX - appending catch
let user = {
  name: 'John',
  surname: 'Smith'
};
// url is a server location 
let response = fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  },
  body: JSON.stringify(user)
}).then((response)=>{
  let result = response.json();
  alert(result.message);
}).catch((error)=>{
  console.error(error);
});
93
Q

What is the executor as it relates to a Promise?

A

The function passed to new Promise is called the executor. When a promise object is created, the executor runs automatically. It contains the code which produces the result. The arguments resolve and reject are callbacks.

94
Q

What are the callbacks called when an executor obtains a result?

A

resolve(value) — if the job finished successfully, with the result value.

reject(error) — if an error occurred, the error is the error object.

95
Q

What are the allowed states for a Promise?

A

The Promise.status property, gives information about the state of the Promise object.

The promise object can have three states: pending, fulfilled, and rejected.

96
Q

How can Consuming Functions be registered?

A

A Promise object connects the executor and the consuming functions which will receive the result or error. Consuming functions can be registered using methods .then, .catch and .finally.

EX
var promise = new Promise(function(resolve, reject) { 
  const x = 5; 
  const y = 3;
  if(x >= y) { 
    resolve(); 
  } else { 
    reject(); 
  } 
}); 
promise. 
    then(function () { 
        console.log('Sucess! x have grater value'); 
    }). 
    catch(function () { 
        console.log('Error'); 
    });
97
Q

How can we create a JSON representation of a Java Object?

A

Just look at the notes.

https://github.com/220613-Reston-Java-Angular-AWS/Curriculum-Notes/blob/newMain/Week-5/Rest-with-JSON.md

98
Q

What are default function parameters in JavaScript?

A

In JavaScript, default function parameters allow us to initialize named parameters with default values if no values or undefined values are passed to the function.

Syntax: function fn(param1=defaultValue1,param2=defaultValue2,..) {
}

If there is no value for the default parameter in a function call, then the function takes the default value.

If we pass an undefined value for the default parameter in a function call, then the function takes the default value.

We can use other parameters as default values in the function.

EX
function add(x = 1, y = x, z = x + y) {
    return x + y + z;
}
//Here x=1, y=1, z=2
console.log(add());     //returns '4' 
//Here x=2, y=3, z=5
console.log(add(2,3));  //returns '10'
//Here x=3, y=3, z=5
console.log(add(3,undefined,5)); //returns '11'
99
Q

What is the Spread Operator?

A

The spread operator “…” provides the ability to expand iterable objects into multiple elements.

The spread operator expands the contents of the array into individual elements.
EX
// spread operator for copying  
let arr = ['a','b','c']; 
let arr2 = [...arr]; 
console.log(arr); // [ 'a', 'b', 'c' ] 
const arr =[1,2,3,4,5,6];
console.log(...arr);    //output: 1 2 3 4 5 6
const days = ["mon", "tue", "wed", "thurs", "fri", "sat", "sun"];
const.log(...days);    //output: mon tue wed thurs fri sat sun

The spread operator can used for combining arrays
EX
const arr1 = [2, 4, 6, 8, 10];
const arr2 = [3, 6, 9, 12, 15];

//combining arr1 and arr2 using spread operator
const arr = [...arr1, ...arr2];
console.log(arr);       // output: [2, 4, 6, 8, 10, 3, 6, 9, 12, 15]
//without spread operator
const array = [arr1, arr2];
console.log(array);     //output: [Array(5), Array(5)]

let merged = [0, …arr1, 0, …arr2];
console.log(merged); //output: [0, 2, 4, 6, 8, 10, 0, 3, 6, 9, 12, 15]

100
Q

What is the Rest Parameter?

A

The rest parameter “…” is used to represent an indefinite number of arguments as an array.

Syntax: The rest parameter (…) should be at the end of the function parameter. If the rest parameter(…) is at the beginning or in the middle of the function parameter list, it will result in an error.

function functionname[...parameters] //... is the rest parameter
{
statement;
}

E

101
Q

What is an Iterator?

A