JavaScript

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

How to use strict mode best?

(function () { 'use strict'; // this function is strict... }()); Do it in an IIFE so that it doesn't affect other scripts

What do ES6 named exports look like?

//------ lib.js ------ export const sqrt = Math.sqrt; export function square(x) { return x * x; } export function diag(x, y) { return sqrt(square(x) + square(y)); } //------ main.js ------ import { square, diag } from 'lib'; console.log(square(11)); // 121 console.log(diag(4, 3)); // 5 //------ main.js ------ import * as lib from 'lib'; console.log(lib.square(11)); // 121 console.log(lib.diag(4, 3)); // 5

CommonJS exports?

//------ lib.js ------ var sqrt = Math.sqrt; function square(x) { return x * x; } function diag(x, y) { return sqrt(square(x) + square(y)); } module.exports = { sqrt: sqrt, square: square, diag: diag, }; //------ main.js ------ var square = require('lib').square; var diag = require('lib').diag; console.log(square(11)); // 121 console.log(diag(4, 3)); // 5

What are false?

0, undefined, null, empty string, NaN, false. That is it. Empty array is TRUE.

What is an example of floating point precision issues?

0.1 + 0.2 == 0.3 This is FALSE. JavaScript doesn't guarantee precision with arithmetic of decimal values. 0.1 == 0.1 will be true, but math will throw it off.

Hex syntax? Binaries?

0xFFFFFF 0b1011

What order will the console logs print? (function() { console.log(1); setTimeout(function(){console.log(2)}, 1000); setTimeout(function(){console.log(3)}, 0); console.log(4); })();

1 4 3 2 Notice 3 is after 4, because JavaScript has an event loop, if it is busy with something it will wait until that has finished before firing any events like setTimeout.

When does "this" change?

1) Assigning an object's method to a variable foo = person.sayName Instead, use bind: var genderTeller = person1.sayGender.bind(person1); 2) Conversely, if you assign a function to an object's function, "this" because the object 3) Async calls, Ajax 4) With event handlers, "this" will be the element that fired the event, not the object the handler is inside.

What does "use strict" do?

1. Prevent duplicate keys in object(dictionary) 2. Prevent accidental globals (foo = 1, without Var) 3. Prevent using the same argument twice 4. Prevent overwriting "this"

Best way to describe a closure?

A closure is a function having access to the parent scope, even after the parent function has closed. It is a FUNCTION WITHIN A FUNCTION, capturing the outer function's variables. It does NOT create copies of the variables, so if that variable changes then it affects the function. A closure is an inner function that has access to the outer (enclosing) function's variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function's variables, and it has access to the global variables.

Have an object that restricts access to another object?

A Proxy.

How are numbers stored?

Always as number type, double precision floating type

How can you reuse node modules in front-end code?

Browserify will take NPM modules and make them able to run in a web browser. It includes all dependencies needed. Not everything in Node would be able to run in the browser obviously.

What are .bind(), .call(), and .apply() used for? how are they different?

Call/apply call the function immediately, bind returns a function.

Briefly describe LESS?

Can do on server or client (server preferably). Server-side using @import is fine, it can concat the scripts to be served together, getting around the concurrency issue. If doing on client, import less.js. Change rel to: <link rel="stylesheet/less" href="foo.less" type="text/css"> @main-color: Pink; body { background: @main-color }

Create new elements?

Clone node, create element, create text node

Print to page?

Document.write

Best way to print all properties?

Document.write(Object.keys(obj)) "For in" can include extra properties you don't want to see.

Why are iterators important?

For one, it allows you to walk through a structure concurrently. You could call iterator.next() in one event, then later call iterator.next() in a whole separate event. E.g. you could setTimeout(() => my.iterator.next(), 200 );

Explain web sockets

HTTP message is sent to server, asks "are you able to do web sockets?". Preferably with SSL. Socket.io handles this.

Get difference of two dates in days?

Have to do a function. Use getTime() on the two dates, and calculate the milliseconds difference, then convert back to days. Date.daysBetween = function( date1, date2 ) { //Get 1 day in milliseconds var one_day=1000*60*60*24; // Convert both dates to milliseconds var date1_ms = date1.getTime(); var date2_ms = date2.getTime(); // Calculate the difference in milliseconds var difference_ms = date2_ms - date1_ms; // Convert back to days and return return Math.round(difference_ms/one_day); }

How does hoisting work?

Hoisting moves variable declarations to the TOP OF THE FUNCTION. Notice the word FUNCTION. Block doesn't matter. E.g. function foo() { if (false) { var bar = "3" } return bar; // Bar is UNDEFINED, but it IS declared. } Same as: function foo() { var bar; if (false) { bar = "3" } return bar; // Bar is UNDEFINED, but it IS declared. }

Famous JavaScript programmers?

John Resig - creator of jQuery Douglas Crockford - author JavaScript: The Good Parts, popularized JSON. Nick Zakas - Multiple popular JS books. David Flanagan - Author of JavaScript: The Definitive Guide. Paul Irish - Lead dev on Modernizr, jQuery core team member, etc. Christian Heilmann - Revealing Module pattern, outspoken Microsoft and Mozilla worker Addy Osmani - Creator of Yeoman, jQuery team member

ES6 getters and setters?

Just append "get" or "set" class Employee { get name() { } set name(newValue) { } }

How do you parse a date from a string?

Just pass it to the Date constructor. Or you can do Date.parse. new Date('Aug 9, 1995'); Date.parse('Aug 9, 1995');

How are globals created?

Leave out "var". If strict mode, this causes an error. But otherwise it will allow anyone outside the function to have access to that variable.

What does WebRTC allow?

It basically allows peer-to-peer connections. It isn't just for video, but video/webchat/etc is one of the first use cases. Instead of doing webcam connections to a web server, and redirecting that to another web client, WebRTC allows the two clients to stream webcams directly to each other, speeding up the connection. DataChannels allow encrypted, compressed sending of data. So WebRTC can allow anything - direct file transfer, game data, etc.

What is "this" within an event handler

It is NOT always the element. <button onclick="doSomething" /> "doSomething" is assigned to the element, so "this" is the button. <button onclick="doSomething()" /> "doSomething" is NOT assigned, it is used in an expression. "this" is the GLOBAL object! You could do it like this instead: <element onclick="doSomething(this)"> Though it is better to just do click registration on the JS side

How do you do a regex match all? Regex capture groups?

It is a method on the STRING class. NOT on RegExp() 'foo'.match(/o/g); // ['o', 'o'] For capture groups, use expression.exec(). It returns an array, where [0] is the full match, [1] is capture group 1, etc.

Arguments object?

It is basically an implicit array passed in to all functions that holds the arguments. Can capture arguments not even declared in the signature, so you could do e.g: function sumAll() { // Loop over, e.g. arguments[0] + arguments[1] etc } sumAll(1,2,3,4) Even though it behaves like an array, it is technically an object (if you do typeof)

Get geolocation information?

It is on the navigator object, same object as appVersion browser info. navigator.geolocation.getCurrentPosition(function(position) { // Got lat/long! });

What is a caveat to using string.replace()? How do you get around it?

It only replaces the first instance found. BUT you can use a regex global. 'foo'.replace(/o/g, "ee") // fee

What is Symbol for?

It provides metadata for a class, like being able to make a class iterable by telling JavaScript how to iterate through it.

How to write an AMD module?

It runs a define statement, and then returns an object or a function that returns an object. define(function(){ var privateValue = 0; return { increment: function(){ privateValue++; }, decrement: function(){ privateValue--; }, getValue: function(){ return privateValue; } }; });

Describe Node.js

It runs the V8 engine. But it also adds hooks to be able to e.g. say that console.log will print to console.

How does for...of work?

It uses ITERATORS. It is equivalent to: while (!iter.done) { let val = iter.next() }

Add external stylesheet?

Link href

ES6 get elements in array matching some criteria?

List comprehension or new array.find(); var greaterThan6 = array.find((num) => num > 6);

Inline click handlers?

Noooo. Hard to debug. Use event listeners in JS file instead: document.getElementById("myBtn").addEventListener("click", displayDate); or $(CLOSEST_CONTAINER_SELECTOR).on('click', '.alertLink', function() { alert('boo'); }; element.addEventListener("mouseover", myFunction); element.addEventListener("click", mySecondFunction); element.addEventListener("mouseout", myThirdFunction);

What three main ways can you get or bind values to controls in React?

Props, state, refs. Refs e.g. <input ref="myInput" /> var input = this.refs.myInput; var inputValue = input.value;

How can you get data in React without binding?

Refs. <input ref="myInput" /> var input = this.refs.myInput; var inputValue = input.value;

Add created element to DOM?

Remove child, insert child, append child, replace child

Generators?

Returns an iterator. It looks like an anonymous function, EXCEPT: * It has an asterisk * after "function". * It uses "yield" inside the function. let numbers = function*() { yield 1; yield 2; yield 3; yield 4; } let iter = numbers(); iter.next() // { value: 1, done: false } iter.next() // { value: 2, done: false } iter.next() // { value: 3, done: false } iter.next() // { value: 4, done: true }

How to use SuperAgent?

Search for "superagent browser CDN" Add to script tag Then access it from "window.superagent" let request = window.superagent; request .get("http://jsonplaceholder.typicode.com/posts") .end((err, res) => { console.log(res.body[0]['title']) });

How does socket.io look?

Server and Client code are basically the same library, similar code. socket.on("event", doSomeFunction); socket.emit("event", data);

What does "configurable" do on an object property?

Setting it to false means you can't change the writable/enumerable/configurable AND more importantly you can't delete the property.

Rest parameters?

Similar to using "arguments", but it only captures the unnamed arguments, and it is also more explicit (that the function allows additional arguments, and a name to discern what those should be). function foo(name, ...numbers) { console.log(name); "shawn" console.log(numbers); // [1, 2, 3] } foo("shawn", 1, 2, 3);

Slice vs Splice?

Slice returns new array of items from array. Splice INSERTS into the SAME array, modifying the array, possibly replacing arr = ["a", "b", "c", "d"] arr.slice(1, 3) // b, c ... it doesn't get the last index mentioned arr.splice(1, 2, "e") // a, e, d

How does Google Hangouts draw stuff on people's faces?

Streams the video out onto a canvas, then you can draw onto the HTML5 canvas.

How do standard HTML forms work?

Submit button is clicked, post data is sent to action_page.php. Method says if it will be query string (GET) or post data (POST). <form action="action_page.php" method="post"> <input type="text" name="firstname" value="Mickey"> <input type="submit"></input> </form> Becomes: action_page.php?firstname=Mickey&lastname=Mouse

Switch statements?

Switch, case, break, default

What is special about arrow functions in ES6?

THIS is not changed in its scope. So you can keep the outer THIS from the class. function Car() { //Note, we could use the new Class feature in ES6 instead this.speed = 0; setInterval(() => { this.speed += 5; // <------ this is from Car }, 1000); }

Templating in ES6?

Template literals use backticks. Templated fields use ${variableName}. Can also use expressions, ${some expression} var foo = "testing"; document.body.innerHTML = `Right now I am ${foo}`

Basic example of a closure, getting around "this"?

The technique of assigning this to "self" is a closure. The "self" variable gets wrapped into the closure of the function callback. var self = this; doSomething(function(foo) { self.process(foo); })

What is the difference between window.onload and onDocumentReady?

The window.onload event won't trigger until every single element on the page has been fully loaded, including images and CSS. The downside to this is it might take a while before any code is actually executed. You can use onDocumentReady to execute code as soon as the DOM is loaded instead.

How is ES6 module loading better than CommonJS?

Their syntax is even more compact than CommonJS's. Their structure can be statically analyzed (for static checking, optimization, etc.). Their support for cyclic dependencies is better than CommonJS's.

WeakSet and WeakMap?

They are like Set and Map, but more limited. Can't view length for example. However, they don't prevent garbage collection if the item they are referring to with a pointer gets deleted.

How to use DOMParser?

To append it, you have to do myobj.childNodes[0] var parser = new DOMParser(); var foo = parser.parseFromString("<p>Foo</p>", 'application/xml'); document.getElementById("hithere").appendChild(foo.childNodes[0]);

Detect browser feature support?

Try modernizr https://modernizr.com/ if (Modernizr.awesomeNewFeature) { showOffAwesomeNewFeature(); } else { getTheOldLameExperience(); }

JavaScript allows computed keys?

YES! ES6 allows syntax for creating keys based on an expression. Uses square brackets, kind of confusing, don't worry about more than that.

Comprehensions?

YES! JavaScript has List Comprehension syntax similar to Python, a little different syntax. arr = [1, 2, 3]; multipliedArr = [for (n of arr) if (n > 1) n * n];

ES6 modules hides implementations?

Yeah, if you don't put export next to it, people can't see it.

Proxy in ES6?

Yeah. It is an object that allows modified access to another object. Maybe you want an object that only allows you to see first name and last name of a Person. Proxy(objectToProxy, { get: function(target, property) { // Return the value if you want to allow access to it } })

Are there getters and setters syntax in JS?

Yeah... // Example of an object property added with defineProperty with an accessor property descriptor var bValue = 38; Object.defineProperty(o, 'b', { get: function() { return bValue; }, set: function(newValue) { bValue = newValue; }, enumerable: true, configurable: true });

Is JavaScript case sensitive?

Yes

Class syntax in ES6?

class Foo extends Bar { constructor(title, name) { super(name); this._title = title; } doSomething() { } }

Array methods?

concat() Joins two or more arrays, and returns a copy of the joined arrays indexOf() Search the array for an element and returns its position join() Joins all elements of an array into a string lastIndexOf() Search the array for an element, starting at the end, and returns its position pop() Removes the last element of an array, and returns that element push() Adds new elements to the end of an array, and returns the new length reverse() Reverses the order of the elements in an array shift() Removes the first element of an array, and returns that element slice() Selects a part of an array, and returns the new array sort() Sorts the elements of an array splice() Adds/Removes elements from an array toString() Converts an array to a string, and returns the result unshift() Adds new elements to the beginning of an array, and returns the new length valueOf() Returns the primitive value of an array

How do you print the current date? In UTC?

date = new Date(2015, 12, 31); date.toUTCString();

Jasmine syntax?

describe("something", function() { it("can do something", function() { var x = 1 var y; expect(x).toBe(1); expect(y).toBeUndefined(); } })

How do you do unicode characters?

document.body.innerHTML = "\u00A9" Keep in mind some unicode might not render by the browser: "\u0006"

Rewrite body?

document.body.innerHTML = "foo"

Get elements?

document.getElementById, getElementsByTagName, getElementsByClassName

How can you submit a form in JS?

document.myform.submit(); E.g. document.forms["myform"].submit(); ... <form id='myform' action='formmail.pl'>

How do you get command line parameters with Node.js?

e.g. process.argv[2]

Make a URI correct ASCii syntax? e.g. converts unicode to unicode character numbers.

encodeURI()

ES6 module syntax?

export class Employee { ... standard class code } =================== import {Employee} from './library/employee' var e = new Employee();

Navigate DOM?

firstElementChild, lastElementChild, nextElementSibling, parentNode, childNodes Note firstChild() selects things like text and comments, not just elements.

What will this print? var bar = { name: "bar", doJerk: function(cb) { cb() } } var foo = { name: "foo", writeName: function() { console.log(this.name + "..."); }, jerk: function() { var wn = this.writeName; this.writeName(); wn(); bar.doJerk(this.writeName); } }; foo.jerk();

foo ... undefined ... undefined ... "this" is ONLY TO WHAT OBJECT IT IS ASSIGNED TO. Even setting this.writeName to a variable changes it. The variable is NOT assigned to any object, so it is on the global object! Same with callbacks, it passes the callback unbound to the method of the new object.

How can you do inheritance in JavaScript?

function Rectangle() { } Rectangle.prototype = Object.create(Shape.prototype); ======================== // Shape - superclass function Shape() { this.x = 0; this.y = 0; } // superclass method Shape.prototype.move = function(x, y) { this.x += x; this.y += y; console.info('Shape moved.'); }; // Rectangle - subclass function Rectangle() { Shape.call(this); // call super constructor. } // subclass extends superclass Rectangle.prototype = Object.create(Shape.prototype); Rectangle.prototype.constructor = Rectangle;

What is a good website regarding browser compatibility information?

http://www.quirksmode.org/

How do you raise an exception?

if (somethingGoesWrong) { throw { name: "SomethingWentWrong", message: "Something happened bad" } } You could also create an object: function NotNumberException() {} throw new NotNumberException();

Check type?

instanceof

Different syntax for arrow functions?

let addOne = x => x + 1 let add = (x, y) => x + y let addAll = (...numbers) { var sum = 0; numbers.forEach(number => { sum += 1; }); return sum; }

Destructuring in method signatures?

let doWork = function(url, {data, cache, headers}) { return data; } let result = doWork("http://foo.com", { data: "test", cache: false });

External CSS?

link rel="stylesheet" type="text/css" href="mystyle.css"

Debugging in Node?

node debug app.py OR node-inspector - Chrome Dev Tools type debugging

How do you push an NPM module so anyone can use it?

npm init, fill in the details npm publish modulename Then anyone can pull it down! npm install modulename

Get length of variable?

my_variable.length It isn't a method in JS

Try/catch/finally?

try { myroutine(); // may throw three types of exceptions } catch (e) { if (e instanceof TypeError) { // statements to handle TypeError exceptions } else if (e instanceof RangeError) { // statements to handle RangeError exceptions } else if (e instanceof EvalError) { // statements to handle EvalError exceptions } else { // statements to handle any unspecified exceptions logMyErrors(e); // pass exception object to error handler } }

Raise an error that the argument is the wrong type?

try { throw new TypeError('Hello', "someFile.js", 10); } catch (e) { console.log(e instanceof TypeError); // true console.log(e.message); // "Hello" console.log(e.name); // "TypeError" console.log(e.fileName); // "someFile.js" console.log(e.lineNumber); // 10 console.log(e.columnNumber); // 0 console.log(e.stack); // "@Scratchpad/2:2:9\n" }

Latest React.js version?

v0.14.3

Print all keys of an object, even nested?

var a = { "a": 1, "b": { "c": 2 } }; function rec(obj) { for (var prop in obj) { if (typeof(a[prop]) == "object") { document.write(prop); rec(a[prop]); } else { document.write(prop); } } } rec(a);

Detect browser version?

var browser = navigator.appName; var version = navigator.appVersion; or navigator.userAgent e.g. if (navigator.userAgent.search("Chrome") >= 0){ } or better, 3rd party library: if (bowser.msie && bowser.version <= 6) { alert('Hello China'); } else if (bowser.firefox){ alert('Hello Foxy'); } else if (bowser.chrome){ alert('Hello Silicon Valley'); } else if (bowser.safari){ alert('Hello Apple Fan'); } else if(bowser.iphone || bowser.android){ alert('Hello mobile'); }

How to use createElement and appendChild?

var div = document.createElement('div'); div.textContent = "Sup, y'all?"; div.setAttribute('class', 'note'); document.body.appendChild(div);

JavaScript Module pattern?

var jspy = (function() { var _count = 0; var incrementCount = function() { _count++; } var getCount = function() { return _count; } return { incrementCount: incrementCount, getCount: getCount }; })();

How can you do currying by using bind()?

var multiby2 = multiplication.bind(this,2); Now multiby2(b) is equal to multiplication(2,b); multiby2(3); //6 multiby2(4); //8

Switch statement?

var num = 3 switch(num) { case 1: return "A"; break; case 2: return "B"; break; case 3: return "C"; break; default: return "D" break; }

How do you make object members not writeable?

var obj = {}; Object.defineProperty(obj, 'key', { enumerable: false, configurable: false, writable: false, value: 'static' }); ================ OR do it with Object.create: o2 = Object.create({}, { p: { value: 42, writable: true, enumerable: true, configurable: true } });

Programatically add a p tag to a DOM element?

var parent = document.getElementById('parent'); var child = parent.firstElementChild.nextElementSibling; var txt = document.createTextNode("foo"); var p = document.createElement("p"); p.appendChild(txt); child.appendChild(p);

Closure example usages?

var resultSelector = ".result"; $.get("ajax/test.html", function(data) { $(resultSelector).html(data); alert("Load was performed"); }) ------------------------------------------- function outer(){ var a = 1; function middle() { var b = 2; function inner() { var c = 3; return a + b + c; } return inner(); } return middle() } document.write(outer())

Revealing module pattern syntax?

var revealingModulePattern = function(){ var privateVar = 1; function privateFunction(){ alert('private'); }; var publicVar = 2; function publicFunction(){ anotherPublicFunction(); }; function anotherPublicFunction(){ privateFunction(); }; // reveal all things private by assigning public pointers return { publicFunction:publicFunction, publicVar:publicVar, anotherPublicFunction:anotherPublicFunction } }(); revealingModulePattern.publicFunction();

What do streams look like?

var stream = fs.createReadStream(filename); stream.pipe( fs.createWriteStream(filename + ".backup") stream.on("data", function(chunk) { contents += chunk; } stream.on("end", function(end) { done(contents); }

Undefined vs null?

var x // undefined var x = null // null

Messagebox? OK/Cancel box? Question box?

window.alert() window.confirm() window.prompt()

Format number as decimal?

3.321321.toFixed(2) // 3.32

What prints? (function() { var a = b = 5; })(); console.log(b);

5 will print. "b" is a global, so it is visible even outside the IIFE This becomes: var a = 5 b = 5

Open a reference in a new tab?

<a href="" target="_blank"></a>

Submit form from A tag?

<form name="myform" action="index.php"> Search: <input type='text' name='query' /> <a href="javascript: submitform()">Search</a> </form> <script type="text/javascript"> function submitform() { document.myform.submit(); } </script>

How are Refs used in React?

<input ref="myInput" /> var input = this.refs.myInput; var inputValue = input.value;

Reference javascript?

<script src="myscript.js"></script>

Change background color with plain JS?

<script type="text/javascript"> document.body.bgColor="pink"; </script>

Implicit conversions?

"1" + 2 = "12" // string 1 + "2" = "12" // same thing, string

Basic DNS?

"CNAME" record points to another domain name. "A" record points to the actual IP address. blog.dnsimple.com. CNAME aetrion.github.io. aetrion.github.io. CNAME github.map.fastly.net. github.map.fastly.net A 185.31.17.133

Regex multiple match search?

"Hello".match(/l/g) Returns array: [ 'l', index: 2, input: 'Hello' ] MAKE SURE to use the "g" flag, so it can return all matches, not just the first one

How do you reverse a name in javascript?

"Shawn".split("").reverse().join("")

ES6 interact with parent class?

"super" represents the parent. constructor(name) { super(name); } doSomething(foo) { super.doSomething(foo); this.doSomethingElseAlso(); }

Result? var text = 'outside'; function logIt(){ console.log(text); var text = 'inside'; }; logIt();

"undefined". This is because the variable gets hoisted, so the closure outside value doesn't get used. var text = 'outside'; function logIt(){ console.log(text); var text = 'inside'; }; logIt();

String methods. Remove whitespace? All caps?

' f '.trim() 'f'.toUpperCase()

How to write Module pattern?

(function(target) { target.newGlobalObject = { doSomething: ... } })(window)

ES6 new features?

* For...of syntax * Iterators * Spread operator, Rest parameters (ellipses stuff ...) * Block scoping with "let" * Block scoping of functions -- functions inside block are private to the block. Don't have to use IIFE!!! * Arrow functions, which also don't overwrite "this" in callbacks * Default parameter values * Rest parameter - gets the rest of the variables passed in, like *args. Syntax: function foo (a, b, ...c) { c[0] } * Templating and multiline with backticks. Syntax: `${firstname + " " + lastname}` * Promised * MUCH MUCH more

What are different CSS sizing units to know?

* em Relative to the font-size of the element (2em means 2 times the size of the current font) * vw Relative to 1% of the width of the viewport* * vh Relative to 1% of the height of the viewport*

Inheritance in JavaScript?

// Create and define Student. function Student() { // Call the Adult function. Adult.call(this); } // Tell Student to inherit Adult. Student.prototype = new Adult(); Student.prototype.constructor = Student;

What primitives are in JavaScript?

A primitive (primitive value, primitive data type) is data that is not an object and has no methods. In JavaScript, there are 6 primitive data types: string, number, boolean, null, undefined, symbol (new in ECMAScript 2015).

What is a trait that is better about AMD module loading (Require.js) versus CommonJS

AMD modules support asynchronous loading of scripts

How to make a field required in a form?

Add "required" to make it a required field <form action="demo_form.asp" method="post"> <input type="text" name="fname" required> //< Required <input type="submit" value="Submit"> </form>

What is a block?

Anything between curly braces. It does NOT have its own scope. e.g. var a = 1 { var b = 2 } a + b // 3 E.g. if (foo) { // Block }

Call vs apply?

Apply is similar to call except that it takes an array-like object instead of listing the arguments out one at a time magicMultiplication.call(this,3,2); //6 magicMultiplication.apply(this,[5,2]); //10

What owners can "this" have?

Basic functions - global object (window). Events like onclick - element that fired event. Anonymous functions - Create their own "this" unless an arrow function Reassignments change this. So a global function assigned to an event handler will then have "this" of the element, not the global object.

Iterate over an array?

Besides for...in, you can also do array.forEach(function);

Alternative to IIFE in ES6?

Block scoping! { function foo() { return 1; } } foo() // undefined!!!!!!!!

Which module loader allows dynamic exports?

CommonJS. ES6 exports are static. CommonJS allows: if (foo) { exports.something = something else exports.something = somethingelse }

How to validate form fields?

Constraint validation <input type="text" pattern="[1-4]{5}" /> <input type="text" required />

Iterators in JavaScript?

Create a fake one in ES6. Typically has: next(), which returns object with done and value. function makeIterator(array){ var nextIndex = 0; return { next: function(){ return nextIndex < array.length ? {value: array[nextIndex++], done: false} : {done: true}; } } } var it = makeIterator(['yo', 'ya']); console.log(it.next().value); // 'yo' console.log(it.next().value); // 'ya' console.log(it.next().done); // true

How do you make your own iterable classes in ES6?

Create a method with [Symbol.iterator]. Allows you to do "for...of", or call iterable.next() let iterable = { 0: 'a', 1: 'b', 2: 'c', length: 3, [Symbol.iterator]() { let index = 0; return { next: () => { let value = this[index]; let done = index >= this.length; index++; return { value, done }; } }; } }; for (let item of iterable) { console.log(item); // 'a', 'b', 'c' }

Creating a promise in ES6?

Creating promise, you create a new Promise object, passing a function with resole and reject. Using the promise, you just call "then", but you pass one or two functions, first function is success, second is failure. var promise = new Promise(function(resolve, reject) { resolve("Success!"); }); promise.then(function(result) { console.log(result); }, function(err) { console.log(err); });

Do jQuery selection WITHOUT jQuery?

EASY! <div class="foo"> <div id="blah">F<div>Bar</div></div> </div> document.querySelector('.foo div#blah').innerText

Loop over items in an array?

ES introduces for...OF syntax. Remember that for...in array will be the INDEX of the array. let arr = [1, 2, 3]; for (number of arr) { ... }

What are the names of the module loaders in ES?

ES6 CommonJS AMD (usually Require.js)

ES6 default exports?

ES6 can have default or named exports. Default looks like this: //------ myFunc.js ------ export default function () { ... }; //------ main1.js ------ import myFunc from 'myFunc'; myFunc();

Find a string in a string?

Either search or indexOf. Search can do regex. indexOf can be faster. "Hello".search(/lo/) == 3 "Hello".indexOf('lo') == 3

Using Node.js debugger, how do you view variables?

Either type "repl" and print there, or say: watch("variableName") watchers unwatch(0)

How are Node.js callbacks typically structured?

Error first. function(err, data) { }

Extra parameter passed to function?

Extra parameter is ignored sum = (a, b) => a + b sum(2,1,3)

What is a "first class function"? What is a "higher order function"?

First class means it is a "first class citizen", being able to be passed around like any other variable. Higher order means the function RETURNS (or RECEIVES) a first class function.

What caveats are there with SetTimeout?

First, the time specified is a MINIMUM time, not a GUARANTEED time. Second, the current stack AND events in front of it in the Message Queue must complete first. So setTimeout of 500ms will happen in 500ms as long as the current stack and prior messages don't take more than 500ms.

Get and change attributes?

Get attribute

What all shows up when you enumerate an object's properties?

If you do "for ... in ...", it will show ALL properties, including inherited ones. You can enumerate own properties instead with a method call. Also, properties marked not enumerable won't show up.

Destructuring with labels, simplified?

If your destructuring statement uses the same variable names as the assigned object, you don't have to give a variable name. function getName() { return { first: "Shawn", middle: "M", last: "Axsom" } } let { first, last } = getName(); document.body.innerHTML = first;

CSS allows imports, why shouldn't you use them?

Imports can't be downloaded concurrently. It slows down page load.

Multi-line strings?

In ES5, you add each line together as different strings. But in ES6, multiline strings ("Template strings") are denoted with BACKTICKS: var htmlString = `Say hello to multi-line strings!`;

What is destructuring?

In ES6, the name of the ability to unpack values. { someFunction } = objectWithFunction; ================= let x = 1; let y = 2; [x, y] = [y, x] console.log(y) // 1

What is the better alternative to W3schools?

MDN Mozilla Developer Network

What does "enumerable" do on an object property?

Makes it not show up when enumerating object properties.

How are Maps much more flexible than Objects?

Maps are also key-value pairs. But the keys can be things besides a string. E.g. could use even a dom node as a key.

How to get absolute value in JS? Max? Random number? Number rounded down? Up?

Math.abs(-4.2) Math.max(2, 5) Math.random() // Returns between 0 and 1 Math.floor(2.5) Math.ceil(2.5)

How do you generate a random number?

Math.random()

N-Tier Architecture?

Means separation of multiple parts of the program. Usually it is 3 tiers, and it means separation of business logic, client access, and data onto separate servers, separate processes and code.

Can ES6 module syntax load CommonJS?

NO, not exactly, I don't think. Babel / Traceur will convert ES6 modules into CommonJS, so you can do it, but the browser itself doesn't do it.

What causes NaN? Infinite?

NaN: 0 / 0 "a" / 2 Infinite: 3 / 0 999999999999999999999999999999 2**4444

Is "this" undefined outside a function?

No! It refers to the "global" object. So you can do: this.document.write() Will be the same as: document.write()

Does JavaScript support overloading?

No. A second declaration of a method name will overwrite the first one.

Is it possible to prevent someone from changing a property's type?

No. I was wrong about configurable, it just means that you can't change writable/enumerable/configurable

DOM node properties?

Node type, node name, node value

What does typeof return?

Notice it returns "object" for null! Also: typeof NaN //"number" typeof "John" // Returns string typeof 3.14 // Returns number typeof NaN // Returns number typeof false // Returns boolean typeof [1, 2, 3, 4] // Returns object typeof {name:'John', age:34} // Returns object typeof new Date() // Returns object typeof function () {} // Returns function typeof myCar // Returns undefined (if myCar is not declared) typeof null // Returns object

What three ways can you create an object?

Object literal syntax, object constructors, or Object.create(literal/object);

How can you assign values to an object without overwriting existing properties?

Object.assign is available in ES6. var obj = Object.assign(o1, o2, o3); console.log(obj); // { a: 1, b: 2, c: 3 } console.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed.

More reliable alternative to typeof?

Object.prototype.toString.call([1,2,3]); //"[object Array]" Object.prototype.toString.call(new Date); //"[object Date]" Object.prototype.toString.call(/a-z/); //"[object RegExp]" Compare: toType(/a-z/); //"regexp" typeof /a-z/; //"object"

How to compare two objects?

Objects are only equal to themselves (even using == double equals). No built in way to do this. But lodash has: _.isEqual(obj1, obj2) Otherwise you have to create your own function, or most frameworks have helper methods like angular.equals()

Describe a polyfill

Polyfill checks if capabilities are missing, adds it. Shim makes existing capabilities standardized or different. One person described it: A polyfill is code that detects if a certain "expected" API is missing and manually implements it. E.g. if (!Function.prototype.bind) { Function.prototype.bind = ...; } A shim is code that intercepts existing API calls and implements different behavior. The idea here is to normalize certain APIs across different environments.

Describe Polyfills

Polyfills are code that introduce newer features to older browsers. If the browser is newer, the polyfill won't execute, using the real implementation. Otherwise, the polyfill tries to simulate the new functionality as best as possible in the older specifications.

What all ways can you add and remove from an array?

Push, pop Slice - get a range, 0, 3 means return 0, 1, 2 as new array Shift - remove first element Unshift - add new first element SPLICE - Adds to the array at a certain index, possibly removing (replacing) items

How does hoisting work WITH let?

The "let" keyword does NOT get hoisted. function foo() { if (false) { var bar = "3" } return bar; // ERROR: bar is NOT declared. }

Regex search many lines?

The "m" modifier /foo/m

What does "this" equal by default?

The "window" object

What is the name of the JavaScript concept that handles asynchronous calls?

The Event Loop. The Event Loop waits for the current call stack to complete. When it does, it will read from the Event Queue, which stores all Events. It will loop over the Event Queue synchronously (JavaScript is single-threaded). So there can't be two different calls going at once. And a long-running call without an async event causes the UI to lock up, since that is processed after the current Message Queue item is finished processing. There is also an Event Table that lists what events should fire under what conditions, so events originate there and then get placed on the Event Queue.

What happens when not enough parameters are passed to a function?

The missing parameters are "undefined" (NOT null)

What all features does the Navigator global object provide?

The navigator object contains information about the browser. http://www.quirksmode.org/js/detect.html Some examples: navigator.appName = Netscape navigator.appVersion = 5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36 navigator.platform = MacIntel navigator.product = Gecko navigator.userAgent = Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36 navigator.language = en-US

Detect OS version?

The navigator.appVersion string can be used to detect the operating system on the client machine.

Problem? <button id="btn-0">Button 1!</button> <button id="btn-1">Button 2!</button> <button id="btn-2">Button 3!</button> <script type="text/javascript"> var prizes = ['A Unicorn!', 'A Hug!', 'Fresh Laundry!']; for (var btnNum = 0; btnNum < prizes.length; btnNum++) { // for each of our buttons, when the user clicks it... document.getElementById('btn-' + btnNum).onclick = function() { // tell her what she's won! alert(prizes[btnNum]); }; } </script>

The onclick function closure uses btnNum, which gets changed. Closures don't make duplicate data, they keep a reference to the same variable, and change as the variable gets changed outside the scope. Fix it by forcing it to make a copy of the variable, by using it as an argument: document.getElementById('btn-' + btnNum).onclick = function(frozenBtnNum){ return function() { // tell her what she's won! alert(prizes[frozenBtnNum]); }; }(btnNum);

What can you use in string replaces?

The replacement can be a string OR FUNCTION. The function can pass in the match AND capture groups. And you can return what to replace with. Nice!

What is the result? for (let i = 0; i < 10; i++) { } return i;

UNDEFINED. "let" inside for loop arguments is basically part of the block, so "i" isn't known in the function outside of the block.

Main data types in JS?

Undefined Null Number String Boolean Object Array Function

Spread operator?

Unpacks the data structure as individual values. function foo(a, b, c) { } var arr = [1, 2, 3] foo(...arr); // Unpack array, so arr[0] = a, arr[1] = b, etc.

How do you insert an item into the middle of an array?

Use Array.splice(). Arguments: splice(index, amountToReplace, item); var arr = []; arr[0] = "Jani"; arr[1] = "Hege"; arr[2] = "Stale"; arr[3] = "Kai Jim"; arr[4] = "Borge"; console.log(arr.join()); arr.splice(2, 0, "Lene"); console.log(arr.join());

How can you basically have mixins in JavaScript?

Use Object.assign. Object.assign(shark, lazer); shark.shootLazer(); // Shark can shoot lazers!

How do you make an object iterate like an array?

Use iterator of Array.prototype[Symbol.iterator]. let iterable = { 0: 'a', 1: 'b', 2: 'c', length: 3, [Symbol.iterator]: Array.prototype[Symbol.iterator] }; iterable.next() // 'a'

Destructuring with labels?

Use object notation, where the values are the variable names. Notice below that firstName is the VALUE, not the key. function getName() { return { first: "Shawn", last: "Axsom" } } let { first: firstName, last: lastName } = getName(); document.body.innerHTML = firstName;

How can you replace a subset of a string, inserting some of the original string contents and new text?

Use str.replace(regex, function); let r = 'hello'.replace(/(e)(ll)/g, (m, g1, g2) => { return g1 + 'NEW' + g2; }) document.body.innerHTML += r;

Get distinct items in an array?

With ES6 you can use a set: var distinctItems = [...new Set( [1, 1, 2] )]; // [ 1, 2 ]

Does JavaScript support automatic type conversion?

Yes! var s = '5'; var a = s*1; var b = +s; typeof(s); //"string" typeof(a); //"number" typeof(b); //"number"

Does JavaScript pass by reference?

Yes, objects are passed by reference. Primitives are by value.

Jasmine do async events in test?

You can do async, but you have to pass in a variable called "done" into the test, and then call done() when finished.

Use ES6 without having to add transpiling into your build?

You can do this with "es6-shim", which is a library of a bunch of polyfills. IDK if it is as fast or realistic as using a transpiler, but all you have to do is include it as a script src in your code.

Destructuring nested items?

You can repeat destructuring nested. function getName() { return { name: {first: "Shawn", middle: "M", last: "Axsom" } } } let { name: {first, last} } = getName(); document.body.innerHTML = first;

How do you react POST variables in JS in browser?

You can't. POST is a server-side thing. POST is what browser sends from client(your broswer) to the web server. Post data is send to server via http headers, and it is available only at the server end or in between the path (example: a proxy server) from client (your browser) to web-server. So it cannot be handled from client side scripts like JavaScript. You need to handle it via server side scripts like CGI, PHP, Java etc. If you still need to write in JavaScript you need to have a web-server which understands and executes JavaScript in your server like Node.js

Describe WebRTC basic technical description

You create an RTCPeerConnection. You add video and audio capabilities to that connection. You then connect to another user's RTCPeerConnection. One person is the caller, the other is the receiver. Web sockets are usually used to establish the connection. Send web socket message to signaling server.

Example using both spread and rest operators?

addAll method below. Unpack an array with Spread operator. Get a variable number of "numbers" with Rest operator. let addAll = (...numbers) => { var sum = 0; numbers.forEach(number => { sum += number; }); return sum; } let arrNum = [2, 6]; let result = addAll(1, 2, 3, 5, 12, ...arrNum); document.body.innerHTML = result;

ES5 and ES6 versions of default params?

function foo(bar) { bar = bar || "missing"; } function foo(bar = "missing") { }

How do you create a Node web server?

function handleHTTPFunction(req, res) { res.writeHead(200, {"Content-type": "text/plain"}); res.write("Hello world!"); res.end("Okay bye!"); } var http = require("http"); http.createServer(handleHTTPFunction).listen("80", "localhost");

Arguments object sum function?

function sumAll() { var sum = 0; for (var index in arguments) { sum += parseInt(arguments[index]); } return sum } document.getElementById("foo").innerHTML = sumAll(1,2)

How do you do form validation in plain old JS?

function validateform(){ var name=document.myform.name.value; var password=document.myform.password.value; if (name==null || name==""){ alert("Name can't be blank"); return false; }else if(password.length<6){ alert("Password must be at least 6 characters long."); return false; } }

sayHello.bind(obj) using call instead?

function(){sayHello.call(obj)}

Casting string to int? Casting int to string?

parseInt("1") // 1 parseInt("a") // NaN 1.toString() // "1"

Input box?

prompt()

Example of a sum() IIFE?

result = (function sum(a, b){ return a + b })(1, 2)


Kaugnay na mga set ng pag-aaral

Examen Oral - Answer in complete sentences

View Set

Decision Point - Session 3 Vocabulary: The Jesus Question

View Set

A&P 2-Fluid, Electrolyte, and Acid-Base Balance

View Set

Chapter 8: Standard Costs and Variances

View Set

PrepU Newborn Assessment (Ch 18)

View Set