Javascript Flashcards

(257 cards)

1
Q

What is the HTML format

A

<html><head>
</head>
<body> ...
<main>
</main>
</body>
</html>

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

is it a group practise to declare variables before you used them

A

True

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

Can the console change objects in the HTML browser

A

True

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

what do you use to create comments in JS

A

// for asingle line,
/*
*/ for paragraphs

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

What is short cut for commenting out a line of code for debugging purposes

A

Place the cursor on a line and type crtl /

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

What is short cut for commenting out multiple lines of code for debugging purposes

A

highlight the lines and type ctrl /

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

what characters is added to the end of lines of code

A

;

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

What does it mean when we say JavaScript is an “object-oriented” language?

A

JavaScript is modeled around objects with properties and methods which can be handled in a modular fashion.

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

What happens to the website and the code when you write code in the browser console?

A

Code in the browser console impacts the current browser instance only. It exists in the console for as long as the window is open.

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

What is an indicator of someone being a good JavaScript developer?

A

They follow standards, invest in learning, use formatting and linting tools for consistency, and write accessible code.

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

What is the natural environment for JavaScript?

A

The browser, server environments, and your computer.

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

What is ECMAScript?

A

The specification describing how browsers should implement and interpret JavaScript.

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

Where should you develop and test your JavaScript code?

A

Develop in a code editor, test in as many browsers as you can get your hands on.

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

Why have command line and automation tools become popular in JavaScript development?

A

They simplify complex processes and introduce features to help developers write better code.

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

How do you indicate to the browser that a section of a program is JS

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

Is it a good practice to place JS code at the end of a doc

A

False

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

What is antipattern

A

Loading JS at the footer

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

What is JS modules

A

Pieces of code save in files and importing/exporting them when they are needed. The code is saved under Script.JS file.

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

When does the browser execute JavaScript?

A

By default: When the script is encountered. If the script is set to “async”, when the script is fully loaded. If the script is set to “defer”, when the entire HTML page is rendered.

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

What happens when you defer JavaScript?

A

The browser loads the JavaScript asynchronously when it is encountered, then waits until all HTML is rendered before executing the script.

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

JavaScript modules are heavily used in frameworks like React and Vue. What is the advantage of using modules?

A

Modules enable modularization of code where individual functions, components, data objects, and other parts can be separated into individual files.

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

What is the correct markup for adding an external JavaScript file to an HTML document?

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

what do properties do in JS

A

Describe objects

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

What are methods

A

Properties changing features inside objects

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
What is the structure of constants
const backpack1 = { name : "Everyday backpack", volume : 30, lidOpen : "false", straplength : { left: 26, right : 26, toggleLid: function(lidStatus) { this.LidOpen = lidStatus; }, newStrapLength: function (lengthleft, LengthRight) { this.straplength.left = lengthLeft; this.straplength.right = lengthRight; }, } , }
26
What is the meaning of the keyword this?
Keyword refers to the current object
27
Cant we change objects inside a container
false
28
what is the structure of the properties
key: value pairs such as name: everyday backpack
29
How to display the property pocket Number of backpack object
console.log(" The pocket value:", backpack.PocketNum ); or console.log(" The pocket value:", backpack"[PocketNum]" ); this is more in control.
30
How to access an inner property of the object straplength
console.log("Strap lenght L:", backpack.strapLength.left );
31
When a function is inside an object is also known as
Method
32
What is the most easy syntax for defining a method of function expression.
ToggleLid : function (LidStatus) { this.LidOpen = LidStatus; };
33
What is non method function syntax for defining a method.
255
34
What is the structure for creating a class
Class Declaration --> class Name { constructor (//Define parameters 1 .. n) { //Define properties this.name = name; .. this.n = "n"}} or Class Expression --> const Name = class { }
35
Define a class definition of Backpack - Class Declaration
class Backpack { constructor( // Defines parameters: name, volume, color, pocketNum, strapLengthL, strapLengthR, lidOpen ) { // Define properties: this.name = name; this.volume = volume; this.color = color; this.pocketNum = pocketNum; this.strapLength = { left: strapLengthL, right: strapLengthR, };
36
Provide an example of Class Expression - using the class Backpack
import Backpack from "./Backpack.js"; const everydayPack = new Backpack( "Everyday Backpack", 30, "grey", 15, 26, 26, false ); console.log("The everydayPack object:", everydayPack); console.log("The pocketNum value:", everydayPack.pocketNum); The values match the definition of parameters.
37
At what point a class can be used in the code
Only after has been declared.
38
Where in the code we should do import of files
at the top of the code.
39
Are classes preferred over the constructed functions
True
40
Given the code below, how do you access the property named in let propName? let propName = "color" const myObject = { ID = 3,
color = "pink", propLength = 4, use = false };
Using bracket notation: myObject[propName]
41
In the following object, what is the code in the second line called? const myObject = { color: "pink" };
An object property with a property name and a property value.
42
Why is the best-practice to place objects inside constants?
So the object isn't accidentally altered or overwritten.
43
Which of the below object property names are not valid? const myObject = { propName = "property", // line 1 prop-name = "hyphenated", // line 2 3rdProp = "numbered", // line 3 $prop = "dollar", // line 4 %prop = "percentage", // line 5 prop name = "space" // line 6 };
Lines 2, 3, 5, and 6
44
How do you access an object in JavaScript?
No: If the class is a constant, this will cause an error. If the class is not a constant, the new object will overwrite the class.
45
How do you define an object in JavaScript?
Create a variable, give it a name, and assign it an object using curly brackets: const myObject = { // Properties and methods go here. };
46
What does the this keyword refer to in a class?
this refers to the current object created from the class.
47
Where do you go to find official documentation and code examples for standard built in (global) objects?
the MDN Web Docs for standard built-in objects
48
What is one advantage to using a class over an object constructor method?
Classes can be extended.
49
What is the established convention for formatting objects?
All properties and methods are listed on their own separate line.
50
What is the difference between a function and a method?
A function is a stand-alone function. A method is a function within an object.
51
Can you use arrow functions to create object methods?
No, object methods must be declared using function expressions or the method definition shorthand.
52
What is a template literal
is is an strategy to to utilise JavaScript to manipulate HTML when rendiring a document on the browser.
53
When creating a class, the prototype methods are added inside the constructor method.
False
54
What does the back ticks indicate to the browser
Any code inside is template literal meaning it is a mixture of HTML, JavaScript and Strings.
55
what does the browser do when reading an HTML file
It creates a document model. This document can be modified with JavaScript.
56
What is DOM
Document Object Model
57
what is the basic structure expression of if
if (variable - test){instructions of what to do}
58
What is the name of the content inside the function () Parenthesis
Arguments which are bits of data they need to do their job.
59
What does the break statement do
It breaks the current loop.
60
What is the basic structure of swtich
const food = "sushi"; switch (food) { case "sushi": console.log("Sushi is originally from Japan."); break; case "pizza": console.log("Pizza is originally from Italy."); break; default: console.log("I have never heard of that dish."); break; }
61
What is the syntax of class
class name { // class body } class name extends otherName { // class body }
62
Describe the syntax of a function used to create the area of an square.
function calcRectArea(width, height) { return width * height; } console.log(calcRectArea(5, 6)); // Expected output: 30
63
Can a variable declare by ""let be change during execution
True
64
What is "let'" declaration
The let declaration declares re-assignable, block-scoped local variables, optionally initializing each to a value.
65
What does const declared
The const declaration declares block-scoped local variables.
66
Can variables defined inside a function be accessible outside the function
False
67
What are the two types of scope
Local and Global scope
68
What are global variables
Variables declared outside the block.
69
What are local variables
They are declared inside a block.
70
What are the two special names for parameters
Default and REST parameters.
71
Why there is var keyword used in some programs
The var keyword is used in pre-ES6 versions of JS.
72
Is Let the preferred way to declare a variable
True
73
Variables that have not been initialized store the primitive data type undefined.
True
74
In ES6, template literals use backticks ` and ${} to interpolate values into a string.
True
75
What does the semicolon indicate to the code flow
Semi-colon tells the interpreter to stop parsing and begin compiling. An if statement does not end until after the else block.
76
What is another way to indicate is equal to
Is equal to: ===
77
What is another way to indicate is not equal to
Is not equal to: !==
78
what is this comparison indicator indicates ===
3 equals signs is known as Identity / strict equality, meaning that the data types also must be equal.
79
When is == used for
When using double equals in JavaScript we are testing for loose equality. Double equals also performs type coercion. Type coercion means that two values are compared only after attempting to convert them into a common type.
80
What is the Boolean outcome of this statement: false === 0
// false (Different type and different value)
81
What is the Boolean outcome of this statement: false == 0
// true; It has to do with falsy values in JavaScript. it’s because in JavaScript 0 is a falsy value. Type coercion will actually convert our zero into a false boolean, then false is equal to false.
82
What are the 6 falsy values in JavaScript
false — boolean false 0 — number zero “” — empty string null undefined NaN — Not A Number
83
What are consider to be ‘rules’ of falsy values
false, 0, and "" for example: false == 0 // true 0 == "" // true "" == false // true
84
How can I test if variable sale is true
if(sale) {} or if (sale === true) {}
85
What is the syntax for ternary operators
Variable ? expression 1 : expression 2
86
What is the syntax for SWITCH Keyword
Variable switch (variable) { case variable1 content : Statement1 case variable n content : Statement n }
87
What is the syntax for declaring functions
function keyword identifier () {statement}; function greetWorld () { console.log(Hello, world') }
88
What is a hoisting feature
access to function declarations before they’re defined.
88
What is the syntax for calling a function
function name()
89
What is the name of the input variables defined in the () of the function
Parameters
90
What is the name of the input values pass to the function ()
Arguments
91
Arguments can be passed to the function as
values or variables
92
When can we define default parameters
When there is an opportunity to be sure the parameters has a value.
93
When a function is called, the computer will run through the function’s code and evaluate the result. By default, the resulting value is undefined.
True.
94
What are helper functions
Function inside another function
95
What is the syntax for function expression
const identifier = function keyword(parameters) { statements }
96
What is call a function with no name
Anonymous function
97
Can function declaration be hoisted
False
98
What is implicit return
A function body composed of a single-line block does not need curly braces. Without the curly braces, whatever that line evaluates will be automatically returned. The contents of the block should immediately follow the arrow => and the return keyword can be removed.
99
What is scope
Scope defines where variables can be accessed or referenced.
100
Where are variables declared in terms of global scope
Outside the blocks.
101
What is block scope
When a variable is defined inside a block, it is only accessible to the code within the curly braces {}.
102
What is scope pollution
Scope pollution is when we have too many global variables that exist in the global namespace, or when we reuse variables across different scopes. Scope pollution makes it difficult to keep track of our different variables and sets us up for potential accidents.
103
What is index in an array
Each element in an array has a numbered position.
104
Zero-indexed
Meaning the positions start counting from 0 rather than 1. Therefore, the first item in an array will be at position 0.
105
Do we need brackets to print an entire array
False
106
What is pass by reference
So when you pass an array into a function, if the array is mutated inside the function, that change will be maintained outside the function as well. You might also see this concept explained as pass-by-reference since what we’re actually passing to the function is a reference to where the variable memory is stored and changing the memory.
107
Where can you find more info about method for working with arrays
Mozilla Developer Network website.
108
What is the process for for loop
A for loop contains three expressions separated by ; inside the parentheses: 1. an initialization starts the loop and can also be used to declare the iterator variable. 2. a stopping condition is the condition that the iterator variable is evaluated against— if the condition evaluates to true the code block will run, and if it evaluates to false the code will stop. 3. an iteration statement is used to update the iterator variable on each loop. for (let counter = 0; counter < 4; counter++) { console.log(counter); }
109
What are Getters
Getters are methods that get and return the internal properties of an object. But they can do more than just retrieve the value of a property!
110
How many data types are in JS
7: String, Number, Boolean, Null, undefined, and symbol. Objects
111
How to define an object iteral
let spaceship = {}; // spaceship is an empty object
112
How a object is fill in in JS
We fill an object with unordered data. This data is organized into key-value pairs. A key is like a variable name that points to a location in memory that holds a value.
113
within an object declaration, the key 'Fuel type' is declared under ', why
The answer is cause there is an space between words.
114
What are the ways to access objects
Dot notation and bracket notation
115
Donation uses the following syntax
let pilotcrew = spaceship20.homePlanet; let planetlista = spaceship20.color; console.log(pilotcrew); console.log(planetlista); console.log(spaceship20.homePlanet); // Returns 'Earth', console.log(spaceship20.color); // Returns 'silver',
116
Bracket notation uses the following syntax
let spaceship = { 'Fuel Type': 'Turbo Fuel', 'Active Duty': true, homePlanet: 'Earth', numCrew: 5 }; spaceship['Active Duty']; // Returns true spaceship['Fuel Type']; // Returns 'Turbo Fuel' spaceship['numCrew']; // Returns 5 spaceship['!!!!!!!!!!!!!!!']; // Returns undefined
117
Are objects mutable
True
118
One of two things can happen with property assignment:
If the property already exists on the object, whatever value it held before will be replaced with the newly assigned value. If there was no property with that name, a new property will be added to the object. It’s important to know that although we can’t reassign an object declared with const, we can still mutate it, meaning we can add new properties and change the properties that are there.
119
What is method
When the data stored on an object is a function. A property is what an object has, while a method is what an object does.
120
Are Objects passed by reference
True
121
functions which change object properties actually mutate the object permanently (even when the object is assigned to a const variable).
True
122
What are Getters
They are methods
123
What is this used for
This is used for accessing a property of an object within a method of included in the object. const goat = { dietType: 'herbivore', makeSound() { console.log('baaa'); }, diet() { console.log(this.dietType); } }; goat.diet(); // Output will be "ReferenceError: dietType is not defined"
124
What are getters
Getters are methods that get and return the internal properties of an object.
125
How do you call getter method
// To call the getter method - fullname: person.fullName; // 'John Doe'
126
What are some notable advantages of using getter methods:
Getters can perform an action on the data when getting a property. Getters can return different values using conditionals. In a getter, we can access the properties of the calling object using this. The functionality of our code is easier for other developers to understand.
127
Is asynchronous programming essential in Node.JS
True
128
What does .then() do
return a new promise object.
129
What does .catch() do
Returns a new Promise related to a previously rejected Promise in the chain. This is ideal for formatting error messages for potential Promise rejections.
130
What is Node.js
Node.js is a JavaScript runtime, an environment that allows us to execute our JavaScript code by converting it into something a computer can understand.
131
What is REPLs
REPLs are processes that read, evaluate, print, and repeat (loop), and Node.js comes with its own REPL we can access in our terminal with the node command.
132
How can code be organised
Code can be organized into separate files, modules, and combined through requiring them where needed using the require() function. Core modules are built into the Node.js environment to efficiently perform common tasks.
133
What does the console module do
The console module exports a global console object allowing the terminal to act as a debugging console, similar to the JavaScript console object provided by web browsers.
134
What does process do
The process module is a global module that gives access to information about the Node.js runtime environment.
135
What does util do
The util module contains methods used to maintain and debug your code.
136
What are modules
Modules are reusable pieces of code in a file that can be exported and then imported for use in another file. A modular program is one whose components can be separated, used individually, and recombined to create a complex system.
137
In JavaScript, there are two runtime environments and each has a preferred module implementation:
1. The Node runtime environment and the module.exports and require() syntax. 2. The browser’s runtime environment and the ES6 import/export syntax.
138
What is process.argv[2]
When a program is executed in the Node environment, process.argv is an array holding the arguments provided. In this case, it looks like ['node', 'celsius-to-fahrenheit.js', '100']. So, process.argv[2] returns 100.
139
What is module.exports
module.exports is an object that is built-in to the Node.js runtime environment. Other files can now import this object, and make use of these two functions, with another feature that is built-in to the Node.js runtime environment: the require() function.
140
What is require()
The require() function accepts a string as an argument. That string provides the file path to the module you would like to import.
141
If I run the file app.js with the terminal command node app.js sillyMode, how can I access the value sillyMode from within app.js?
process.argv2]
142
The object that a method belongs to is called
the calling object.
143
The this keyword refers to the calling object and can be used to
access properties of the calling object.
144
Methods do not automatically have access to other internal properties of the calling object.
True
145
The value of this depends on where the this is being accessed from.
True
146
We cannot use arrow functions as methods if we want to access other internal properties.
True
147
JavaScript objects do not have built-in privacy, rather there are conventions to follow to notify other developers about the intent of the code.
True
148
Setters and getter methods allow for more detailed ways of accessing and assigning properties.
True
149
There are different ways to use object destructuring:
one way is the property value shorthand and another is destructured assignment.
150
const refrigerator = { dairy: ['cheese', 'milk', 'sour cream'], temperature: 35, 'produce drawer': { vegetables: ['lettuce', 'broccoli', 'peas'], fruit: ['apples', 'berries', 'grapes'] } }
refrigerator['produce drawer'].fruit[0]
151
Which line of code would NOT print the value saved to the _num key in the tempObj object. let tempObj = { _num: 22, get num() { return this._num; } };
console.log(tempObj.num())
152
How can we call the method in the code below? let myObj = { sayHello() { return 'Hello there!'; } }
myObj.sayhello()
153
How can we add a property to the object below? let bikes = { schwinn: 'blue', trek: 'black' }
bikes['specialized'] = 'Red'
154
What will the following code output? const car = { numDoors: 4, isDirty: true, color: 'red' } for (let key in car) { console.log(key) }
numDoors isDirty color
155
Which of the following is an example of destructured assignment? const myDog = { name: 'Tadpole', breed: 'mutt', color: 'tan', weight: 32 }
let{name}=mydog
156
Which is the correct syntax for creating an object literal?
let myobject={ greeting: 'Hello' }
157
Which of the following statements is correct?
objects stored unordered data of any type as pair of keys values
158
What is a method?
A method is apropety with a function as its value
159
Which line of code would NOT print the value saved to the _num key in the tempObj object. let tempObj = { _num: 22, get num() { return this._num; } };
console.log(tempObj.num())
160
How can we add a property to the object below?\ let bikes = { schwinn: 'blue', trek: 'black' }
bikes['specialized'] = 'red'
161
Which of the following Object methods can be used to copy all of the properties of an object into a new object?
object.assig()
162
Which is the correct syntax for creating an object literal?
let myObject = { greeting:'Hello' };
163
What is a factory function?
A function that return an object
164
What should we add to the empty .withDiscount() method to return the cost of the meatballs object with a two dollar discount? let meatballs = { cost: 5, withDiscount() { } };
retun.thiscost -2;
165
What’s wrong with the setter method in the example below? let tempObj = { _num: 22, set num(numIn) { _num = numIn; } };
The setter should contain this.num in place of _num
166
In JavaScript, functions are first class objects
True
167
In JavaScript, functions are first class objects. This means that, like other objects you’ve encountered, JavaScript functions can have properties and methods.
True
168
How do we call functions that get passed in as parameters
callback functions; Callback functions get invoked during the execution of the higher-order function.
169
What is hoisting
JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables, classes, or imports to the top of their scope, prior to execution of the code.
170
In colloquial terms, any of the following behaviors may be regarded as hoisting:
Being able to use a variable's value in its scope before the line it is declared. ("Value hoisting") Being able to reference a variable in its scope before the line it is declared, without throwing a ReferenceError, but the value is always undefined. ("Declaration hoisting") The declaration of the variable causes behavior changes in its scope before the line in which it is declared. The side effects of a declaration are produced before evaluating the rest of the code that contains it.
171
Why there is no hoisting here: { var x = 1; } console.log(x); // 1
There's no "access before declaration" here; it's simply because var declarations are not scoped to blocks.
172
Is javascript case sensitive
True
173
is a semicolon necessary for each line
A semicolon is not necessary after a statement if it is written on its own line. But if more than one statement on a line is desired, then they must be separated by semicolons. It is considered best practice, however, to always write a semicolon after a statement, even when it is not strictly needed. This practice reduces the chances of bugs getting into the code.
174
What are the comments in JavaScript
// a one line comment /* this is a longer, * multi-line comment */
175
What is var
Declares a variable, optionally initializing it to a value.
176
What is let
Declares a block-scoped, local variable, optionally initializing it to a value.
177
What is const
Declares a block-scoped, read-only named constant.
178
What are the variable scope
Global scope: The default scope for all code running in script mode. Module scope: The scope for code running in module mode. Function scope: The scope created with a function.
179
variables declared with let or const can belong to an additional scope:
Block scope: The scope created with a pair of curly braces (a block).
180
What is the value of this code const randomNums = [1, 123, 25, 90, 3543, 42]; const foundElement = randomNums.findIndex(num => num > 200);
4
181
Where the error as log as
error stack trace
182
you should ask yourself every time you want to debug an error:
1. In what line did the error occur? You can almost always find this information on the first line of the stack trace in the following format /:. In this example, the location is app.js:1. This means that the error was thrown in the file named app.js on line 1. 2. What type of error was thrown? The first word on the fifth line of the stack trace is the type of error that was thrown. In this case, the type of error was ReferenceError. We will discuss this error type in the next exercise. 3. What is the error message? The rest of the fifth line after the error type provides an error message, describing what went wrong. In this case, the description is myVariable is not defined.
183
Here are three common error types:
1. SyntaxError: This error will be thrown when a typo creates invalid code — code that cannot be interpreted by the compiler. When this error is thrown, scan your code to make sure you properly opened and closed all brackets, braces, and parentheses and that you didn’t include any invalid semicolons. 2. ReferenceError: This error will be thrown if you try to use a variable that does not exist. When this error is thrown, make sure all variables are properly declared. 3. TypeError: This error will be thrown if you attempt to perform an operation on a value of the wrong type. For example, if we tried to use a string method on a number, it would throw a TypeError.
184
JavaScript calls the constructor() method every time it creates a new instance of a class.
True
185
What is the main difference between an object and class
The constructor method
186
why is this used inside the constructor method
Inside of the constructor() method, we use the this keyword. In the context of a class, this refers to an instance of that class. In the Dog class, we use this to set the value of the Dog instance’s name property to the name argument.
187
Class method and getter syntax is the same as it is for objects except you can not include commas between methods.
True
188
Get has a special syntax restriction
A getter must have exactly zero parameters.
189
The extends keyword makes
the methods of the animal class available inside the cat class.
190
The super keyword calls
the constructor of the parent class. In this case, super(name) passes the name argument of the Cat class to the constructor of the Animal class. When the Animal constructor runs, it sets this._name = name; for new Cat instances.
191
What is a framework
They are libraries of server side programming language that constructthe back end structure of a side so it makes it easier to write to maintain and to scale web applications and they provide us with tools and libraries that simplifies that simplified web development tasks.
192
What are the most popular frameworks
Rails - Ruby Django - Python Flask - Python Express - Node
193
What are the recommendations for starting in Cloud development
1. choose language and framework 2. Learn to serve content to the client. sending messages from my code to the client. 3. Basic API and HTTP methods (get, post, etc). Learn to send code from different locations 4 Connect to database 5 Build something on your own.
194
What are servers?
A server is a computer or program that provides services to other computers and programs, called clients, over a network. Servers are part of client-server architecture in which a client requests something and the server responds to the request. A well-known example of a server is a web server, where the client (web browser) requests a page and the server provides the page to the browser.
195
What is a client?
A client is a machine or program that depends on a server for some resource or service. The client will send a request to the server for the resource or service. Different physical locations make no difference to the client and server since they are connected through a mutual network such as the Internet.
196
The roles of a server include:
Sharing data between one or more client machines. Share resources, such as services or programs, between client machines. Distribute work to several connected machines.
196
Clients use a URL to connect to a server across the Internet. The URL has four main components:
1. A connection scheme, usually HTTPS (“Hypertext Transfer Protocol Secure”), browsers and web servers use to talk with one another. 2. A subdomain that specifies the particular server (usually organized by resource type) to be delivered to the client. 3. A domain name that specifies the name of the organization(s) associated with the URL. 4. A top-level domain that specifies the type of organization associated with the URL.
197
What happens when we request contact to a web site
1. The browser first communicates with the internet service provider (ISP). 2. This further communicates with the domain name server to get the IP address of the server. 3. The domain name server converts a domain name to an IP address. 4. Using this IP address, the browser connects to the server. 5. Once connected to the web server, our browser sends the request to the server and asks for particular files. 6. When the browser has connected to the server at the correct IP address, the servers send all the requested HTML text for the web page to our browser.
198
The commonly used server operating systems are:
Windows: UNIX Linux
199
Some of the most common types of servers are as follows:
1. A file server is used to store data files for multiple users. 2. A database server allows another computer to access the database and retrieve or upload data. 3. A web server delivers web pages requested by multiple client web browsers. 4. An application server provides a software environment with all the needed requirements. This server allows users to access the application without needing to download additional software. 5. The proxy server communicates with the websites you are visiting on your behalf. It links the user with the rest of the internet. The browser connects to the proxy server, and the proxy server sends your request to the website and sends the website’s response back to you
200
What is runtime
Runtime is the period of time during which a program is running, executing the specific instructions that make up the software. Runtime errors are common types of errors in software development. A runtime error is any error a program has while it is running.
201
What is Runtime Environment
The runtime environment is the infrastructure required to implement features in the language itself. This can include functions for optimization, memory management, debugging, and input/output. Runtimes make software development easier for engineers by making these functions more accessible.
202
In computer science, a process is
the instance of a computer program that is being executed. You can open Task Manager if you’re on a Windows machine or Activity Monitor from a Mac to see information about the various processes running on your computer right now. Node has a global process object with useful methods and information about the current process.
203
Is asynchronous programming essential to Node.js.
True
204
What does return do
The return statement ends function execution and specifies a value to be returned to the function caller.
204
What does "This " do
The this keyword refers to the context where a piece of code, such as a function's body, is supposed to run. Most typically, it is used in object methods, where this refers to the object that the method is attached to, thus allowing the same method to be reused on different objects.
204
What does "get" do
The get syntax binds an object property to a function that will be called when that property is looked up. It can also be used in classes.
205
What are events
Events are things that happen in the system you are programming, which the system tells you about so your code can react to them. For example, if the user clicks a button on a webpage, you might want to react to that action by displaying an information box. In this article, we discuss some important concepts surrounding events, and look at how they work in browsers. This won't be an exhaustive study; just what you need to know at this stage.
206
Are event handlers attached to events
True
207
What is event handler
This is a block of code (usually a JavaScript function that you as a programmer create) that runs when the event fires. When such a block of code is defined to run in response to an event, we say we are registering an event handler. Note: Event handlers are sometimes called event listeners — they are pretty much interchangeable for our purposes, although strictly speaking, they work together. The listener listens out for the event happening, and the handler is the code that is run in response to it happening.
208
What does addEventListener() do
The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target. Common targets are Element, or its children, Document, and Window, but the target may be any object that supports events (such as IDBRequest).
209
What is click
The HTMLElement.click() method simulates a mouse click on an element. When called on an element, the element's click event is fired (unless its disabled attribute is set). click()
210
Type JavaScript code to change colour every time a user click on a button
const btn = document.querySelector("button"); function random(number) { return Math.floor(Math.random() * (number + 1)); } function changeBackground() { const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`; document.body.style.backgroundColor = rndCol; } btn.addEventListener("click", changeBackground);
211
What is The Node.js Event emitter
If you worked with JavaScript in the browser, you know how much of the interaction of the user is handled through events: mouse clicks, keyboard button presses, reacting to mouse movements, and so on. On the backend side, Node.js offers us the option to build a similar system using the events module. This module, in particular, offers the EventEmitter class, which we'll use to handle our events.
212
Is JavaScript single-threaded.
True
213
What is thread
A thread is a sequence of instructions that a program follows. Because the program consists of a single thread, it can only do one thing at a time: so if it is waiting for our long-running synchronous call to return, it can't do anything else.
214
setTimeout() global function
The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.
215
What are promises
A Promise is an object representing the eventual completion or failure of an asynchronous operation. Since most people are consumers of already-created promises, this guide will explain consumption of returned promises before explaining how to create them.
216
What is DOM
he Document Object Model (DOM) is the data representation of the objects that comprise the structure and content of a document on the web. This guide will introduce the DOM, look at how the DOM represents an HTML document in memory and how to use APIs to create web content and applications. The Document Object Model (DOM) is the data representation of the objects that comprise the structure and content of a document on the web. This guide will introduce the DOM, look at how the DOM represents an HTML document in memory and how to use APIs to create web content and applications.
217
The .on() method takes two arguments
1. the name of the event 2. the listener callback function.
218
The .emit() method takes two arguments
1. the first argument the name of the event as a string 2. the data that should be passed into the listener callback function.
219
Many asynchronous Node APIs use error-first callback functions—callback functions which have
1. an error as the first expected argument and the 2. data as the second argument. If the asynchronous task results in an error, it will be passed in as the first argument to the callback function. If no error was thrown, the first argument will be undefined.
220
What does .toString() do
method translates the Buffer object into a human-readable string. It accepts three optional arguments: Encoding: Default is UTF-8. Start: The byte offset to begin translating in the Buffer object. Default is 0. End: The byte offset to end translating in the Buffer object. Default is the length of the buffer. The start and end of the buffer are similar to the start and end of an array, where the first element is 0 and increments upwards.
221
What does .concat()
two arguments: Array: Required. An array containing Buffer objects. Length: Optional. Specifies the length of the concatenated buffer.
221
What does .from() method
is provided to create a new Buffer object from the specified string, array, or buffer. The method accepts two arguments: Object: Required. An object to fill the buffer with. Encoding: Optional. Default is UTF-8.
222
What is sandboxing
When running JavaScript code on a browser, it’s important for a script to have only limited access to a user’s filesystem. This technique of isolating some applications from others.
223
What is The Node fs core module
is an API for interacting with the file system. It was modeled after the POSIX standard for interacting with the filesystem.
224
What is the syntax of Node JS fs.readFile() Method
fs.readFile( filename, encoding, callback_function ) filename: It holds the file’s name to read or the entire path if stored at another location. encoding: It holds the encoding of the file. Its default value is ‘utf8’. callback_function: A callback function is called after reading the file. It takes two parameters: err: If any error occurred. data: Contents of the file. Return Value: It returns the contents/data stored in file or error if any.
225
What is a promise
A promise is an asynchronous action that may complete at some point and produce a value. It is able to notify anyone who is interested when its value is available
226
What is stream
we practiced reading the contents of entire files into our JavaScript programs. In more realistic scenarios, data isn’t processed all at once but rather sequentially, piece by piece.
227
Blocking code runs synchronously and non-blocking code, such as timer functions, runs asynchronously.
True
228
Core modules are provided to developers to perform common tasks efficiently. Core modules are used by passing a string with the module’s name into the require() statement.
True
229
We can make our own instances of the EventEmitter class, and we can subscribe to listen for named events with the .on() method and emit events with the .emit() method.
True
230
Node allows for both output, data/feedback to a user-provided by a computer, and input data/feedback to the computer provided by the user. To handle errors during asynchronous operations, provided callback functions are expected to have an error as their first parameter.
True
231
The buffer module provides global Buffer objects used to represent a fixed amount of memory that can’t be resized.
True
232
The Node fs core module is an API for interacting with the file system.
True
233
What is Node.js module.exports
object to export code from a file - meaning its functions and/or data can be used by other files/modules.
234
What is Node.js require() function
import functions and/or data from another module.
235
Which of the following is the valid syntax to export this module in Node? Code let Robot = {}; Robot.name = 'Johnny'; Robot.sayName = (name) => { console.log(`My name is ${name}`); };
module.exports = robot;
236
What is event loop
Javascript is single threaded (one task at a time). a specific design that allows it to perform asynchronous tasks even while only using a single thread
237
What are Asynchronous Callbacks
One common example of asynchronicity in JavaScript is the use of asynchronous callbacks. This is a type of callback function that executes after a specific condition is met and runs concurrently to any other code currently running. Let’s look at an example: easterEgg.addEventListener('click', () => { console.log('Up, Up, Down, Down, Left, Right, Left, Right, B, A'); }); In the code above, the function passed as the second argument of .addEventListener() is an asynchronous callback — this function doesn’t execute until the easterEgg is clicked.
238
What is addEventListener()
he addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target. addEventListener(type, listener), type = A case-sensitive string representing the event type to listen for. Listener= The object that receives a notification (an object that implements the Event interface) when an event of the specified type occurs.
239
What is the syntax of SetTimeout()
setTimeout(functionRef, delay, param1) function = A function to be executed after the timer expires. function replace by code = An alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is not recommended for the same reasons that make using eval() a security risk. Delay = The time, in milliseconds that the timer should wait before the specified function or code is executed. If this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, the next event cycle.
240
What is the heap
They are data structures part of the javascript engine. The heap is a block of memory where we store objects in an unordered manner. JavaScript variables and objects that are currently in use are stored in the heap.
241
The event loop is made up of these parts:
1.Memory Heap 2. Call Stack 3. Event Queue 4.Event Loop 5. Node or Web APIs
242
The Call Stack
The stack, or call stack, tracks what function is currently being run in your code. When you invoke a function, a frame is added to the stack. Frames connect that function’s arguments and local variables from the heap. Frames enter the stack in a last in, first out (LIFO) order. In the code snippet below, a series of nested functions are declared, then foo() is called and logged.
243
The Event Queue
The event queue is a list of messages corresponding to functions that are waiting to be processed. In the diagram, these messages are entering the event queue from sources such as various web APIs or async functions that were called and are returning additional events to be handled by the stack. Messages enter the queue in a first in, first out (FIFO) order. No code is executed in the event queue; instead, it holds functions that are waiting to be added back into the stack.
244
What the async keyword is used for
to write functions that handle asynchronous actions. We wrap our asynchronous logic inside a function prepended with the async keyword. Then, we invoke that function. async function myFunc() { // Function body here }; myFunc();
245
246
async functions always return a promise. This means we can use traditional promise syntax,
like .then() and .catch with our async functions. An async function will return in one of three ways: If there’s nothing returned from the function, it will return a promise with a resolved value of undefined. If there’s a non-promise value returned from the function, it will return a promise resolved to that value. If a promise is returned from the function, it will simply return that promise
247
async...await is syntactic sugar built on native JavaScript promises and generators.
True
248
Inside an async function we use the await operator to pause execution of our function until an asynchronous action completes and the awaited promise is no longer pending .
True
249
await returns the resolved value of the awaited promise.
True
250
We can write multiple await statements to produce code that reads like synchronous code.
True
251
We use try...catch statements within our async functions for error handling.
True
252