Javascript Flashcards
TODO need to add the following: - Generators - Fetch
Create a class with a constructor, public field/method, private field/method, static field/method, private static method, and a property with accessor.
class MyClass { // Constructor constructor() { // Constructor body } // Instance field myField = "foo"; // Instance method myMethod() { // myMethod body } // Static field static myStaticField = "bar"; // Static method static myStaticMethod() { // myStaticMethod body } // Static block static { // Static initialization code } // Fields, methods, static fields, and static methods all have // "private" forms #myPrivateField = "bar"; } // Accessor methods, allow you to act on the property directly. myClass.myProp get myProp() { return 1; } set myProp(value) { this.somethingElse = 1; }
Give a brief overview of the major iterations of Javascript
The web started out completely static. Over time, some simple client-side logic was made possible via scripting languages with conflicting compatibility. Standardization came in the form of ECMAScript (really the javascript standard). ES1 (1997)
After that the major releases are ES3, ES5, then ES6 which has released updates roughly every year since 2015.
ES3 (1999) introduced a number of features,
- strict equality ===
- try/catch
- regexp
ES5 (2009)
- “use strict”
- Array methods
- JSON handling
- getters/setters
ES6, generally speaking meant the need for the Babel transpiler to write code in ES6 and ship it with ES5 compatibility. New features include
- Classes
- Big arrow =>
- Destructuring and rest and spread operators
- let and const
- Promises and async/await
Discuss the different ways to declare variables and functions
// var var x = 2; // Creates a global variable when used outside a function (global is window in the browser) // var declarations are hoisted //let and const are ES6 features let: let x = 2; const: const x = 2; // A constant cannot change value through assignment or be re-declared while the script is running. It must be initialized to a value. const x; // ERROR //let and const have the scope of their containing block statement
=========
~~~
// Here x is an undeclared variable
x = 2;
// Declaring but not assigning results in undefined values.
var x; // x === undefined
let x; // x === undefined
// Functions
// Function Declaration (it is hoisted)
foo(); // “bar”
function foo() {
console.log(‘bar’);
}
//Function Expressions (not hoisted)
var baz = function() {
console.log(‘bar2’);
};
~~~
Create an array and iterate it with different methods
let arr = [1, 2, 3]; for (var i = 0; i < arr.length; i++) { console.log(arr[i] + ' at index ' + i); } arr.forEach((x, i) => console.log(x + ' at index ' + i)); for (const x of arr) { console.log(x); }
What are the different loops and show how to use them
for - loops through a block of code a number of times
for/of - loops through the values of an iterable object
for/in - loops through the properties of an object
while - loops through a block of code while a specified condition is true
do/while - also loops through a block of code while a specified condition is true
let arr = [1, 2, 3]; // for for (var i = 0; i < arr.length; i++) { console.log(arr[i] + ' at index ' + i); } // for/of for (const x of arr) { console.log(x); } //for/in only enumerable string properties const person = {fname:"John", lname:"Doe", age:25}; let text = ""; for (const x in person) { text += person[x]; } // while while (i < 10) { text += "The number is " + i; i++; } //do while do { text += "The number is " + i; i++; } while (i < 10);
Implement ES6 class features using ES5 javascript.
function Apple(size) { this.color = red; this.size = size; } Apple.prototype.appleMethod = function() { return this.color + this.size; } // or this way const myObject = { myField: 1, myMethod: function(params) { // do something }, // this works too! myOtherMethod(params) { // do something else }, //getters and setters get b() { return this.myField + 1; }, set b(x) { this.myMethod(x); }, // Static methods and fields don't really exist, but you can define a prototype with methods and properties shared by all objects which set our prototype. }
What is a javascript object, discuss the prototype
An object is just a collection of key/value pairs. Additionally it inherits through the prototype chain, all the way up to the object prototype.
What is hoisting?
JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code.
// Function hoisting catName("Tiger"); function catName(name) { console.log(`My cat's name is ${name}`); } /* The result of the code above is: "My cat's name is Tiger" */ // var hoisting console.log(num); // Returns 'undefined' from hoisted var declaration (not 6) var num; // Declaration num = 6; // Initialization console.log(num); // Returns 6 after the line with initialization is executed.
Class hoisting:
Classes defined using a class declaration are hoisted, which means that JavaScript has a reference to the class. However the class is not initialized by default, so any code that uses it before the line in which it is initialized is executed will throw a ReferenceError.
Function expressions and class expressions are not hoisted.
Explain how the logical operators like && work, what do they return and what are they checking
Logical AND, &&
like expr1 && expr2
Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.
Logical OR, ||
like expr1 || expr2
Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.
Logical NOT, !
like !expr1
Returns false if its single operand that can be converted to true; otherwise, returns true.
These operators with 2 operands are short circuiting operations.
List javascript types
Seven data types that are primitives:
Boolean - true and false.
null - A special keyword denoting a null value
undefined - A top-level property whose value is not defined.
Number - An integer or floating point number. For example: 42 or 3.14159.
BigInt - An integer with arbitrary precision. For example 9007199254740992n
String - A sequence of characters that represent a text value. For example: “Howdy”.
Symbol - A data type whose instances are unique and immutable.
Object - named containers for values
== vs ===
== is loose equality check, does type conversions
=== adds a typeof check, values must be of the same type
What is truthy and what is falsy
In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy. That is, all values are truthy except false, 0, -0, 0n, “”, null, undefined, and NaN.
Show how to use a regexp
const re = /ab+c/; // Compiled at script load time const re = new RegExp('ab+c'); // Compiled at runtime const testStr = 'my test str'; re.exec(testStr); //returns an array or null, it's complicated... re.test(testStr); // returns true or false testStr.match(re); // returns array of matches or null testStr.replace(re, 'something'); testStr.search(re); //returns first index of or -1
Compare and contrast null vs undefined.
Undefined is the value of any object property not specifically assigned a value, it is also the value of an uninitialized var declaration. You can set values specifically to undefined though this is discouraged, null is better.
Show how to use promises and async/await, explain how promises work, what’s actually going on under the hood
doSomething() .then((result) => doSomethingElse(result)) .then((newResult) => doThirdThing(newResult)) .then((finalResult) => { console.log(`Got the final result: ${finalResult}`); }) .catch(failureCallback); // Equivalently async function foo() { try { const result = await doSomething(); const newResult = await doSomethingElse(result); const finalResult = await doThirdThing(newResult); console.log(`Got the final result: ${finalResult}`); } catch (error) { failureCallback(error); } } foo(); // Returns a pending promise which will eventually resolve with an undefined value