Section 1

Preview this deck

Use concat() function: let a = [1, 2, 3, 4]; let b = [5, 6, 7, 8]; let ab = a.concat(b); The result will be [1, 2, 3, 4, 5, 6, 7, 8]

Front

Star 0%
Star 0%
Star 0%
Star 0%
Star 0%

0.0

0 reviews

5
0
4
0
3
0
2
0
1
0

Active users

0

All-time users

0

Favorites

0

Last updated

6 years ago

Date created

Mar 14, 2020

Cards (111)

Section 1

(50 cards)

Use concat() function: let a = [1, 2, 3, 4]; let b = [5, 6, 7, 8]; let ab = a.concat(b); The result will be [1, 2, 3, 4, 5, 6, 7, 8]

Front

How to merge two arrays in one?

Back

Use "For-In" loop: let obj = {name: "John", age: 28}; for (let key in obj) { alert(key); // to get the key alert(obj[key]); // to get the value }

Front

How to walk over all properties in a given object?

Back

Primitives are still primitives. JavaScript allows for a special "Object Wrapper" that provides extra methods that can be applied to the primitives. The wrapper is automatically destroyed when the function is completed. The wrappers exist for all primitive, except "null" and "undefined". Those are the most primitive types.

Front

Explain what does it mean "primitives as object"?

Back

There are seven data types in JavaScript: - Number - String - Boolean - Null - Undefined - Object - Symbol (new in ES6)

Front

What datatypes JavaScript uses?

Back

An arrow function has a more simple syntax that a function expression: let sum = (a, b) => a + b; is the same as: let sum = function (a, b) { return a + b; }

Front

Explain arrow function. Why should we use it?

Back

Mutable objects have properties that can be changed (mutated). Immutable objects (such as strings and numbers) cannot be changed, since they have specific memory allocation.

Front

What is the difference between mutable and immutable objects?

Back

Anonymous functions are typically used in callbacks or as private methods of classes.

Front

What is a typical use of anonymous functions?

Back

Try to walk through all properties: let obj= {} function isEmpty(obj) { for (let key in obj) { return "has keys"; } return "has no keys"; }

Front

How to check if an object has any property?

Back

Use a toString() function: let number = 12345 let result = number.toString(); Output: string "12345"

Front

Convert number 12345 to string.

Back

Unicode symbols begin with backslash and "u" character. To assign a copyright Unicode symbol to a variable, one may write: let str = "\u00a9";

Front

How to enter a Unicode symbol into a string?

Back

Interaction functions are: alert(message); result = prompt(title, optionalDefault); boolean = confirm(question);

Front

What are the interaction functions?

Back

Use a "Do-While" loop with a isFinite() function to check if it is a finite number or not. function promptNumber() { let number; do { number = prompt("Enter a number", 0); } while (!isFinite(number)); return +number; } Here "+" in return operator forces to cast variable to numerical value.

Front

Write a function definition that asks a user to enter a number and keep prompting if it is not a number. Return the number.

Back

Output: Number 1. True converts to number 1, false converts to number 0.

Front

What is the output? true + false

Back

Output: Number -1. Since you cannot "extract" from a string, everything after will be a number. Empty string converts to number 0.

Front

What is the output? "" - 1 + 0

Back

Think of a string as an array characters. Take the last element of the array using it's length property: let str = "Excellent"; let char = str[str.length - 1];

Front

How to get the last character of a given string?

Back

The idea is that if we have a lot of elements handled in a similar way, then instead of assigning a handler to each of them - we put a single handler on their common ancestor. The algorithm: 1. Put a single handler on the container (parent). 2. In the handler - check the source element event.target. 3. If the event happened inside an element that interests us (child), then handle the event.

Front

Explain event delegation.

Back

Use "For-In" loop: let obj = {name: "John", age: 28}; let prop = "name"; let result = (prop in obj) ? "exists" : "does not exist"; Output: "exists"

Front

How to check if a certain property exists in the given object?

Back

Use one of the Math library functions: Math.floor() Math.ceil() Math.round() To round a number to a second decimal use toFixed() function: let number = 1.235 result = number.toFixed(2); Output: 1.24

Front

How would you round a number?

Back

Parse it to integer. JavaScript will try to get the number from the string if it starts with a number: let str = "100px"; alert(parseInt(str)); Outputs number 100 to the console.

Front

What is a way to get a number from the string "100px"?

Back

Since the last operand is a string, the compiler converts the number to string and concatenates them. The result is a string "1020".

Front

What would be the result? let result = 10 + "20";

Back

There are 3 ways of doing it: let str = "Excellent" 1. newStr = str.substring(1, 6); output: "xcell" take all from 1 (including) to 6 (not include) (start from 0) 2. newStr = str.substr(1, 6); output: "xcelle" take all from 1 to 6 including all (start from 0) 3. newStr = str.slice(1, 6); output: "xcell" take all from 1 (including) to 6 (not include) (start from 0) newStr = str.slice(2); output: "cellent" take all from 2 (including) and till the end (start from 0) newStr = str.slice(-2); output: "nt" take two last characters

Front

How to get a substring from a string?

Back

Think of a string as an array of characters. Take the second element of the array: let str = "Excellent"; let char = str[1];

Front

How to get the second character of a given string?

Back

Think of a string as an array. Take the first element of the array and apply toUpperCase() function. Add the rest of the string. let str = "john"; let newStr = str[0].toUpperCase() + str.slice(1); output: string "John"

Front

Replace the first letter with a capital: john

Back

Null is an object. Undefined means that the variable is declared but has no value. Undeclared means that the variable is referenced before it is actually exists.

Front

What is the difference among null, undefined and undeclared?

Back

Yes. there are no difference.

Front

Are these the same? let user = new User(); let user = new User;

Back

Yes. Square notation is much more powerful, since you may insert an expression inside them: let fruit = "apple"; let bag = { [fruit + 'Computers']: 5}; with dot notation you cannot use the expression: bag.appleComputers = 5;

Front

Is there any difference in using square brackets notation or dot notation for object keys? obj.key and obj[key]

Back

Output: String "10". The "+" sign is a concatenation. Since you are adding to a string, everything after it will be a string.

Front

What is the output? "" + 1 + 0

Back

No. The property will be of "undefined" type.

Front

If property of an object does not exist, will it return an error?

Back

Use isNaN() function or isFinite() function: let number = 123; alert (!isNaN(number)); or alert(isFinite(number)); But remember, that space or an empty string is treated as number 0.

Front

How to check if the value is a number?

Back

Output: String "9px". Add two numbers and concatenate them with the string.

Front

What is the output? 4 + 5 + "px"

Back

Yes. It returns "undefined".

Front

If a function has no return (empty return) does it actually returns anything?

Back

You can check the data type using "typeof" operator: let value = 12; console.log(typeof value); Output: string "number".

Front

How to check a data type of a given value?

Back

Use Math library: function randomNum(min, max) { return Math.floor(Math.random() * (1 + max - min) + min); } let result = randomNum(5, 15);

Front

How to get a random number from 5 to 15?

Back

let str = ""; if (!str) return "Empty";

Front

How to check if a string is empty?

Back

Use "For of" loop: let str = "Excellent"; for (let char of str) { alert(char); }

Front

How to iterate over all characters in a given string?

Back

Use scientific notation: let number = 1e9;

Front

Create a number that designates one billion.

Back

A closure is an inner function that has access to the outer function's variables: function showName(first, last) { let intro = "Your name is "; function fullName() { return intro + first + last; return fullName(); } let result = showName('John', 'Doe'); Here fullName is a closure function, that can use outer function's (showName) parameters.

Front

What is a closure?

Back

Function Declaration can be used anywhere in the script: function sayHello { alert("Hello"); } Function Expression is used after assignment to its variable: let sayHello = function() { alert("Hello"); }

Front

What is the difference between Function Declaration and Function Expression?

Back

Check if the object keys have any length: let obj = {}; let result = (Object.keys(obj).length > 0) ? "is not empty" : "is empty";

Front

How to check if an object is empty?

Back

Use includes() function: let str = "Excellent"; let word = "cell"; let result = str.includes(word)); result outputs "true"

Front

How to find out if a given string has a particular word inside?

Back

key *= 2;

Front

What is a different notation for: key = key * 2;

Back

Add "0" to the number and remove two last characters: let number = 9; number = ("0" + number).slice(-2); Output is a string "09".

Front

Write a code that If a given number is less than 10 adds a "0" in front of the number.

Back

False. Use "dictionary comparison" of strings. Compiler starts comparison from the first letter of each word. Since "a" isn't greater than "p", the expression is false.

Front

True or False: "apple" > "pineapple";

Back

"this" always refers to an object (usually inside a function) and contains the value of the object that invokes this function. Use "this" to access properties or methods of the object that invokes that function.

Front

Explain "this" keyword.

Back

To have a "deep copy" of the given object, copy each key of the object, or use Object.assign() function: let user = {name: "John", age: 28, address: { street: "Easy" }}; let userClone = Object.assign({}, user);

Front

How to properly clone an object?

Back

Output: Infinity You cannot divide by 0.

Front

What is the output? 7 / 0

Back

call() function takes comma separated parameters apply() function takes single array of arguments.

Front

What is the difference between call() and apply()?

Back

Output: Number 2. Since you cannot divide on a string, the string is converted to a number.

Front

What is the output? 6 / "3"

Back

Output: NaN. Since you cannot subtract from a string, you are getting NaN.

Front

What is the output? "4px" - 2

Back

Pros: Promises have a cleaner code with a possibility of chaining methods. Events can perform synchronously. Cons: Once started, a promise cannot be stopped.

Front

What are Pros and Cons of Promises compare with callback functions?

Back

Section 2

(50 cards)

With Date native object: let current = new Date();

Front

How to show current time?

Back

In JavaScript, functions are objects.

Front

What type is a function?

Back

Two ways: let number = 2; let result = Math.pow(number, 2); or let result = 2 ** 2;

Front

How to write number 2 in power of 2?

Back

We may decide to execute a function not right now, but at a certain time later. That's called "scheduling a call". There are two methods for it: setTimeout() allows to run a function once after the interval of time. setInterval() allows to run a function regularly with the interval between the runs. For instance, this code calls sayHi() after one second: function sayHi() { alert('Hello'); } setTimeout(sayHi, 1000);

Front

What does it mean "Scheduling a function call"?

Back

Pass the timestamp to the Date object: let date = new Date(timestamp);

Front

How to get date from a timestamp?

Back

Method map() uses a function, which is called repetitively for each element of the array: let result = arr.map(function(item, index, array) { // should return an array of new values instead of item }) Example: let lengths = ["Bilbo", "Gandalf", "Nazgul"] lengths.map(item => item.length) alert(lengths); Output: "5,7,6"

Front

Explain how map() method works with arrays.

Back

Technically, both loops can be applied to an array, but the "For-In" loop iterates over all properties, not only the numeric ones. "For-in" loops are optimized for generic objects, not arrays, and thus is 10-100 times slower. Generally, we shouldn't use "For-in" loops for arrays.

Front

What is faster way to loop through elements of an array, "For-In" loop or "For-Of" loop?

Back

In computer science, a "stack" means an ordered collection of elements which supports two operations: - push adds an element to the end. - pop takes an element from the end. So new elements are added or taken always from the "end". For stacks, the latest pushed item is received first, that's also called LIFO (Last-In-First-Out) principle.

Front

What is a Stack data structure?

Back

Use JSON.stringify() method: let student = { name: 'John', age: 30, isAdmin: false, courses: ['html', 'css', 'js'], wife: null }; let json = JSON.stringify(student); The resulting json string is a called JSON-encoded or serialized or stringified or marshalled object.

Front

How to convert an object to JSON?

Back

"var" variables are either function-wide or global. if (true) { var test = true; // use "var" instead of "let" } alert(test); // true. The variable lives after if.

Front

What is the difference among "var", "let", and "const"?

Back

There are two ways to create an array: let arr = new Array(); let arr = []; Almost all the time, the second syntax is used.

Front

What is the syntax to create a new array?

Back

Output: Number 1. Null is treated as a number 0.

Front

What is the output? null + 1

Back

No. It will be ignored.

Front

Can we convert a function to JSON?

Back

Method find() uses a function, which is called repetitively for each element of the array: let result = arr.filter( function(item, index, array) { // should return an array of items we are looking for }); Example: let users = [ {id: 1, name: "John"}, {id: 2, name: "Pete"}, {id: 3, name: "Mary"} ]; let users = users.filter(item => item.id < 3); alert(users); Output: "John,Mary".

Front

Explain how filter() method works with arrays.

Back

The throw operator generates an error. The syntax: throw <error object> Simple example: let json = '{ "age": 30 }'; // incomplete data try { let user = JSON.parse(json); // <-- no errors if (!user.name) { throw new SyntaxError("Incomplete data: no name"); } alert( user.name ); } catch(e) { alert( "JSON Error: " + e.message ); }

Front

What "throw" operator is doing?

Back

Method find() uses a function, which is called repetitively for each element of the array: let result = arr.find( function(item, index, array) { // should return true if the item is what we are looking for }); If it returns true, the search is stopped, the item is returned. If nothing found, undefined is returned. Example: let users = [ {id: 1, name: "John"}, {id: 2, name: "Pete"}, {id: 3, name: "Mary"} ]; let user = users.find( item => item.id == 1 ); alert(user.name); Output: "John".

Front

Explain how find() method works with arrays.

Back

Method sort() sorts the array in place. The items are sorted as strings by default: let arr = [ 1, 2, 15 ]; arr.sort(); Output: "1, 15, 2". To use our own sorting order, we need to supply a function of two arguments as the argument of the sort() method: function compareNumeric(a, b) { if (a > b) return 1; if (a == b) return 0; if (a < b) return -1; } let arr = [ 1, 2, 15 ]; arr.sort(compareNumeric); Output: "1, 2, 15".

Front

Explain how sort() method works with arrays.

Back

Deletion (from index 1 remove 1 element): let arr = ["I", "study", "JavaScript"]; arr.splice(1, 1); alert( arr ); Output: "I", "JavaScript". Deletion with Replacement (remove 3 first elements and replace them with another): let arr = ["I", "study", "JavaScript", "right", "now"]; arr.splice(0, 3, "Let's", "dance"); alert( arr ); Output: "Let's", "dance", "right", "now". Insertion (from index 2 insert 2 elements): let arr = ["I", "study", "JavaScript"]; arr.splice(2, 0, "complex", "language"); alert( arr ); Output: "I", "study", "complex", "language", "JavaScript". Negative indexes are allowed. They specify the position from the end of the array. (from index -1 (one step from the end) delete 0 elements, then insert 3 and 4): let arr = [1, 2, 5]; arr.splice(-1, 0, 3, 4); alert( arr ); Output: 1,2,3,4,5

Front

Explain how splice() method works with arrays.

Back

Try..catch allows to "catch" errors and, instead of dying, do something more reasonable.

Front

Why "Try - Catch" block is used?

Back

delete() method will only delete the value, but not the index from the array. To delete both, use splice() method. This method is actually used to add, delete and insert array elements.

Front

How to delete an element from the array? Since array is an object, Can I use delete() method?

Back

2 1 first copy a to b, then increment a.

Front

What is the output? let a = 1; let b = a++; console.log(a, b);

Back

Array is still an object. ...But what makes arrays really special is their internal representation. The engine tries to store its elements in the contiguous memory area, one after another, just as depicted on the illustrations in this chapter, and there are other optimizations as well, to make arrays work really fast. Arrays are carefully tuned inside JavaScript engines to work with contiguous ordered data, please use them this way. And if you need arbitrary keys, chances are high that you actually require a regular object {}.

Front

What is the difference between an object and array?

Back

Use function object property .name: function hello() { alert("hi") } let name = hello().name;

Front

How to get a name of a function into a variable?

Back

toString() method returns a comma-separated list of elements: let arr = [1, 2, 3]; console.log( arr.toString() ); Output: String "1,2,3".

Front

What would a toString() method of an array return?

Back

Destructuring assignment is a special syntax that allows us to "unpack" arrays or objects into a bunch of variables. It's called "destructuring assignment", because it "destructurizes" by copying items into variables. But the array itself is not modified. let [firstName, surname] = arr; is the same as let firstName = arr[0]; let surname = arr[1]; The destructuring assignment also works with objects: let options = { title: "Menu", width: 100, height: 200 }; let {title, width, height} = options; alert(title); // Menu alert(width); // 100 alert(height); // 200

Front

Why destructuring assignment is used? Explain how it works

Back

Use forEach() function. let arr = ["Bilbo", "Gandalf", "Nazgul"] arr.forEach((item, index, array) => { alert(`${item} is at index ${index} in ${array}`); }); The result of the inner function (if it returns any) is thrown away and ignored.

Front

How to run a function for each element of an array?

Back

Document Object Model. The document object gives access to the page content. We can change or create anything on the page using it: document.body.style.background = "red";

Front

What is DOM?

Back

Make the array's length property a zero: let arr = [1, 2, 3, 4, 5]; arr.length = 0; The length property is actually writable. If we decrease it, the array is truncated.

Front

What is the simplest way to clear an array?

Back

Use unshift() method: let fruits = ["Orange", "Pear"]; fruits.unshift("Apple"); "Apple" is added to the beginning of the array.

Front

How to add an element to the beginning of an array?

Back

shift() and unshift() are slower, because they need to move each element of an array in one or another side.

Front

Which of this array methods slower than others? shift(), unshift(), push(), pop().

Back

It is impossible.

Front

How to add comments to JSON?

Back

Use JSON.parse() method: let numbers = "[0, 1, 2, 3]"; numbers = JSON.parse(numbers);

Front

How to get an object out of a JSON string?

Back

This runs, but the result probably is not what you expect. The proper way is to pass a function reference to the setTimeout method (no parenthesis): setTimeout(sayHi, 1000); You also may use a function inside the setTimeout: setTimeout( () => alert( 'Hi' ), 1000 );

Front

Will this run? function sayHi() { alert( 'Hi' ); } setTimeout(sayHi(), 1000);

Back

Use push() method: let fruits = ["Apple", "Orange"]; fruits.push("Pear"); "Pear" is added to the end of the array.

Front

How to append an element to the end of an array?

Back

Use shift() method: let fruits = ["Apple", "Orange", "Pear"]; alert( fruits.shift() ); "Apple" is removed from the array and is returned. Array is changed.

Front

How to extract the first element from an array and return it?

Back

Use getTime() method: let current = new Date(); console.log(current.getTime()); or shorter (without using Date object): let current = Date.now();

Front

How to get a current timestamp?

Back

Functions alert/confirm/prompt are a part of BOM (Browser Object Method: they are directly not related to the document, but represent pure browser methods of communicating with the user. They cannot be styled.

Front

Why alert/confirm/prompt have such "style-less" look?

Back

2 2 first increment a, then copy a to b.

Front

What is the output? let a = 1; let b = ++a; console.log(a, b);

Back

Yes, with Date.parse() method. The string should be formatted: YYYY-MM-DDTHH:mm:ss.sssZ YYYY-MM-DD - is the date: year-month-day. The character "T" is used as the delimiter. HH:mm:ss.sss - is the time: hours, minutes, seconds and milliseconds. The optional 'Z' part denotes the time zone in the format +-hh:mm. A single letter Z that would mean UTC+0. For example: let date = new Date( Date.parse('2012-01-26T13:51:50.417-07:00') );

Front

Can we get a date from a string?

Back

In computer science, a "queue" means an ordered collection of elements which supports two operations: - push appends an element to the end. - shift get an element from the beginning, advancing the queue, so that the 2nd element becomes the 1st. For queues, we have FIFO (First-In-First-Out).

Front

What is a Queue data structure?

Back

Yes. This is called Named Function Expression. You may use "func" inside the function block to refer the function itself. "func" is not visible outside of the function. let sayHi = function func(who) { if (who) { alert(`Hello, ${who}`); } else { func("Guest"); // use func to re-call itself } }; sayHi(); // Output: Hello, Guest. But this won't work: func(); // Output: Error, func is not defined (not visible outside of the function).

Front

Does this code execute without error? let sayHi = function func(who) { alert(`Hello, ${who}`); };

Back

Use function object custom property. Let's create a custom property called "count": function sayHi() { alert("Hi"); sayHi.counter++; } sayHi.counter = 0; // initial value sayHi(); // Hi sayHi(); // Hi console.log(sayHi.counter); Output: 2.

Front

How to count how many times a function was executed?

Back

There are two ways: 1. A normal C-like "For" loop: let arr = ["Apple", "Orange", "Pear"]; for (let i = 0; i < arr.length; i++) { alert( arr[i] ); } 2. A special "For-Of" loop: let fruits = ["Apple", "Orange", "Plum"]; for (let fruit of fruits) { alert( fruit ); }

Front

How would you loop through an array?

Back

Output: NaN. Undefined is neither a string or a number. You cannot add to it.

Front

What is the output? undefined + 1

Back

Spread operator turns array into a list of arguments. For instance, there's a built-in function Math.max that returns the greatest number from a list: Math.max(3, 5, 1); Now let's say we have an array [3, 5, 1]. How do we call Math.max with it? We can't manually list items in the code Math.max(arr[0], arr[1], arr[2]). Spread operator to the rescue! let arr = [ 3, 5, 1 ]; alert( Math.max( ...arr ) ); The spread operator operates only on iterables.

Front

Explain spread operator.

Back

The JSON (JavaScript Object Notation) is a general format to represent values and objects. It's easy to use JSON for data exchange when the client uses JavaScript and the server is written on Ruby/PHP/Java/Whatever.

Front

What is JSON and where should we use it?

Back

Use isArray() function. Since array does not have its own type, it is impossible to get the type with "typeof", because it will return "object". alert(Array.isArray( {} )); Output: false alert(Array.isArray( [ ] )); Output: true

Front

How to tell if the structure is an array?

Back

The number of milliseconds that has passed since the beginning of 1970 is called a timestamp.

Front

What is a timestamp?

Back

No. Try..catch only works for runtime errors. The syntax should be always valid.

Front

Is it possible to catch syntax errors with "Try - Catch" block?

Back

Use pop() method: let fruits = ["Apple", "Orange", "Pear"]; alert( fruits.pop() ); "Pear" is removed from the array and is returned. Array is changed.

Front

How to extract the last element of an array and return it?

Back

Section 3

(11 cards)

outerHTML property includes the HTML of the calling element.

Front

What is the difference between innerHTML and outerHTML?

Back

They both objects.

Front

What is data type of a DOM tag and a text inside it.

Back

Use getElementsByTagName() method: let divs = document.getElementsByTagName('div');

Front

How to get an element using its tag name?

Back

Use textContent property: <ul> <li>one</li> <li>two</li> <li>three</li> </ul> alert(document.body.textContent);

Front

How to get a texts from the element?

Back

Use "hidden" property: <div id="elem">A blinking element</div> <script> setInterval(() => elem.hidden = !elem.hidden, 1000); </script>

Front

Create a simple blinking element with a setInterval function.

Back

The innerHTML property allows to get the HTML inside the element as a string.

Front

What for innerHTML property is used?

Back

Use querySelectorAll() method: <ul> <li>one</li> <li>two</li> <li>three</li> </ul> let list = document.querySelectorAll('ul > li'); for (let el of list) { alert(el.innerHTML); }

Front

How to get all <li> elements of an <ul> element?

Back

With getElementById() method: <p id="one">First Paragraph</p> let element = document.getElementById('one');

Front

How to get any element in the DOM bi it's ID?

Back

The document element.

Front

What is the "entry point" of the DOM?

Back

Use "For-Of" loop. Do not use "For-In" loop, since it loops through all properties, which is slower.

Front

How to loop through a collection?

Back

The call to document.write only works while the page is loading.

Front

Why using document.write may be a problem?

Back