Javascript
Module formats
1. Asynchronous Module Definition (AMD) //Calling define with a dependency array and a factory function define(['dep1', 'dep2'], function (dep1, dep2) { //Define the module value by returning a value. return function () {}; }); 2. CommonJS var dep1 = require('./dep1'); var dep2 = require('./dep2'); module.exports = function(){ // ... } 3. Universal Module Definition (UMD) The UMD format can be used both in the browser and in Node.js. 4. System.register The System.register format was designed to support the ES6 module syntax in ES5: import { p as q } from './dep'; var s = 'local'; export function func() { return q; } export class C { } ES6 module f 5. ES6 module format
isInteger --> write a function
Discuss possible ways to write a function isInteger(x) that determines if x is an integer. ES6: Number.isInteger() numeric values are always stored as floating point values. function isInteger(x) { return (x^0) === x; } function isInteger(x) { return Math.round(x) === x; } function isInteger(x) { return (typeof x === 'number') && (x % 1 === 0); } function isInteger(x) { return parseInt(x, 10) === x; } NaN, +- Infinity is not an Integer
Create a function that, given a DOM Element on the page, will visit the element itself and all of its descendents (not just its immediate children). For each element visited, the function should pass that element to a provided callback function. The arguments to the function should be: a DOM element a callback function (that takes a DOM element as its argument)
Visiting all elements in a tree (DOM) is a classic Depth-First-Search algorithm application. Here's an example solution: function Traverse(p_element,p_callback) { p_callback(p_element); var list = p_element.children; for (var i = 0; i < list.length; i++) { Traverse(list[i],p_callback); // recursive call } }
implicitly stringify the parameter value: - {key:'b'} --> "[object Object]" - {key:'c' } --> "[object Object]"
What is the output out of the following code? Explain your answer. var a={}, b={key:'b'}, c={key:'c'}; a[b]=123; a[c]=456; console.log(a[b]); -->>456 As a result, a[b] anda[c] are both equivalent to a["[object Object]"] and can be used interchangeably. Therefore, setting or referencing a[c] is precisely the same as setting or referencing a[b].
coercion
console.log(1 + "2" + "2"); - > "122" console.log(1 + +"2" + "2"); -> "32" console.log(1 + -"1" + "2"); - > "02" console.log(+"1" + "1" + "2"); -> "112" console.log( "A" - "B" + "2"); -> "NaN2" console.log( "A" - "B" + 2); -> NaN Here's why... The fundamental issue here is that JavaScript (ECMAScript) is a loosely typed language and it performs automatic type conversion on values to accommodate the operation being performed. Let's see how this plays out with each of the above examples. Example 1: 1 + "2" + "2" Outputs: "122" Explanation: The first operation to be performed in 1 + "2". Since one of the operands ("2") is a string, JavaScript assumes it needs to perform string concatenation and therefore converts the type of 1 to "1", 1 + "2" yields "12". Then, "12" + "2" yields "122". Example 2: 1 + +"2" + "2" Outputs: "32" Explanation: Based on order of operations, the first operation to be performed is +"2" (the extra + before the first "2" is treated as a unary operator). Thus, JavaScript converts the type of "2" to numeric and then applies the unary + sign to it (i.e., treats it as a positive number). As a result, the next operation is now 1 + 2 which of course yields 3. But then, we have an operation between a number and a string (i.e., 3 and "2"), so once again JavaScript converts the type of the numeric value to a string and performs string concatenation, yielding "32". Example 3: 1 + -"1" + "2" Outputs: "02" Explanation: The explanation here is identical to the prior example, except the unary operator is - rather than +. So "1" becomes 1, which then becomes -1 when the - is applied, which is then added to 1 yielding 0, which is then converted to a string and concatenated with the final "2" operand, yielding "02". Example 4: +"1" + "1" + "2" Outputs: "112" Explanation: Although the first "1" operand is typecast to a numeric value based on the unary + operator that precedes it, it is then immediately converted back to a string when it is concatenated with the second "1" operand, which is then concatenated with the final "2" operand, yielding the string "112". Example 5: "A" - "B" + "2" Outputs: "NaN2" Explanation: Since the - operator can not be applied to strings, and since neither "A" nor "B" can be converted to numeric values, "A" - "B" yields NaN which is then concatenated with the string "2" to yield "NaN2". Example 6: "A" - "B" + 2 Outputs: NaN Explanation: As exlained in the previous example, "A" - "B" yields NaN. But any operator applied to NaN with any other numeric operand will still yield NaN.
recursion (factorial)
console.log( (function f(n){ return ( (n > 1) ? n * f(n-1) : n ) })(10) );
closure alkalmazasa
for (var i = 0; i < 5; i++) { var btn = document.createElement('button'); btn.appendChild(document.createTextNode('Button ' + i)); btn.addEventListener('click', function(){ console.log(i); } ); document.body.appendChild(btn); } (a) What gets logged to the console when the user clicks on "Button 4" and why? --> 5 (b) Provide one or more alternate implementations that will work as expected. for (var i = 0; i < 5; i++) { var btn = document.createElement('button'); btn.appendChild(document.createTextNode('Button ' + i)); btn.addEventListener('click', (function(i) { function(i){ console.log(i); } })(i) ); document.body.appendChild(btn); }
shorthand
object property shorthand ami lehet, data vagy function is (akar parameterrel)
object as key of an object.. call toString by using
var a={}, b={key:'b'}, c={key:'c'}; a[b]=123; a[c]=456; console.log(a[b]); When setting an object property, JavaScript will implicitly stringify the parameter value b and c -> converted to "[object Object]" a[b] and a[c] -> a["[object Object]"] a[c] is precisely the same as setting or referencing a[b].
What is a "closure" in JavaScript? Provide an example. - is an inner function - has access to (1) variable in its own scope, (2) variables in the enclosing function's scope, and (3) global variables.
var globalVar = "xyz"; (function outerFunc(outerArg) { var outerVar = 'a'; (function innerFunc(innerArg) { var innerVar = 'b'; console.log( "outerArg = " + outerArg + "\n" + "innerArg = " + innerArg + "\n" + "outerVar = " + outerVar + "\n" + "innerVar = " + innerVar + "\n" + "globalVar = " + globalVar); })(456); })(123);
"this" not available in inner (clouser) function solution 1. => lexical scope solution 2 =>arrow function
var myObject = { foo: "bar", func: function() { var self = this; console.log("outer func: this.foo = " + this.foo); console.log("outer func: self.foo = " + self.foo); (function() { console.log("inner func: this.foo = " + this.foo); console.log("inner func: self.foo = " + self.foo); }()); } }; myObject.func(); outer func: this.foo = bar outer func: self.foo = bar inner func: this.foo = undefined inner func: self.foo = bar
What would the following lines of code output to the console? console.log("0 || 1 = "+(0 || 1)); console.log("1 || 2 = "+(1 || 2)); console.log("0 && 1 = "+(0 && 1)); console.log("1 && 2 = "+(1 && 2));
|| --> op1 ? op1 : op2 && --> op1 ? op2 : op1
closure alkalmazas for (var i = 0; i < 5; i++) { setTimeout(function() { console.log(i); }, i * 1000 ); }
55555 The reason for this is that each function executed within the loop will be executed after the entire loop has completed and all will therefore reference the last value stored in i, which was 5. Closures (IIFE) can be used to prevent this problem by creating a unique scope for each iteration, storing each unique value of the variable within its scope, as follows: for (var i = 0; i < 5; i++) { (function(x) { setTimeout(function() { console.log(x); }, x * 1000 ); })(i); } This will produce the presumably desired result of logging 0, 1, 2, 3, and 4 to the console.
single var declaration
(function(){ var a = b = 3; })(); console.log("a defined? " + (typeof a !== 'undefined')); console.log("b defined? " + (typeof b !== 'undefined')); -------------------------------------------------------- It is a shorthand for: b = 3; var a = b; -Not using strict mode: a defined? false b defined? true --------> go to global an defined by runtime - In strict mode: will generate a runtime error of ReferenceError: b is not defined - in srict mode y // undeclared, "not defined" variable, ReferenceError (variable is not defined) ----------> but "typeof" return with "undefined" ----------------------------------------------------------------------------------------------------------------
closure alkalmazas
(function(x) { return (function(y) { console.log(x); })(2) })(1); An important feature of closures is that an inner function still has access to the outer function's variables.
Module patterns in ES5
*Immediately Invoked Function Expression (IIFE) *Revealing Module pattern = (IIEF + expose API by return )
destructuring
- assigment in one shut - swap variable - objects - define local variable from and object -can use shorthand
function block = private space
-------------------------------------------------------- What is the significance of, and reason for, wrapping the entire content of a JavaScript source file in a function block? -------------------------------------------------------- This technique creates a closure around the entire contents 1.)- creates a private namespace - helps avoid potential name clashes between different JavaScript modules and libraries 2.) allow for an easily referenceable (presumably shorter) alias for a global variable. pl jquery ->$ reference to the jQuery namespace (function($) { /* jQuery plugin code referencing $ */ } )(jQuery); -------------------------------------------------------- --------------------------------------------------------
typeof
1. typeof null === "object" What is a potential pitfall with using typeof bar === "object" to determine if bar is an object? How can this pitfall be avoided? -------------------------------------------------------- null is an object also (bar !== null) && (typeof bar === "object") or: (bar !== null) && ((typeof bar === "object") || (typeof bar === "function")) or: (bar !== null) && (typeof bar === "object") && (toString.call(bar) !== "[object Array]") -------------------------------------------------------- -------------------------------------------------------- 2. What would following code return? console.log(typeof typeof 1); -------------------------------------------------------- typeof 1 will return "number" and typeof "number" will return string. -------------------------------------------------------- -------------------------------------------------------- 3. What is the value of typeof undefined == typeof NULL? -------------------------------------------------------- The expression will be evaluated to true, since NULL will be treated as any other undefined variable. Note: JavaScript is case-sensitive and here we are using NULL instead of null.
Explain how prototypal inheritance works
All JavaScript objects have a prototype property, that is a reference to another object. When a property is accessed on an object and if the property is not found on that object, the JavaScript engine looks at the object's prototype, and the prototype's prototype and so on, until it finds the property defined on one of the prototypes or until it reaches the end of the prototype chain. This behavior simulates classical inheritance, but it is really more of delegation than inheritance. References https://www.quora.com/What-is-prototypal-inheritance/answer/Kyle-Simpson https://davidwalsh.name/javascript-objects
AMD
Asynchronous Module Definition
semicolons after return is optional -->automatic semicolon insertion (ASI)
Consider the two functions below. Will they both return the same thing? Why or why not? function foo1() { return { bar: "hello" }; } function foo2() { return { bar: "hello" }; } foo1 returns: Object {bar: "hello"} foo2 returns: undefined semicolons are technically optional!!! return statement (with nothing else on the line) is encountered in foo2(), a semicolon is automatically inserted immediately after the return statement. This behavior also argues for following the convention of placing an opening curly brace at the end of a line in JavaScript, rather than on the beginning of a new line
Explain event delegation
Event delegation is a technique involving adding event listeners to a parent element instead of adding them to the descendant elements. The listener will fire whenever the event is triggered on the descendant elements due to event bubbling up the DOM. The benefits of this technique are: *Memory footprint goes down because only one single handler is needed on the parent element, rather than having to attach event handlers on each descendant. *There is no need to unbind the handler from elements that are removed and to bind the event for new elements. References https://davidwalsh.name/event-delegate https://stackoverflow.com/questions/1687296/what-is-dom-event-delegation
Explain how this works in JavaScript
If the new keyword is used when calling the function, this inside the function is a brand new object. If apply, call, or bind are used to call/create a function, this inside the function is the object that is passed in as the argument. If a function is called as a method, such as obj.method() — this is the object that the function is a property of. If a function is invoked as a free function invocation, meaning it was invoked without any of the conditions present above, this is the global object. In a browser, it is the window object. If in strict mode ('use strict'), this will be undefined instead of the global object. If multiple of the above rules apply, the rule that is higher wins and will set the this value. If the function is an ES2015 arrow function, it ignores all the rules above and receives the this value of its surrounding scope at the time it is created. For an in-depth explanation, do check out his article on Medium. References https://codeburst.io/the-simple-rules-to-this-in-javascript-35d97f31bde3 https://stackoverflow.com/a/3127440/1751946
duck typing
In computer programming with object-oriented programming languages, duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface.
callback queue and stack working
In what order will the numbers 1-4 be logged to the console when the code below is executed? Why? (function() { console.log(1); setTimeout(function(){console.log(2)}, 1000); setTimeout(function(){console.log(3)}, 0); console.log(4); })();
mixin
Mixins are sometimes described as being "included" rather than "inherited".
What's the difference between host objects and native objects?
Native objects are objects that are part of the JavaScript language defined by the ECMAScript specification, such as ---> String, Math, RegExp, Object, Function, etc. Host objects are provided by the runtime environment (browser or Node), such as --> window, XMLHTTPRequest, etc.
NaN What is NaN? What is its type? How can you reliably test if a value is equal to NaN?
Not A Number = is number console.log(typeof NaN === "number"); // logs "true" ES6: Number.isNaN()
recursion - The stack overflow is eliminated because the event loop handles the recursion, not the call stack setTimeout( nextListItem, 0);
The following recursive code will cause a stack overflow if the array list is too large. How can you fix this and still retain the recursive pattern? var list = readHugeList(); var nextListItem = function() { var item = list.pop(); if (item) { // process the list item... nextListItem(); } };
UMD
Universal Module Definition
'use strict' = >>>> - enforce stricter parsing and error handling
What is the significance, and what are the benefits, of including 'use strict' at the beginning of a JavaScript source file? - nem lehet az undefined-et valtozonevkent hasznalni - Makes debugging easier - Prevents accidental global Eliminates this coercion. - Disallows duplicate property names or parameter values.---------------------> (e.g., function foo(val1, val2, val1){}), - Throws error on invalid usage of delete. T -Eliminates this coercion. Without strict mode, a reference to a this value of null or undefined is automatically coerced to the global. This can cause many headfakes and pull-out-your-hair kind of bugs. In strict mode, referencing a a this value of null or undefined throws an error.
==, != values equals - implicit type conversion, tries to coerce the values before comparing them ===, !== type equals - no type conversion
What will be the output when the following code is executed? Explain. console.log(false == '0') console.log(false === '0') true false
How work: Array.prototype.reverse "in-place mutators" -- a reverse mutal és visszater egy referenciaval Array.prototype.put --a put ket array-t nem tud osszefuzni
What will the code below output to the console and why? var arr1 = "john".split(''); var arr2 = arr1.reverse(); var arr3 = "jones".split(''); arr2.push(arr3); console.log("array 1: length=" + arr1.length + " last=" + arr1.slice(-1)); console.log("array 2: length=" + arr2.length + " last=" + arr2.slice(-1));
machine epsilon (Number.EPSILON)
What will the code below output? Explain your answer. console.log(0.1 + 0.2); console.log(0.1 + 0.2 == 0.3); function epsEqu(x, y) { return Math.abs(x - y) < Number.EPSILON; } console.log(epsEqu(0.1+0.2, 0.3)); // true 0.30000000000000004 false
Copy a function from an object
What will the following code output to the console and why: var hero = { _name: 'John Doe', getSecretIdentity: function (){ return this._name; } }; var stoleSecretIdentity = hero.getSecretIdentity; console.log(stoleSecretIdentity()); console.log(hero.getSecretIdentity());
palindrome
Write a simple function (less than 80 characters) that returns a boolean indicating whether or not a string is a palindrome.
a function which is return a function
Write a sum method which will work properly when invoked using either syntax below. console.log(sum(2,3)); // Outputs 5 console.log(sum(2)(3)); // Outputs 5
Promises properties
guaranted future (cannot cancel) immutable single value caching
Event delagation <ul id="todo-app"> <li class="item">Walk the dog</li> <li class="item">Pay bills</li> <li class="item">Make dinner</li> <li class="item">Code for one hour</li> </ul> It is working but isn't very efficient. document.addEventListener('DOMContentLoaded', function() { let app = document.getElementById('todo-app'); let items = app.getElementsByClassName('item'); // attach event listener to each item for (let item of items) { item.addEventListener('click', function() { alert('you clicked on item: ' + item.innerHTML); }); } });
one event listener to the whole container, and then be able to access each item when it's actually clicked. document.addEventListener('DOMContentLoaded', function() { let app = document.getElementById('todo-app'); // attach event listener to whole container app.addEventListener('click', function(e) { if (e.target && e.target.nodeName === 'LI') { let item = e.target; alert('you clicked on item: ' + item.innerHTML); } }); });
arrow function one liner
one liner (no braces and return keyword) THIS work with as a function callback parameter, as LEXICAL scope, not dinamyc scope, return value egy kifejezes kell legyen, ha object akkor ()-be kell tenni
rest and spread
rest: function print(...names){ console.log(names) } print('name1', 'name2') spread: function(name1, name2){ console.log(names1) console.log(names1) } const names = ['name1', 'name2'] print(...names) lehet ojectet is speadelni property alapjan