Basic JavaScript Flashcards

1
Q

What is JavaScript and what do we need it for?

A

JavaScript is a scripting or programming language that allows you to implement complex features on web pages. To better understand what JavaScript does, analyze it in the context how it talks with HTML and CSS:

  • HTML is the markup language that we use to structure and give meaning to our web content, for example defining paragraphs, headings, and data tables, or embedding images and videos in the page.
  • CSS is a language of style rules that we use to apply styling to our HTML content, for example setting background colors and fonts, and laying out our content in multiple columns.
  • JavaScript is a scripting language that enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Difference between Compiled and Interpreted language?

A

Code compilation is a set of steps that process the text of your code and turn it into a list of instructions the computer can understand. Typically, the whole source code is transformed at once, and those resulting instructions are saved as output (usually in a file) that can later be executed.

Interpretation performs a similar task to compilation, in that it transforms your program into machine-understandable instructions. But the processing model is fairly different. Unlike a program being compiled all at once, with interpretation the source code is typically transformed line-by-line.

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

4 ways of displaying data with JavaScript

A

Writing into an HTML element, using innerHTML.
Writing into the HTML output using document.write().
Writing into an alert box, using window.alert().
Writing into the browser console, using console.log().

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

Ways of commenting code

A

// Single line comments

/*Multi line
Comment
*/

CTRL+ /

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

What is a variable?

A

In programming, just like in algebra, we use variables (like price1) to hold values.
In programming, just like in algebra, we use variables in expressions (total = price1 + price2).

All JavaScript variables need to be identified with unique names (identifiers)

The attributes of a variable are:

  • name
  • identifier (identifies place in memory)
  • value
  • we can also add one more attribute - lifetime of a function, which is dependent on the scope.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are falsy values?

A

The falsy values in JavaScript are 0, 0n, null, undefined, false, NaN, and the empty string “”. They evaluate to false when coerced by JavaScript’s typing engine into a boolean value, but they are not necessarily equal to each other.

To the contrary, the values below are truthy:
“string”, 42, [], {}, function foo() {}

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

Operands and operators

A

Mathematically, anoperationis a calculation on one or more values calledoperandsmapping to an output value. An operator is a symbol/sign that maps operands to output values.

x + y = z

In the equation above x and y are operands, + and = are operators while z is the result

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

What are unary operators?

A

A unary operation is an operation with only one operand. Unary operators are more efficient than standard JavaScript function calls. Additionally, unary operators can not be overridden, therefore their functionality is guaranteed.

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

What are the types of unary operators?

A
Unary plus (+) Tries to convert the operand into a number*
Unary negation (-) *Tries to convert the operand into a number and negates after
Logical Not (!) Converts to boolean value then negates it
Increment (++) Adds one to its operand
Decrement (--) Decrements by one from its operand
Bitwise not (~) Inverts all the bits in the operand and returns a number
typeof Returns a string which is the type of the operand
delete Deletes specific index of an array or specific property of an object
void Discards a return value of an expression.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How to create a valid variable name.

A

To create a variable name you need to:
Start with One of: _ $ letter
Followed by Zero or More: _ $ letter number

Variables that begin with _ usually denote that this variable will be private in some way

Variables starting with $ are usually for automatically generated code.

__proto__ variables reserved for non-standard features

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

What is the main difference between var and let keywords?

A

Main difference is scoping rules
to be continued..

Hoisting
let variables are not initialized until their definition is evaluated. Accessing them before the initialization results in a ReferenceError. Variable said to be in “temporal dead zone” from the start of the block until the initialization is processed.
Redeclaration
In strict mode, var will let you re-declare the same variable in the same scope while let raises a SyntaxError.
Leakage
When you declare let variables inside of a code block, it is declared just inside this code block, while doing it with var keyword would leak the variable when called outside of the block. var variables DO NOT have block scope.

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

What are types of values in JS

A

Primitives: Boolean, Null, Undefined, Number, String
Technically - also Symbol and BigInt
1 complex: Object

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

How we can interpolate variable into a string?

A

You can put strings in “”,
‘’,
or backticks ``

By using backticks you can embed js code into a string like Hello, ${userName}

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

What value do you set the variable to, if you want to wipe out the value?

A

It is best practice to set the variable to null.
Undefined means that we have not initialized a variable in script, while null will show that the programmer set the value himself

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

What you should keep in mind when compare results of calculations to a literal (especially in an if clause)?

A

That JavaScript uses inaccurate floating point numbers.

When you make calculations, try to bear in mind that you need to use toFixed() function

However toFixed() method converts to a string, to convert to a number you need to use ‘+’ sign before the expression.

as in example:

if ( +(1.1 + 1.3).toFixed(2) == 2.4){
showMessage(‘true’);
}

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

What is the role of ternary operator?

A

Ternary operator is essentially a short-cut to if statements. They also allow us to input a value to a variable, where standard if /else statement couldn’t do it

// (condition) ? true-stement : false-statement;
let message = ( price > 10 ) ? ‘expensive’ : ‘cheap’
showMessage(message); //expensive

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

What is the role of symbol?

A

Symbols can be used inside of an object to hide information.

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

What is the difference between slice and splice methods?

A

Both methods are allowing us to manipulate arrays.

splice() changes the original array whereas slice() doesn’t but both of them returns array object. Splice also allows us to replace values that were deleted.

slice(0,4) - will return an array starting from index 0, but index 4 will not be included [0, 1, 2, 3];

splice(1,2) - will return an array starting from index 1 and will be two element

splice(3,1, ‘hamster’) - will replace the element at 3rd index with ‘hamster’

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

What are rest parameters?

A

Rest parameter- Collects all remaining arguments into an actual array.

function sumAll(...nums) {
   let total = 0;
   for (let n of nums) total+=n;
   return total
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is destructuring and how can it be applied

A

Destructuring is a short, clean syntax to ‘unpack’:
- values from arrays
- properties from objects
Into distinct variables.

const [gold, silver, bronze] = raceResults;
const {first,last} = runner;

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

What is spread?

A

Spread syntax allows us to take an array and spread its elements so they can be assigned to parameters.

Spread has many usecases:
1) Spread for Function Calls (Expands and iterable into a list of arguments)
const nums = [9,3,2,8]
Math.max(…nums) //same as calling Math.max(9,3,2,8)
2) Spread in Array Literals (Create a new aray using an existing array. Spreads the elements from one array into a new array)
[…nums1, …nums2, 7, 8, 9] // Can also be used to make a copy of an array
3) Spread in object literals (Copies properties from one object into another object literal)

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

What does continue keyword do to a loop?

A

The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop.

As in example:
for (let i=0; i<5; i++) {
if (i===3)
continue;
console.log(i);
}
0 1 2 4 will be printed
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What are IIFE’s?

A

Immediately Invoked Function Expression.
By Immediately invoked we mean that it is ran immediately after it’s declared.

You can close the function in parenteses and then immediately invoke it:
(function() {
console.log(“Example”);
})();

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

What are the differences between call an apply functions

A

call and apply are both used to change the value of this. within a function.

With call and apply functions we are allowed to pass an object to a function.

let welcome = function(){
console.log(‘Hello “ + this.name);
}
welcome.call(person1) // Hello John

Thedifference between call and apply is that call requires the arguments to be passed in one-by-one, and apply takes the arguments as an array.

Use apply() when the input parameter is already in the form of array with similar elements

Use call if you are dealing with multiple arguments that are not really related to each other

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

What bind function does?

A

While call and apply functions allow us to call a function and change the this. value.

We call bind. on a function and it makes a copy a function and assings a new context (a value that has been assigned by this.).

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

What are arrow functions and how do they behave?

A

ES6 arrow functions can’t be bound to a this keyword, so it will lexically go up a scope, and use the value of this in the scope in which it was defined.

The big change:
Arrow functions do not have their own “this” value.
“this” refers to the enclosing context. The value of this is always inherited from the enclosed scope.

Regular functions’ this value refers to the object that holds the function.

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

How do you add default parameters for a function?

A
function(carId, city= 'NY'){
}

Whenever the function is called with only carId argument, the default one for city will be ‘NY’.
Introduced in ES6.

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

What is a constructor?

A

A constructor is a function that gets executed when a new instance of an object is created.

For constructor function to work properly we need to declare new object with new keyword.

let vehicle = new Car();

because this. in constructor function 
function Car() {
console.log(this);
}
is referred to the global scope if we simply call Car();

The most important thing to keep in mind when working with objects like this and constructor functions is to use this. keyword, to access the context of the object.

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

What are prototypes used for?

A

The problem with constructor object is that when we create 100.000 objects like this, the functions would be replicated 100.000 times.
That’s where prototypes come in.

User.prototype.usrCreated = function(){
console.log(“User “ + this.userName+’#’+this.userId +’ has been created!’);
};
When you use prototypes remember that you still need to reference to the object with this. keyword

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

What is the best method to iterate over an array?

A

There are better methods than using for loop on an array to iterate over elements.

Arrays have a method called: forEach that calls function on each elements of the array.

carIds.forEach( (car, index) => console.log(car, index));

31
Q

What is a recursive function?

A

Recursive function is a function that calls itself. Recursion is the concept that a function can be expressed in terms of itself. Usually, this case would be broken down in a for loop.

  function multiply(arr, n) {
    if (n <= 0) {
      return 1;
    } else {
      return multiply(arr, n - 1) * arr[n - 1];
    }
  }

Recursive functions must have a base case when they return without calling the function again

32
Q

What is a fallback value?

A

A fallback value is a value you would use when the main thing you requested is not available.

Fallback value in JS is defined with export/import module that were added in ES6.
by adding default export, you add the fallback value when the module is imported.

By using an export default, you do create a fallback value.
When you try to import something with a name that hasn’t been specified among the named exports, what you will import is the fallback value given by the export default (if present).

33
Q

How do you prevent object mutation?

A

const declaration alone doesn’t really protect your data from mutation. To ensure your data doesn’t change, JavaScript provides a function Object.freeze to prevent data mutation.

Once the object is frozen, you can no longer add, update, or delete properties from it. Any attempt at changing the object will be rejected without an error.

Add:
You cannot change object with changing the variables using . notation, however you can change it using square brackets.

34
Q

What is a promise?

A

A promise in JavaScript is exactly what it sounds like - you use it to make a promise to do something, usually asynchronously. When the task completes, you either fulfill your promise or fail to do so. Promise is a constructor function, so you need to use the new keyword to create one. It takes a function, as its argument, with two parameters - resolve and reject.

A promise has three states: pending, fulfilled, and rejected.

Promises are most useful when you have a process that takes an unknown amount of time in your code (i.e. something asynchronous), often a server request. When you make a server request it takes some amount of time, and after it completes you usually want to do something with the response from the server.

35
Q

What are classes?

A

Classes play the same exact role as the contructor functions.
They are templates for creating objects end encapsulating logic related to that objects.

36
Q

What are switch statements and when they should be used?

A

Switch statements are similar to if/else statements.

If you have many options to choose from, use a switch statement. A switch statement tests a value and can have many case statements which define various possible values. Statements are executed from the first matched case value until a break is encountered.

If you have many options to choose from, a switch statement can be easier to write than many chained if/else if statements

37
Q

What are the benefits of functional programming

A

A function, ideally, should be a pure function, meaning that it does not cause any side effects. Changing or altering things is called mutation, and its outcome a side effect.

1) Don’t alter a variable or object - create new variables and objects and return them if need be from a function.
2) Declare function arguments - any computation inside a function depends only on the arguments, and not on any global object or variable. Also, it is good to always declare your dependencies explicitly.

38
Q

How does reduce() method work?

A

Reduce is the most general of all array operations in JS. The reduce method iterates over each item in an array and returns a single value (i.e. string, number, object, array). This is achieved via a callback function that is called on each iteration.

const sumOfAges = users.reduce((sum, user) => sum + user.age, 0);

39
Q

Explain arr.sort method for sorting strings and numbers

A

Sort method sorts the elements according to callback function. It is advised to use the callback function.
For strings:
arr.sort((a,b) => (a<b>b) ? 1 : 0)
We want to iterate over all array elements, however each time we are considering only 2 arguments a and b. IF argument a should come before argument b, then the value should be negative.</b>

For numbers
arr.sort((a,b) => a-b)
IF a should come before b, then we return a negative number. When a is lower than b, it will always return a negative number.

IMPORTANT Sort method mutates the array in place.</b>

40
Q

What are data collections in javascript?

A

Data collection stores and structures large amounts of data types for easy access. Provides methods to access that data.

Types of data collections in JS:
Before ES6 there were Arrays and Objects
ECMAScript6 gave Sets, Maps, WeakSets WeakMaps.

41
Q

What are sets?

A

Set is a type of data collection, that enables you to store unique values of any type, whether primitive values or object references.

Properties:
Size

Methods:
Add
Clear
Delete
Entries
forEach
Has
Keys
Values
42
Q

What are maps?

A

Maps use key-value pairs and keep the original insertion order of the keys. Any value (objects and primitive values) may be used as either a key or a value.

map.set(key, value);

Properties:
Size

Methods:
Clear
Delete
Entries
forEach
Get
Set
Has
Keys
Values
43
Q

How to quickly convert truthy or falsy values to boolean?

A

You can do it with !! operator.

!!"" // false
!!0 // false
!!null // false
!!undefined // false
!!NaN // false

!!”hello” // true
!!1 // true
!!{} // true
!![] // true

44
Q

What is the purpose of timers and what are the basic timer functions available in global scope of JS.

A

Timer fire asynchronously, so the events can be handled.

let timeoutID = setTimeout(function(), 1000) is a function available in the global scope. In miliseconds
if we need to cancel clearTimeout(timeoutID)
let intervalId = setInterval( function(),1000)
it will be called repeatedly.
clearInterval(intervalId)
45
Q

How do you handle errors using try and catch keywords?

A

This keywords allow us to handle errors gracefully in our application and not prevent the app from running.

try {
let car = myCar;
}
catch(error) {
console.log('error: ', error)
}
46
Q

What is the difference between try catch and finally keywords.

A

While try and catch keywords, help us error handling in our application and catch the errors without being stopped by reference errors.

finally {
}
block always runs.

47
Q

Mutating vs non mutating array methods

A
Mutating:
splice()
shift()
push()
unshift()
pop()
sort()
reverse(
Non-mutating:
slice()
map()
forEach()
filter()
concat()
48
Q

What are the properties of equality operator: ==

And why is it weird to use it.

A

== is not type safe,
“42” == 42 (could be used in rare cases, when you expect a value in string and want to compare it to a numeric value).
Sometimes the results are not very intuitive:
0 == false
null == undefined
“” == 0
[1,2] == “1,2”

49
Q

What exactly are events?

A

Events are actions or occurrences in the system, that are fired inside of the browser window (see BOM), such as mouse click, button press, form submit, finished loading.

When such a block of code is defined to be run in response to an event firing, we say we are registering an event handler.

50
Q

What are parameters event objects?

A

They are parameters that are passed in the event handlers to provide extra features or info.
The target property of the event object is always a reference to the element that the event has just occurred upon.

51
Q

What is the difference between primitive types and complex (object types) when it comes to holding values?

A

Primitive types, hold values and get a copy of the value, of the variable it was referenced to.
While object types (array, object, built in objects) hold reference to the place it is stored in memory.
Meaning, if object changes, then all the places it is referenced in change.

52
Q

What is the difference between instanceof and typeof?

A

typeof is an operator that returns the type of an object (if it’s primitive, then returns its primitive type, if it’s an object -object)
(instanceof checks if an object is an instance of a constructor).
cities instanceof String;
cities instanceof Array;
cities instanceof Object;
cities instanceof Function;

53
Q

How do you dereference objects and why?

A

In order to garbage collect an object, after it has been used, you need to dereference it from any variables that it was referenced to. (In JS while declaring variables that are referenced to different variables which are primitive values, you make a copy of that variable and store it in memory. For objects, you just store one object and have a link).

The garbage collection routine requires us to set all the variables that the object is referenced to null.

For example:
let letters = [‘a’, ‘b’, ‘c’];
let characters = letters;

letters = null;
characters = null
or
letters = characters = null;

54
Q

What are basic Array methods?

A

arr.push() - pushes object at the end of array (returns arr.length)
arr.unshift() - pushes object at the begining of an array (returns arr.length)
arr.shift() - takes the 1st element of an array and returns it (mutates the original array)
arr.pop() - takes the last element of an array and returns it (mutates)
arr.concat(arr) - concatenates two arrays into one an returns the new array (does not mutate original arrays)
another new ES6 option is to use spread operator […redColors, …greenColors];
arr.slice()
arr.splice()
arr.reduce()
arr.map()
arr.forEach()
arr.includes()
arr.some()
arr.find()
arr.filter()

55
Q

What are the key elements of JS loops?

A

for loop: for (let i = 0; i < 10; i++){} for loop consists of initialization expression, condition, loop body and post-expression

while loop: while (condition) {} in while loop’s case the iterator needs to be included in loop body, while.

do…while loop: will initiate at least once.

for of (ES6) for (const color of colors) { console.log(color) }

56
Q

What are the ways of creating functions?

A
1. Function expression - we assign a variable name to a function and we invoke it by calling the variable name.
const showMessage = function(message) {console.log()}
2. Function declaration 
function addNumbers(x, y) {return x + y}
3. Arrow functions const filterVal = () => {}
57
Q

What is a callback function?

A

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

58
Q

What is the role of arguments object?

A
Argument is an object that is built in a function. It is an array like object, that can be referenced to by square brackets, length, however cannot be used with normal array methods.
In order to use array methods we need to create a new array and make a copy of arguments like: 
Array.prototype.slice.call(arguments) 
or ES6 var args = Array.from(arguments);

With arguments, we can make a function behave differently depending on the arguments passed to a function.

59
Q

How can you add computed properties to an object?

A

When declaring an object, you can use square brackets. This is how you can use a variable as a key name in an object literal property:

const role= 'host';
const person = 'Jools Holland'
const team = {
  [role]: person
}
60
Q

What’s the value of this?

A

The value of this depends on the invocation (execution) context the function it is used in. Hence, sometimes, with keyword this one might refer to window object.
It doesn’t depend on where you write this keyword, but how you call the method.

Arrow functions do not get their own this value.

61
Q

How do you calculate the difference between timestamps using date object?

A
const before = new Date('February 1 2019 7:30:59')
const now = new Date();
const diff = now.getTime() - before.getTime()
// getTime() method will provide us with timestamp in milliseconds since 1 January 1970.

const days = Math.round(diff/1000/3600/24);

62
Q

What are the methods to get year, month, date, hours from a date object?

A
// year, months, day, times
getFullYear()
getMonth()
getDate()
getDay()
getHours()
getMinutes()
getSeconds()
// Timestamp
getTime()

// date strings
toDateString()
toTimeString()
toLocaleString()

You can also extract date from the toLocaleString, by passing object as an argument.
const shanghaiDate = new Date().toLocaleTimeString('en-GB', {
    timeZone: 'Asia/Shanghai'
})

Then, simple destructurization:
[hour, minute, second] = shanghaiDate.split(‘:’);

63
Q

What is localStorage?

A

Local storage is an object that is stored on the window object. It is used to store and retrieve data that user has input. Objects saved in localStorage are stored long-term and remain on the disk after closing the browser.

64
Q

What are the ways to set and get data in localStorage?

A

In order to set an Item in local storage (store, or overwrite), we can use
localStorage.setItem(‘key’, value) method.
to get:
localStorage.getItem(‘key’).

However it’s important to remember, that even if the value that we pass is an integer, it will be changed into a string.

Because it’s an object, we can also use standard methods to set and get values from objects, with dot notation or [].

65
Q

What are the methods to remove data from localStorage?

A

localStorage.removeItem(‘name’);

localStorage.clear();

66
Q

What is the reason for parsing objects and arrays into strings when it comes to localStorage and how exactly is it done?

A

All of the values that are stored in localStorage have to be strings.

If we want to send a javascript object to an endpoint on the web, we would want it to convert it to json.
JSON.stringify(arr);

To achieve opposite result, you need to:
JSON.parse(jsonIn);

67
Q

How can you establish the value of this?

A

Ask 3 questions and proceed as follows:

  1. Did you define he function with an arrow function? -> Write ‘console.log(this)’ on the first valid line above the arrow function. Value of this in the arrow function will be equal to that console.log
  2. Did you call ‘bind’, ‘call’ or ‘apply’ on the function when you invoked it? -> ‘this’ is equal to the first argument of ‘bind’, ‘call’ or ‘apply’
  3. All other cases -> ‘this’ is equal to whatever is to the left of the ‘.’ in the method call.
68
Q

What is the difference between for … of and for … in loops?

A
  1. for..in iterates over all enumerable property keys of an object.
  2. for..of iterates over the values of an iterable object. Examples of iterable objects are arrays, strings, and NodeLists.
69
Q

What is an iterator?

A

Iterator is any object that implement the Iterator protocol by having a next() method that returns a value property and a done property.

70
Q

How does an object become an iterable in JavaScript?

A

For an object to become an Iterable in JavaScript it must implement an iterator method -> meaning that the object must have a property with Symbol.iterator key.

1) iterable can be enumerated with a for..of loop
2) It adheres to the Iterator Protocol
3) It returns an object with an object that has a value and done property.

71
Q

What is a generator function?

A

A generator function is a function that can be paused and resumed at a later time, while having the ability to pass values to and from the function at each pause point.

!! Executing the generator function alone DOES NOT execute its containing code.

Generator function syntax requires an asterix * inbetween function keyword and function name.

72
Q

What does yield keyword do?

A

Yield keyword signals the pause point of a generator function.

Yield keyword can:

  • Send a value to the iterator
  • Receive a value from the iterator

There will not be equal number of yield keywords and .next() calls, as first .next() starts the iterator

73
Q

What is yield delegation?

A

Yield delegation essentially allows a host generator function to control the iteration of a different generator function.

74
Q

What’s the difference between import nad require keywords?

A

With import keyword, we make use of ES2015 Modules system - it is a set of rules that describes how code can be shared between different javascript files.

With require keyword we make use of CommonJS Modules (how to share code between files)