JavaScript Flashcards

1
Q

What is JavaScript

A

JavaScript is a lightweight programming language that web developers commonly use to create more dynamic interactions when developing web pages, applications, servers, and or even games. It runs on the client-side, meaning it executes in the web browser of the person visiting the website.

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

Difference between Java and JavaScript

A

JavaScript and Java are similar in some ways but fundamentally different in some others. The JavaScript language resembles Java but does not have Java’s static typing and strong type checking. JavaScript follows most Java expression syntax, naming conventions and basic control-flow constructs which was the reason why it was renamed from LiveScript to JavaScript.

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

Describe what is JavaScript DataTypes
Identify the benefits of using JavaScript DataTypes

A

JavaScript DataTypes refer to the different types of values that can be assigned to variables in the JavaScript programming language. In JavaScript, variables are not explicitly declared with a data type, but the data type is automatically determined based on the value assigned to the variable.

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

Describe what is JavaScript Variable Scopes

A

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

Global Scope
Variables defined outside any function, block, or module have global scope. The global scope variables are accessed everywhere in the application.

Local Scope
Local Scope used to refer to Function-local scope, but following the introduction of block scope, this term is considered ambiguous and should not be used. The local scope has divided into the function scope, the block scope and the lexical scope. The block scope concept is introduced in ECMA Script 6 (ES6) together with the new ways to declare variables - const and let.

Function Scope
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.

Block Scope
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.

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

Hoisting
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 as shown below.

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

Describe what is let and const keywords in JavaScript

A

let: The let keyword allows you to declare variables that are block-scoped. Block scope refers to the portion of code within curly braces {}. Variables declared with let are limited in scope to the block in which they are defined. They are not accessible outside of that block. This helps prevent variable name clashes and unintended scope pollution.

const: The const keyword is used to declare variables that have a constant value, meaning their value cannot be reassigned after declaration. Like let, const is also block-scoped. When using const, you must assign a value to the variable at the time of declaration, and you cannot reassign it later.

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

What is an array 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.

Creating an Array In JavaScript, arrays can be created using square brackets, using what is known as an array literal. They can also be created using the new keyword, but it is best practice to use array literals.

All array objects share a common structure. Each array has a length field that stores the current length of the array. In addition, the prototype of an array is [], giving each array access to certain function.

Arrays in JavaScript are zero-indexed, meaning that the first element in an array is represented by the key 0.

Changing the Array Length - JavaScript is a dynamic language and arrays are no different. the length of an array can be changed in several ways.

Adding an Item - To add an item to an array you can specify an index

Removing an Item - Removing an item from an array in JavaScript can result in unexpected behavior if done incorrectly. When removing a key from an object, you might use the delete keyword. When you do this with an array, the length field will not be updated, resulting in an empty slot.

Arrays are iterable, and so you can use a for-in or for-of loop to iterate through an array. for-in will iterate through the keys of an array. for-of will iterate through the values of the array.

There is also the forEach() method on the Array Prototype. This function is a functional array method that takes in a callback function and runs that function for each element in the array. The forEach() method returns undefined.

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

What is a function in JavaScript

A

A function is a group of reusable code which can be called anywhere in the program. A JavaScript function is defined using the function keyword.

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

Describe what is this keyword

A

The this keyword in JavaScript refers to the context in which a function is executed.
In method invocations, this refers to the object on which the method is invoked.
In constructor functions, this refers to the newly created instance of the object.
In event handlers, this typically refers to the element that triggered the event.
In the global scope or default function context, this refers to the global object (e.g., window).
Arrow functions do not have their own this value but inherit it from the surrounding scope.
Remember, the behavior of this depends on the specific usage and how a function is invoked.

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

Describe what is 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
10
Q

Difference between == and ===

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
11
Q

What is falsy

A

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

Obviously 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
12
Q

What is Truthy

A

In JavaScript, any expressions or value that results in boolean true value, are considered as Truthy. Any expression or value other than above listed falsy values – is considered truthy

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

Selecting elements from the DOM

A

JavaScript is used to get or modify the content or value of the HTML elements on the page. To perform any action on the HTML element, we need to select the target HTML element.

4 different ways

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

Selecting Elements by ID

A

The getElementById() method is used to select an element based on its unique ID. The getElementById() method will return the element as an object if the matching element was found, or null if no matching element was found in the document.

<body>
<p>This is a paragraph.</p>

<script>
document.getElementById("demo").innerHTML = "Paragraph Changed";
</script>

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

Selecting Elements by Tag Name

A

The getElementsByTagName() method 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.

<body>
<h1> Heading </h1>
<p>This is a paragraph of text.</p>
<div>This is another paragraph of text.</div>
<p>This is one more paragraph of text.</p>

<script>
var matches = document.getElementsByTagName("p");
        
        for(var elem in matches) {  
        matches[elem].style.background = "red";
        }
</script>

</body>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Selecting Elements with CSS Selectors

A

We can use querySelector() and querySelectorAll() methods to select elements that matches the specified CSS selector. The querySelector() finds the first element that matches a CSS selector whereas the querySelectorAll() finds all elements that match a CSS selector.

<body>
<p>This is a paragraph</p>
<ul>
<li>Apple</li>
<li>Orange</li>
<li>Mango</li>
</ul>

<script>
var matches = document.querySelectorAll("ul li");
 
    for(var elem of matches) {  
        document.write(elem.innerHTML + "<br>"); //outputs: "Apple Orange Mango"
    }
      document.write(document.querySelector('#para').textContent); //outputs: "This is a paragraph"
</script>

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

DOM Manipulation

A

We can add, remove, replace, and copy any element into a DOM tree. DOM Manipulation methods are listed below:

18
Q

Create Elements

A

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

19
Q

Replace Child Elements

A

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

20
Q

Remove Child Elements

A

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

21
Q

Append a Node

A

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

22
Q

Insert a Node before another

A

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

23
Q

Insert a Node After another

A

JavaScript DOM provides the insertBefore() method that allows you to insert a new after an existing node as a child node. However, it hasn’t supported the insertAfter() method yet.

So, we can insert a new node after an existing node as a child node, by selecting a parent node of the existing node and call the insertBefore() method on the parent node to insert a new node before that immediate sibling node.

24
Q

Get or Set text of a Node

A

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

25
Q

Get or Set HTML of Element

A

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.

26
Q

Clone a Node

A

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.

27
Q

Managing Attributes

A

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.

28
Q

Event handlers and event listeners

A

Event handlers and event listeners are both used in JavaScript to respond to events triggered by user interactions or other actions. They allow you to execute code in response to events such as clicks, mouse movements, keyboard input, or changes in the document.

29
Q

Event Handlers:

A

Event handlers are functions that are directly assigned to an event property of an HTML element. They define the behavior or action to be executed when the associated event occurs. Event handlers can be defined inline within HTML attributes or assigned programmatically using JavaScript.

30
Q

Event Listeners:

A

Event listeners are functions that are attached to elements to listen for specific events. Unlike event handlers, event listeners can handle multiple events for an element, and they provide a more flexible and organized way to manage event-driven code.

31
Q

Event listeners offer advantages over event handlers:

A

Separation of Concerns: Event handling logic is decoupled from the HTML markup, promoting better code organization and maintainability.

Multiple Event Handling: Event listeners allow you to attach multiple event handlers to the same element, enabling more complex event interactions.

Dynamic Event Handling: Event listeners can be added or removed dynamically at runtime, allowing for more flexible event management.

32
Q

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.

33
Q

Event Capturing

A

In Event Capturing, the event propagates from the top element to the target element. Capturing follows the Top to Bottom approach.

34
Q

async keyword

A

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

35
Q

await

A

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

36
Q

give an analogy for Async and Await keyword

A

Analogy: Waiting for a Pizza Delivery

Imagine you’re ordering a pizza for delivery. The process of ordering, preparing, and delivering the pizza involves multiple steps that take time to complete. In this analogy, the pizza delivery process represents an asynchronous operation, and you are the caller of this operation.

  1. Without async/await:
    Ordering the pizza without async/await is like placing the order and being given a ticket with a promise that your pizza will be delivered. You’re free to do other things while waiting, but you need to periodically check if the pizza has arrived by using the ticket. Once the ticket is resolved, you can collect your pizza.
  2. With async/await:
    Using async/await is like placing the order and receiving a notification that the pizza will be delivered. However, instead of constantly checking for updates, you can simply await the delivery at your doorstep. The await keyword allows you to pause the execution of your actions until the pizza has arrived. Once the delivery is complete, you can resume your tasks with the pizza readily available.

In this analogy, the async function represents the pizza delivery service, and the await keyword represents your willingness to wait for the delivery to complete before continuing with other tasks. This way, you can write code that reads more synchronously, making it easier to manage asynchronous operations and handle the results when they become available.

37
Q

Template Literals

A

Template literals are a new feature introduced in ECMAScript 2015/ ES6. It provides an easy way to create multiline strings and perform string interpolation. Template literals are the string literals and allow embedded expressions.

Template literals are strings that enclosed within the backtick character(`). Template literals allow for embedded expressions (placeholders), which are indicated by the dollar sign and curly braces ($(expression}). These expressions can be used to evaluate code.

Multiline strings
We use the escape character, represented as \n, to give a new line for creating a multiline string. In Template Literals, there is no need to add \n at the end when the string enclosed within the backtick (`) character. Template literals used to create the new line by literally moving a string to a new line without using any character.

console.log(I am the first line I am the second line I am the third line);
String Interpolation
In JavaScript, the template literals give support for string interpolation. Template literals perform string interpolation using embedded expressions, ${}, which are replaced with the value of the code within it.

function sayHello(){
return “Hello World!!!”
}
var x = 10;
var y = 20;
document.write(${sayHello()}, The product of the variables ${x} and ${y} are ${x*y});

38
Q

Arrow Functions

A

They save developers time and simplify function scope.

Also, reduce takes two parameters, brackets are needed to prove it clear that the parameters are present for the arrow function, and not for the reduce call.

Arrow functions could have multiple statements within, in which case you need to use a block. You are also required to use the return keyword.

39
Q

Promise

A

An object that encapsulates the result of an asynchronous operation let asynchronous methods return values like synchronous method

40
Q

Closure

A

A function with preserved and private data. Gives you access to an outer functions scope, from an inner function

Helps with data security

document.getElementById(“loginButton”).onclick = login();

//userInbox = 420.69;

function login(){
let userName = “Bro”;
let userInbox = 1;

function alertUser(){
    alert(`${userName} you have ${userInbox} new messages!`);
    userInbox = 0;
}

return alertUser; }
41
Q

Fetch

A

fetch(): It is used to fetch a resource. Headers: It represents response or request headers, letting us to create a query and take different actions depending on the outcomes. Request: It represents a resource request. Response: It represents the response to a request.

The Fetch API is a modern JavaScript API for making asynchronous network requests in the browser. It provides a streamlined way to fetch resources from a server and handle the response.

With the fetch() function, you can make requests and receive a Promise that resolves to a Response object representing the server’s response.

You can handle the response using methods like .then() and .catch(). For example, you can check response.ok to see if the request was successful and use response.json() to parse the response data.

The Fetch API supports various HTTP methods and allows you to set custom headers. It’s a more modern alternative to older methods like XMLHttpRequest, simplifying network requests and response handling.

In summary, the Fetch API is a powerful tool for making asynchronous network requests and working with server responses in JavaScript web applications.