JavaScript Coding Questions

Ace your homework & exams now with Quizwiz!

comparing a boolean with a non boolean, so JavaScript coerces the boolean to a number and compares. false will be coerced to 0 => '0' == 0. so the answer is true.

'0' == false

true true true false

'0' == false Boolean('0') Boolean("0") Boolean(NaN)

Index: 4, element: undefined *IIFE* const arr = [10, 12, 15, 21]; for (var i = 0; i < arr.length; i++) { (function(j) { setTimeout(function() { console.log(`The value ${arr[j]} is at index: ${j}`); }, j * 1000); })(i) } *declare i variable with let* const arr = [10, 12, 15, 21]; for (let i = 0; i < arr.length; i++) { setTimeout(function() { console.log(`The value ${arr[i]} is at index: ${i}`); }, (i) * 1000); } Considering the above code, the console will display four identical messages "The value undefined is at index: 4". This happens because each function executed within the loop will be executed after the whole loop has completed, referencing to the last value stored in i, which was 4.

*how to fix this function?*

- There is typically one global scope, and each function defined has its own [nested] local scope. - Any locally scoped items are not visible in the global scope - unless exposed, meaning if I define functions or variables within a new scope, it's inaccessible outside of that current scope.

- Can think of local scope as any new scope that you create within the global scope. - locally scoped variables are only visible and accessible within their local scopes - each function written in JavaScript creates a new local scope. The locally scoped variables can only be accessed within the function that they are defined. - Any locally scoped items are not visible in the global scope - unless exposed, meaning if I define functions or variables within a new scope, it's inaccessible outside of that current scope.

Observer Design Pattern

- if an object is modified, it broadcasts to dependent objects that a change has occurred. - MVC architecture => the view updates when the model changes. - advantage: decoupling the view from the model to reduce dependencies.

Module Design Pattern

- modules are JavaScript classes. one of many advantages of classes is encapsulation - protecting states and behaviors from being accessed from other classes. - modules should be IIFE (immediately-invoked-function-expressions) to allow for private scopes a.k.a a closure that protect variables and methods *however, it will return an object instead of a function).

Singleton

- only allows for a single instantiation, but many instances of the same object. - it restricts clients from creating multiple objects, after the first object created, it will return instances of itself.

Prototype Design Pattern

- relies on JavaScript prototypical inheritance. - mainly used for creating objects in performance-intensive situations. - to clone an object: 1. a constructor must exist to instantiate the first object. Next, by using the keyword prototype variables and methods bind to the object's structure.

const and let

- will still hoisted, just different from var - live within the block they are in

- .call() and .apply() methods allows you to pass in a scope to a function, which binds the correct this value. - .call() takes individual arguments, .apply() takes an array of arguments - in JavaScript, class methods are not bound by default. If you forget to bid this.handleClick and pass it to onClick, this will be undefined when the function is actually called.

.call() / .apply() / .bind()

12 10 -1 "-9 (next line) 5" -14 6 9px $45 2 undefined 1 1

1 + "2" = "" + 1 + 0 = "" - 1 + 0 = "-9\n" + 5 = "-9\n" - 5 = "2" * "3" = 4 + 5 + "px" = "$" + 4 + 5 = "4" - 2 = "4px" - 2 = null + 1 = undefined + 1 =

false https://stackoverflow.com/questions/51645993/javascript-why-is-this-false-10-9-8-true

10 > 9 > 8 === true

True False True False

2 == "2" 2 === "2" undefined == null undefined === null

True False True (first char) True False False False

5 > 4 "apple" > "pineapple" "2" > "12" undefined == null undefined === null null == "\n0\n" null === +"\n0\n"

false true true true true true

Boolean(null) Boolean('hello') Boolean('0') Boolean(' ') Boolean([]) Boolean(function(){})

for (let i = 1; i <= 100; i++) { let f = i % 3 == 0, b = i % 5 == 0; console.log(f ? (b ? 'FizzBuzz' : 'Buzz') : b ? 'Fizz' : i); }

Create a for loop that iterates up to 100 while outputting "fizz" at multiples of 3, "buzz" at multiples of 5 and "fizzbuzz" at multiples of 3 and 5.

solution: https://docs.google.com/document/d/1XjtASaBy-ZDJuhaH68EdcCEKi_dZ6TL71Gj2PH0boeI/edit?usp=sharing

If you created a React element like Twitter below, what would the component definition of Twitter look like?

let result = [] result.push(...arr) result.push(...arr)

Make this work: duplicate([1,2,3,4,5]); // [1,2,3,4,5,1,2,3,4,5]

example of JavaScript Design Patterns?

Module Design Pattern Prototype Design Pattern Observer Design Pattern Singleton

false NaN doesn't equal to anyone; it does not even equal to itself.

NaN === NaN?

- a variation of the module pattern - purpose: maintain encapsulation and reveal certain variables and methods returned in an object literal. - disadvantage: unable to reference the private methods.

Revealing Module Pattern

- provides encapsulation with public and private members since it returns an object literal. - since we are returning an object, we will prefix the prototype object with a function.

Revealing Prototype Pattern

object

What does the above alert?

this refers to the outer most global object

What is 'this'?

A function does not have to return in order to be called a closure. Simply accessing variables outside of the immediate lexical scope creates a closure. - the combination of a function bundled together (enclosed) with reference to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time. - useful because they let you associate some data (the lexical environment) with a function that operates on that data. - 閉包 (closure) 在比較高層次的概念上,可以想成把函式和一組資料關聯起來。

What is closure?

Each function defined has its own nested scope as we know, and any function defined within another function has a local scope which is linked to the outer function - this link is called the chain.

What is scope chain?

scope refers to the current context of your code.

What is scope?

immediately invoked function expression put parentheses around the function; *JavaScript interpret whatever inside the parentheses as expression*.

What needs to be changed to properly make it an IIFE? what is IIFE?

true (foo will just be overwritten as function)

What prints to the console? true false ReferenceError

2

What value is alerted?

- reduce collision - maintain independence - easier to write your own code

Why is it, in general, a good idea to leave the global scope of a website as-is and never touch it?

to control variable scope

Why need IIFE?

JavaScript 未声明变量直接使用会抛出异常:var name is not defined,如果没有处理异常,代码就停止运行了。但是,使用typeof undeclared_variable并不会产生异常,会直接返回 undefined。 typeof(ss) //undefined console.log(ss) //Uncaught ReferenceError: ss is not defined

difference between not defined and undefined?

target: user actually clicked on currentTarget: the event listener is attached to

difference between target and currentTarget?

Inverse of event delegation. events on an element will "bubble up" and also fires on all parents

explain event bubbling

If you attach an event listener to DOM element, the listener does not only fire on that DOM element, but it fires on every children in that. Happens through *event bubbling* example: if add an event listener to ul, it also adds to all the li in it.

explain event delegation

all var are declared at the top (beginning) of any given function scope

explain hoisting

statement: more like a reference, but not an actual value. expression results in a value.

explain the difference between writing a function as expressions or definitions

false == "" //true false == [] //true false == {} //false "" == 0 //true *"" == []* //true "" == {} //false *0 == []* //true 0 == {} //false 0 == null //false

false == "" false == [] false == {} "" == 0 "" == [] "" == {} 0 == [] 0 == {} 0 == null

7 / 12 要回答這個問題,需要去思考,add5 和 add10 兩個閉包 (closure) 看到的 x 變數值分別是什麼。 這裡我就直接破梗講答案囉! 對 add5 而言,x = 5。 對 add10 而言,x = 10。 add5 和 add10 同樣都是呼叫 makeAdder 的回傳結果,但是就結果而言,分別記住了各自的一組環境。 這個結果的原理來自於這個特性: ☝️每當函式被呼叫時,都會產生一組新的環境 (Lexical Environment)。 所以第一次呼叫makeAdder(5)的時候,創造了一組x = 5的環境,因此add函式看到的x = 5;而第二次回傳的add函式看到的x = 10。 總之 add5 和 add10 看到的 x 變數在記憶體中是不一樣的兩個變數。 http://shubo.io/javascript-closure/

function makeAdder(x) { function add(y) { return x+y } return add } let add5 = makeAdder(5) let add10 = makeAdder(10) add5(2) add10(2)

10

function test(v){ console.log(v) var v = 3} test(10)

1. arrayList = [] 2. arrayList.length = 0; 3. arrayList.splice(0, arrayList.length)

how to clear up javascript array? var arrayList = ['a','b','c','d','e','f'];

false true true

let a = 0; alert( Boolean(a) ); let b = "0"; alert( Boolean(b) ); alert(a == b);

'new global 1' 'local global 2' 'is not defined' 'new global 1' 'global 2'

let g1 = 'global 1' let g2 = 'global 2' { /* Creating a new block scope */ g1 = 'new global 1' let g2 = 'local global 2' console.log(g1) console.log(g2) console.log(g3) let g3 = 'I am not hoisted'; } console.log(g1) console.log(g2)

- whenever you see a function within another function, the inner function has access to the scope in the outer function, this is called lexical scope or closure - also called static scope. - lexical scope does not work backwards

lexical scope

Error: myFunction is not a function

myFunction() var myFunction = function() { console.log("hello") }

typeof 0 typeof true typeof 'Hello' typeof Math typeof null typeof Symbol('Hi')

number boolean string Object *Object* Symbol

undefined function bar() {} function bar(){} var foo console.log(foo) console.log(bar) foo = function bar(){}

output?

undefined 2 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

second question: foo(1,9), what will be the output?

what will be the output?

var a = b = 3 is actually equals to var b = 3; var a = b; a defined? false b defined? true

5

var v = 5 var v console.log(v)

- In a method, this refers to the owner object - Alone, this refers to the global object - In a function, this refers to the global object - In a function, in strict mode, this is undefined - In an event, this refers to the element that received the event. - Methods like call(), and apply() can refer this to any object. https://www.w3schools.com/js/js_this.asp

what is this in JavaScript?

直譯器(interpreter) v.s 編譯器(compiler) 編譯這個步驟就是把原始碼 A 編譯為目的碼 B,就這樣而已,但你要保證 A 跟 B 執行完的結果要相同。 而直譯就是你輸入原始碼 A,輸出就直接是你程式碼裡面要執行的語義,裡面怎麼做的是一個黑箱子。

直譯器 v.s 編譯器


Related study sets

Evaluating Quadratic Functions, Set 3

View Set

business of law hw questions test 3

View Set

Western Civilization 1 CLEP: Cultures

View Set

C6: Functionalism: Antecedent Influences

View Set

Intro to coding: chapters 11,12,13

View Set

Common Sense Life Insurance Licensing Test

View Set