Salesforce JavaScript Developer I Cert Practice Exam

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

Refer to the code below: const https = require('https'); const server = https.createServer((req, res) => { // Line 3: code goes here let reqData = JSON.parse(chunk); console.log(reqData);}); res.end('OK');}); server.listen(8000); Which code does the developer need to add to line 03 to receive incoming request data? A. req.on('data', (chunk) => { B. req.get('data', (chunk) => { C. req.data((chunk) => { D. req.on('get', (chunk) => {

ANSWER A. req.on('data', (chunk) => { Additional Info req.get is used with http requests. req.data is what is getting passed in, not a method. req.on('get', ... the 'get' argument is not passed in so can not be used this way.

Which two syntax examples correctly initialize a value to the variable strLang? A. let strLang = 'javascript'; B. const strLang = 'java' + 'script'; C. let strLang = javascript; D. str strLang = 'javascript';

ANSWER: A. let strLang = 'javascript'; B. const strLang = 'java' + 'script'; Additional Info: Note that C doesn't have a value that has single quotes around the word 'javascript' and for D, 'str' is not a proper identifier

What's the output? (() => { let x, y; try { throw new Error(); } catch (x) { (x = 1), (y = 2); console.log(x); } console.log(x); console.log(y); })(); A: 1 undefined 2 B: undefined undefined undefined C: 1 1 2 D: 1 undefined undefined

ANSWER: A: 1 undefined 2 Additional Info: The catch block receives the argument x. This is not the same x as the variable when we pass arguments. This variable x is block-scoped. Later, we set this block-scoped variable equal to 1, and set the value of the variable y. Now, we log the block-scoped variable x, which is equal to 1. Outside of the catch block, x is still undefined, and y is 2. When we want to console.log(x) outside of the catch block, it returns undefined, and y returns 2.

What's the output? function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } const lydia = new Person('Lydia', 'Hallie'); const sarah = Person('Sarah', 'Smith'); console.log(lydia); console.log(sarah); A: Person {firstName: "Lydia", lastName: "Hallie"} and undefined B: Person {firstName: "Lydia", lastName: "Hallie"} and Person {firstName: "Sarah", lastName: "Smith"} C: Person {firstName: "Lydia", lastName: "Hallie"} and {} D: Person {firstName: "Lydia", lastName: "Hallie"} and ReferenceError

ANSWER: A: Person {firstName: "Lydia", lastName: "Hallie"} and undefined Additional Info: For sarah, we didn't use the new keyword. When using new, this refers to the new empty object we create. However, if you don't add new, this refers to the global object! We said that this.firstName equals "Sarah" and this.lastName equals "Smith". What we actually did, is defining global.firstName = 'Sarah' and global.lastName = 'Smith'. sarah itself is left undefined, since we don't return a value from the Person function.

What's the output? console.log(typeof typeof 1); A: "number" B: "string" C: "object" D: "undefined"

ANSWER: B: "string" Additional Info: typeof 1 returns "number". typeof "number" returns "string"

What's the output? !!null; !!''; !!1; A: false true false B: false false true C: false true true D: true true false

ANSWER: B: false false true Additional Info: null is falsy. !null returns true. !true returns false. "" is falsy. !"" returns true. !true returns false. 1 is truthy. !1 returns false. !false returns true.

What's the output? [[0, 1], [2, 3]].reduce( (acc, cur) => { return acc.concat(cur); }, [1, 2], ); A: [0, 1, 2, 3, 1, 2] B: [6, 1, 2] C: [1, 2, 0, 1, 2, 3] D: [1, 2, 6]

ANSWER: C: [1, 2, 0, 1, 2, 3] Additional Info: [1, 2] is our initial value. This is the value we start with, and the value of the very first acc. During the first round, acc is [1,2], and cur is [0, 1]. We concatenate them, which results in [1, 2, 0, 1]. Then, [1, 2, 0, 1] is acc and [2, 3] is cur. We concatenate them, and get [1, 2, 0, 1, 2, 3]

What are some of the basic DOM data types?

ANSWER: Document, node, element, nodeList, attribute, and namedNodemap.

Where can you use the await keyword and what does it do?

Keyword await only works inside async functions and makes JavaScript wait until that promise settles and returns its result.

When it comes to frameworks, what is one of the main benefits of using popular frameworks?

One of the main benefits is a strong community supporting the framework. This usually results in good documentation and resources.

What are the most important items in your npm package.json file if you plan to publish a package?

The name and version. Together they form a unique identifier for the package.

What is the difference between for ... of and for ... in while iterating over an array of elements?

for ... of iterates via elements while for ... in uses an index through the array.

The promise object returned by the new Promise constructor has internal properties. What are they?

state — initially "pending", then changes to either "fulfilled" when resolve is called or "rejected" when reject is called. result — initially undefined, then changes to value when resolve(value) called or error when reject(error) is called

What's the output? for (let i = 1; i < 5; i++) { if (i === 3) continue; console.log(i); } A: 1 2 B: 1 2 3 C: 1 2 4 D: 1 3 4

ANSWER: C: 1 2 4 Additional Info: The continue statement skips an iteration if a certain condition returns true.

When using async, what type of object is always returned? A. Null B. String C. Promise D. Map

ANSWER: C. Promise

What's the output? function getAge() { 'use strict'; age = 21; console.log(age); } getAge(); A: 21 B: undefined C: ReferenceError D: TypeError

ANSWER: C: ReferenceError Additional Info: With "use strict", you can make sure that you don't accidentally declare global variables. We never declared the variable age, and since we use "use strict", it will throw a reference error. If we didn't use "use strict", it would have worked, since the property age would have gotten added to the global object.

What's the output? function checkAge(data) { if (data === { age: 18 }) { console.log('You are an adult!'); } else if (data == { age: 18 }) { console.log('You are still an adult.'); } else { console.log(`Hmm.. You don't have an age I guess`); } } checkAge({ age: 18 }); A: You are an adult! B: You are still an adult. C: Hmm.. You don't have an age I guess

Answer: C: Hmm.. You don't have an age I guess Additional Info: When testing equality, primitives are compared by their value, while objects are compared by their reference. JavaScript checks if the objects have a reference to the same location in memory. The two objects that we are comparing don't have that: the object we passed as a parameter refers to a different location in memory than the object we used in order to check equality. This is why both { age: 18 } === { age: 18 } and { age: 18 } == { age: 18 } return false.

What's the output? +true; !'Lydia'; A: 1 and false B: false and NaN C: false and false

ANSWER: A: 1 and false Additional Info: The unary plus tries to convert an operand to a number. true is 1, and false is 0. The string 'Lydia' is a truthy value. What we're actually asking, is "is this truthy value falsy?". This returns false.

What's the value of sum? const sum = eval('10*10+5'); A: 105 B: "105" C: TypeError D: "10*10+5"

ANSWER: A: 105 Additional Info: eval evaluates codes that's passed as a string. If it's an expression, like in this case, it evaluates the expression. The expression is 10 * 10 + 5. This returns the number 105.

What happens when we do this? function bark() { console.log('Woof!'); } bark.animal = 'dog'; A: Nothing, this is totally fine! B: SyntaxError. You cannot add properties to a function this way. C: "Woof" gets logged. D: ReferenceError

ANSWER: A: Nothing, this is totally fine! Additional Info: This is possible in JavaScript, because functions are objects! (Everything besides primitive types are objects) A function is a special type of object. The code you write yourself isn't the actual function. The function is an object with properties. This property is invocable.

Here is the package.json for the bar.awesome module: {"name": "bar.awesome","version": "1.3.5","peerDependencies": { "baz": "5.x" }} A particular project has the package.json definition below. {"name": "UC Project Extra","version": "0.0.5","dependencies": { "bar.awesome": "1.3.5", "baz": "6.0.0" }} What happens when a developer executes npm install? A. The command fails because bar.awesome does not have any dependency. B. The command fails because bar versions are not compatible. C. The command succeeds but displays a warning about a version mismatch. D. The command succeeds with no errors or warnings.

ANSWER C. The command succeeds but displays a warning about a version mismatch. Additional Info: bar does have a dependency on baz. The bar versions are compatible, but the baz versions are not. The command does succeed but there is a warning for the mismatched baz dependency.

What will the output be in the console for the following: class Animal { constructor(name) { this.name = name; } printName() { console.log(this.name); } } console.log(typeof Animal);

ANSWER function Additional Info: the underlying object created is still a function

If an application manipulates the browser history using the History API, which event should a developer use to detect when the browser's native back or forward button is clicked? A. popstate B. navigate C. pushstate D. change

ANSWER: A. Popstate, A popstate event is dispatched to the window each time the active history entry changes between two history entries for the same document. Additional Info: The navigate() method loads a specified URL. The pushstate() method pushes the given data onto the session history stack with the specified title. The change event is fired for changes to <input>, <select> , and <textarea> elements.

What will the output be in the console for the following: const myDt = new Date(); console.log(myDt + 10);

ANSWER: Today's date, plus 10 days.

What will the output be in the console for the following: let array1 = ['one', 'two']; let array2 = ['three', 'four']; array1.push(...array2); console.log(...array1);

ANSWER: "one" "two" "three" "four" Additional Info: using ... also acts as a spread and will pull elements one at a time through.

What will the output be in the console for the following: const arr = [1, 4, 9, 16]; const reducer = (acc, curr) => acc + curr; console.log(arr.reduce(reducer));

ANSWER: 30

What will the output be in the console for the following: let s1 = '2 + 2' let s2 = new String('2 + 2') console.log(eval(s1)) console.log(eval(s2)) console.log(eval(s2.valueOf()))

ANSWER: 4 "2 + 2" 4

What is the difference between == vs ===?

ANSWER: == compares the direct value while === compares the direct value and type. Additional Info: 10 == '10' // true 10 === '10' // false

Refer to this code: const p1 = new Promise((resolve, reject) => { setTimeout(() => { resolve('P1 Resolved'); }, 1500); }); const p2 = (data) => new Promise((resolve, reject) => { setTimeout(() => resolve('${data}, P2 Resolved'), 1500, data); }); Which two answers correctly execute p1 and p2? A. p1.then((data) => p2(data)).then(result => result); B. async function getResult() { const data = await p1; return await p2(data); } getResult(); C. p1().then(function() { p2().then(function(result) { return result; }); }); D. async function getResult() { const data = p1; const result = p2(data); } await getResult();

ANSWER: A + B Additional Info: A. The method promise.then() is used to associate further action with a promise that becomes settled. B. Using await inside the function causes both to execute. C. The syntax is wrong for calling p1 and p2. D. The await is outside the function calling the data.

Events are fired inside the browser window and tend to attach to specific items residing in the browser. What are some of these items?

ANSWER: A single element, set of elements, the HTML document loaded in the current tab, or the entire browser window.

Which one is true? const bird = { size: 'small', }; const mouse = { name: 'Mickey', small: true, }; A: mouse.bird.size is not valid B: mouse[bird.size] is not valid C: mouse[bird["size"]] is not valid D: All of them are valid

ANSWER: A. Additional Info: B+C both evaluate to true. mouse.bird is not a valid path in dot notation.

Refer to this code: const getId = new Promise((resolve, reject) => { setTimeout(() => resolve(15), 1500); }); const getBook = bookId => new Promise((resolve, reject) => { setTimeout(() => resolve('${bookId}:JavaScript Algorithms'), 1500); }); getId.then(id => getBook(id)).then(data => data); What is the correct code to replace the last line with an async/await function? A. async function getBookInfo() { const Id = await getId; const result = await getBook(id); } getBookInfo(); B. async function getBookInfo() { const Id = await getId; const result = await getBook(id); } await getBookInfo(); C. await function getBookInfo() { const Id = getId; const result = getBook(id); } async getBookInfo(); D. async function getBookInfo() { const Id = getId; const result = getBook(id); } await getBookInfo();

ANSWER: A. Additional Info: The await expression is always inside an async function.

What's the output? let c = { greeting: 'Hey!' }; let d; d = c; c.greeting = 'Hello'; console.log(d.greeting); A: Hello B: Hey! C: undefined D: ReferenceError E: TypeError

ANSWER: A. Hello Additional Info: In JavaScript, all objects interact by reference when setting them equal to each other. First, variable c holds a value to an object. Later, we assign d with the same reference that c has to the object. When you change one object, you change all of them.

What's the output? String.prototype.giveLydiaPizza = () => { return 'Just give Lydia pizza already!'; }; const name = 'Lydia'; name.giveLydiaPizza(); A: "Just give Lydia pizza already!" B: TypeError: not a function C: SyntaxError D: undefined

ANSWER: A: "Just give Lydia pizza already!" Additional Info: String is a built-in constructor, which we can add properties to. I just added a method to its prototype. Primitive strings are automatically converted into a string object, generated by the string prototype function. So, all strings (string objects) have access to that method!

Which of these values are falsy? 0; new Number(0); (''); (' '); new Boolean(false); undefined; A: 0, '', undefined B: 0, new Number(0), '', new Boolean(false), undefined C: 0, '', new Boolean(false), undefined D: All of them are falsy

ANSWER: A: 0, '', undefined Additional Info: There are 8 falsy values: undefined null NaN false '' (empty string) 0 -0 0n (BigInt(0)) Function constructors, like new Number and new Boolean are truthy.

What's the output? function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } const member = new Person('Lydia', 'Hallie'); Person.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; console.log(member.getFullName()); A: TypeError B: SyntaxError C: Lydia Hallie D: undefined undefined

ANSWER: A: TypeError Additional Info: In JavaScript, functions are objects, and therefore, the method getFullName gets added to the constructor function object itself. For that reason, we can call Person.getFullName(), but member.getFullName throws a TypeError. If you want a method to be available to all object instances, you have to add it to the prototype property: Person.prototype.getFullName = function() { return `${this.firstName} ${this.lastName}`; };

What does this return? [...'Lydia']; A: ["L", "y", "d", "i", "a"] B: ["Lydia"] C: [[], "Lydia"] D: [["L", "y", "d", "i", "a"]]

ANSWER: A: ["L", "y", "d", "i", "a"] Additional Info: A string is an iterable. The spread operator maps every character of an iterable to one element.

What does the setInterval method return in the browser? setInterval(() => console.log('Hi'), 1000); A: a unique id B: the amount of milliseconds specified C: the passed function D: undefined

ANSWER: A: a unique id Additional Info: It returns a unique id. This id can be used to clear that interval with the clearInterval() function.

When you click the paragraph, what's the logged output? <div onclick="console.log('div')"> <p onclick="console.log('p')"> Click here! </p> </div> A: p div B: div p C: p D: div

ANSWER: A: p div Additional Info: If we click p, we see two logs: p and div. During event propagation, there are 3 phases: capturing, target, and bubbling. By default, event handlers are executed in the bubbling phase (unless you set useCapture to true). It goes from the deepest nested element outwards.

Everything in JavaScript is either a... A: primitive or object B: function or object C: trick question! only objects D: number or object

ANSWER: A: primitive or object Additional Info: JavaScript only has primitive types and objects. Primitive types are boolean, null, undefined, bigint, number, string, and symbol. What differentiates a primitive from an object is that primitives do not have any properties or methods; however, you'll note that 'foo'.toUpperCase() evaluates to 'FOO' and does not result in a TypeError. This is because when you try to access a property or method on a primitive like a string, JavaScript will implicitly wrap the primitive type using one of the wrapper classes, i.e. String, and then immediately discard the wrapper after the expression evaluates. All primitives except for null and undefined exhibit this behaviour.

The JavaScript global execution context creates two things for you: the global object, and the "this" keyword. A: true B: false C: it depends

ANSWER: A: true Additional Info: The base execution context is the global execution context: it's what's accessible everywhere in your code.

What's the output? let greeting; greetign = {}; // Typo! console.log(greetign); A: {} B: ReferenceError: greetign is not defined C: undefined

ANSWER: A: {} Additional Info: It logs the object, because we just created an empty object on the global object! When we mistyped greeting as greetign, the JS interpreter actually saw this as global.greetign = {} (or window.greetign = {} in a browser). In order to avoid this, we can use "use strict". This makes sure that you have declared a variable before setting it equal to anything.

All object have prototypes. A: true B: false

ANSWER: All objects have prototypes, except for the base object. The base object is the object created by the user, or an object that is created using the new keyword. The base object has access to some methods and properties, such as .toString. This is the reason why you can use built-in JavaScript methods! All of such methods are available on the prototype. Although JavaScript can't find it directly on your object, it goes down the prototype chain and finds it there, which makes it accessible for you.

When creating a class in JavaScript, what is autogenerated? A. prototype B. constructor C. function D. extension

ANSWER: B. Constructor

Which statement sorts the following number array so it is in ascending order? const arr = [7, 3, 400, 10]; A. arr.sort(); B. arr.sort((a, b) => a - b); C. arr.sort((a, b) => a < b); D. arr.sort((a, b) => b - a);

ANSWER: B. arr.sort((a, b) => a - b); Additional Info: A. The sort() function sorts values as strings, which will sort this as [10, 3, 400, 7]. C. The compare function expects a positive, negative, or 0 to be returned. D. The compare function will actually reverse the order of the numbers.

A developer wants to set a breakpoint in his code while in the editor so they don't have to switch to the browser. What is the in-line command for setting a breakpoint? A. break B. debugger C. debug D. breakpoint

ANSWER: B. debugger

Which of the following is NOT a Promise state? A. rejected B. failed C. pending D. fulfilled

ANSWER: B. failed

A developer wants to use a module called DatePrettyPrint. This module exports one default function called printDate(). How can a developer import and use the printDate() function? A. import printDate() from '/path/DatePrettyPrint.js'; printDate(); B. import printDate from '/path/DatePrettyPrint.js'; printDate(); C. import DatePrettyPrint from '/path/DatePrettyPrint.js'; DatePrettyPrint.printDate(); D. import printDate from '/path/DatePrettyPrint.js'; DatePrettyPrint.printDate();

ANSWER: B. import printDate from '/path/DatePrettyPrint.js'; printDate(); Additional Info: Once imported by name, you must call the imported method directly by name. You must call the methods directly or use the * to import all methods.

Given the following Animal constructor: function Animal(size, age) { this.size = size; this.age = age; this.canTalk = false; } Which method creates a new instance of the object? A. Object.create('Animal'); B. new Animal('large', 10); C. Object.prototype(Animal); D. Object.new(Animal);

ANSWER: B. new Animal('large', 10); Additional Info: A. The create method needs the object name without quotes. C. This is an incorrect way to use a prototype. Prototypes are used to add methods to existing constructors. D. This is not the correct way to use the new keyword. It is not a method.

What's the output? let number = 0; console.log(number++); console.log(++number); console.log(number); A: 1 1 2 B: 1 2 2 C: 0 2 2 D: 0 1 2

ANSWER: C: 0 2 2 Additional Info: The postfix unary operator ++: Returns the value (this returns 0) Increments the value (number is now 1) The prefix unary operator ++: Increments the value (number is now 2) Returns the value (this returns 2) This returns 0 2 2.

What's the output? const person = { name: 'Lydia', age: 21, }; for (const item in person) { console.log(item); } A: { name: "Lydia" }, { age: 21 } B: "name", "age" C: "Lydia", 21 D: ["name", "Lydia"], ["age", 21]

ANSWER: B: "name","age" Additional Info: With a for-in loop, we can iterate through object keys, in this case name and age. Under the hood, object keys are strings (if they're not a Symbol). On every loop, we set the value of item equal to the current key it's iterating over. First, item is equal to name, and gets logged. Then, item is equal to age, which gets logged.

What's the output? function sayHi() { return (() => 0)(); } console.log(typeof sayHi()); A: "object" B: "number" C: "function" D: "undefined"

ANSWER: B: "number" Additional Info: The sayHi function returns the returned value of the immediately invoked function expression (IIFE). This function returned 0, which is type "number". FYI: there are only 7 built-in types: null, undefined, boolean, number, string, object, and symbol. "function" is not a type, since functions are objects, it's of type "object".

What does this return? const firstPromise = new Promise((res, rej) => { setTimeout(res, 500, 'one'); }); const secondPromise = new Promise((res, rej) => { setTimeout(res, 100, 'two'); }); Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); A: "one" B: "two" C: "two" "one" D: "one" "two"

ANSWER: B: "two" Additional Info: When we pass multiple promises to the Promise.race method, it resolves/rejects the first promise that resolves/rejects. To the setTimeout method, we pass a timer: 500ms for the first promise (firstPromise), and 100ms for the second promise (secondPromise). This means that the secondPromise resolves first with the value of 'two'. res now holds the value of 'two', which gets logged.

What's the output? var num = 8; var num = 10; console.log(num); A: 8 B: 10 C: SyntaxError D: ReferenceError

ANSWER: B: 10 Additional Info: With the var keyword, you can declare multiple variables with the same name. The variable will then hold the latest value. You cannot do this with let or const since they're block-scoped.

What's the output? const shape = { radius: 10, diameter() { return this.radius * 2; }, perimeter: () => 2 * Math.PI * this.radius, }; console.log(shape.diameter()); console.log(shape.perimeter()); A: 20 and 62.83185307179586 B: 20 and NaN C: 20 and 63 D: NaN and 63

ANSWER: B: 20 and NaN Additional Info: Note that the value of diameter is a regular function, whereas the value of perimeter is an arrow function. With arrow functions, the this keyword refers to its current surrounding scope, unlike regular functions! This means that when we call perimeter, it doesn't refer to the shape object, but to its surrounding scope (window for example). There is no value radius on that object, which returns NaN.

What's the output? const a = {}; const b = { key: 'b' }; const c = { key: 'c' }; a[b] = 123; a[c] = 456; console.log(a[b]); A: 123 B: 456 C: undefined D: ReferenceError

ANSWER: B: 456 Additional Info: Object keys are automatically converted into strings. We are trying to set an object as a key to object a, with the value of 123. However, when we stringify an object, it becomes "[object Object]". So what we are saying here, is that a["[object Object]"] = 123. Then, we can try to do the same again. c is another object that we are implicitly stringifying. So then, a["[object Object]"] = 456. Then, we log a[b], which is actually a["[object Object]"]. We just set that to 456, so it returns 456.

What's the output? const foo = () => console.log('First'); const bar = () => setTimeout(() => console.log('Second')); const baz = () => console.log('Third'); bar(); foo(); baz(); A: First Second Third B: First Third Second C: Second First Third D: Second Third First

ANSWER: B: First Third Second Additional Info: We have a setTimeout function and invoked it first. Yet, it was logged last. This is because in browsers, we don't just have the runtime engine, we also have something called a WebAPI. The WebAPI gives us the setTimeout function to start with, and for example the DOM. After the callback is pushed to the WebAPI, the setTimeout function itself (but not the callback!) is popped off the stack. Now, foo gets invoked, and "First" is being logged. foo is popped off the stack, and baz gets invoked. "Third" gets logged. The WebAPI can't just add stuff to the stack whenever it's ready. Instead, it pushes the callback function to something called the queue. This is where an event loop starts to work. An event loop looks at the stack and task queue. If the stack is empty, it takes the first thing on the queue and pushes it onto the stack. bar gets invoked, "Second" gets logged, and it's popped off the stack.

How long is cool_secret accessible? sessionStorage.setItem('cool_secret', 123); A: Forever, the data doesn't get lost. B: When the user closes the tab. C: When the user closes the entire browser, not only the tab. D: When the user shuts off their computer.

ANSWER: B: When the user closes the tab. Additional Info: The data stored in sessionStorage is removed after closing the tab. If you used localStorage, the data would've been there forever, unless for example localStorage.clear() is invoked.

What's the output? function getPersonInfo(one, two, three) { console.log(one); console.log(two); console.log(three); } const person = 'Lydia'; const age = 21; getPersonInfo`${person} is ${age} years old`; A: "Lydia" 21 ["", " is ", " years old"] B: ["", " is ", " years old"] "Lydia" 21 C: "Lydia" ["", " is ", " years old"] 21

ANSWER: B: ["", " is ", " years old"] "Lydia" 21 Additional Info: If you use tagged template literals, the value of the first argument is always an array of the string values. The remaining arguments get the values of the passed expressions!

Which statement sorts the following string array so it is in descending order? const arr = ["Banana", "Orange", "Apple", "Mango"]; A. arr.sort(); B. arr.sort((a, b) => a - b); C. arr.reverse(); D. arr.sort((a, b) => b - a);

ANSWER: C. arr.reverse(); Additional Info: A. The sort() function sorts values as strings in ASCENDING order: ["Apple", "Banana", "Mango", "Orange"]; B,D. Expect a number array.

How do you instantiate a value as a BigInt? A. Nothing, JavaScript will automatically cast a number to a BigInt if the value is greater than ((2^53) - 1) B. const bigInt = BigInt.parse(1234567890123456789012345678901234567890); C. const bigInt = 1234567890123456789012345678901234567890n; D. const bigInt = BigInt.parse('1234567890123456789012345678901234567890');

ANSWER: C. const bigInt = 1234567890123456789012345678901234567890n; Additional Info: BigInt does NOT work in IE.

What's the output? function getAge(...args) { console.log(typeof args); } getAge(21); A: "number" B: "array" C: "object" D: "NaN"

ANSWER: C: "object" The rest parameter (...args) lets us "collect" all remaining arguments into an array. An array is an object, so typeof args returns "object"

What's the output? function* generator(i) { yield i; yield i * 2; } const gen = generator(10); console.log(gen.next().value); console.log(gen.next().value); A: [0, 10], [10, 20] B: 20, 20 C: 10, 20 D: 0, 10 and 10, 20

ANSWER: C: 10, 20 Additional Info: Regular functions cannot be stopped mid-way after invocation. However, a generator function can be "stopped" midway, and later continue from where it stopped. Every time a generator function encounters a yield keyword, the function yields the value specified after it. Note that the generator function in that case doesn't return the value, it yields the value. First, we initialize the generator function with i equal to 10. We invoke the generator function using the next() method. The first time we invoke the generator function, i is equal to 10. It encounters the first yield keyword: it yields the value of i. The generator is now "paused", and 10 gets logged. Then, we invoke the function again with the next() method. It starts to continue where it stopped previously, still with i equal to 10. Now, it encounters the next yield keyword, and yields i * 2. i is equal to 10, so it returns 10 * 2, which is 20. This results in 10, 20.

What is the output of the following: for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1); } for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1); } A: 0 1 2 and 0 1 2 B: 0 1 2 and 3 3 3 C: 3 3 3 and 0 1 2

ANSWER: C: 3 3 3 and 0 1 2 Additional Info: In the first loop, the var i value is GLOBAL, which means the value is set OUTSIDE of the scope of the loop. So the var i value is incremented independent of the setTimeout function firing. let and const are block-scoped and follow the increment accordingly.

What's the output? const numbers = [1, 2, 3]; numbers[10] = 11; console.log(numbers); A: [1, 2, 3, 7 x null, 11] B: [1, 2, 3, 11] C: [1, 2, 3, 7 x empty, 11] D: SyntaxError

ANSWER: C: [1, 2, 3, 7 x empty, 11] Additional Info: When you set a value to an element in an array that exceeds the length of the array, JavaScript creates something called "empty slots". These actually have the value of undefined, but you will see something like: [1, 2, 3, 7 x empty, 11] depending on where you run it (it's different for every browser, node, etc.)

What is the event.target when clicking the button? <div onclick="console.log('first div')"> <div onclick="console.log('second div')"> <button onclick="console.log('button')"> Click! </button> </div> </div> A: Outer div B: Inner div C: button D: An array of all nested elements.

ANSWER: C: button Additional Info: The deepest nested element that caused the event is the target of the event. You can stop bubbling by event.stopPropagation

What's the output? let a = 3; let b = new Number(3); let c = 3; console.log(a == b); console.log(a === b); console.log(b === c); A: true false true B: false false true C: true false false D: false true true

ANSWER: C: true false false Additional Info: new Number() is a built-in function constructor. Although it looks like a number, it's not really a number: it has a bunch of extra features and is an object. When we use the == operator, it only checks whether it has the same value. They both have the value of 3, so it returns true. However, when we use the === operator, both value and type should be the same. It's not: new Number() is not a number, it's an object. Both return false.

What's the output? const obj = { 1: 'a', 2: 'b', 3: 'c' }; const set = new Set([1, 2, 3, 4, 5]); obj.hasOwnProperty('1'); obj.hasOwnProperty(1); set.has('1'); set.has(1); A: false true false true B: false true true true C: true true false true D: true true true true

ANSWER: C: true true false true Additional Info: All object keys (excluding Symbols) are strings under the hood, even if you don't type it yourself as a string. This is why obj.hasOwnProperty('1') also returns true. It doesn't work that way for a set. There is no '1' in our set: set.has('1') returns false. It has the numeric type 1, set.has(1) returns true.

What's the output? const obj = { a: 'one', b: 'two', a: 'three' }; console.log(obj); A: { a: "one", b: "two" } B: { b: "two", a: "three" } C: { a: "three", b: "two" } D: SyntaxError

ANSWER: C: { a: "three", b: "two" } Additional Info: If you have two keys with the same name, the key will be replaced. It will still be in its first position, but with the last specified value.

Which of the following is FALSE about Modules? A. Modules always execute in strict mode, which means that variables need to be declared. B. They only get executed once, which is right when they are loaded. C. Import statements get hoisted, which means that all dependencies will execute right when the module is loaded. D. Modules must include a constructor to be exported.

ANSWER: D. Modules must include a constructor to be exported.

What's the output? class Chameleon { static colorChange(newColor) { this.newColor = newColor; return this.newColor; } constructor({ newColor = 'green' } = {}) { this.newColor = newColor; } } const freddie = new Chameleon({ newColor: 'purple' }); console.log(freddie.colorChange('orange')); A: orange B: purple C: green D: TypeError

ANSWER: D. TypeError Additional Info: The colorChange function is static. Static methods are designed to live only on the constructor in which they are created, and cannot be passed down to any children. Since freddie is a child, the function is not passed down, and not available on the freddie instance: a TypeError is thrown.

Given two nested divs and the code below which window.onload kicks off: the window loads and fires the following event => { document.querySelector('.outerDiv') .addEventListener('click', displayOuterMessage, true); document.querySelector('.innerDiv') .addEventListener('click', displayInnerMessage, true); }; What order will the event listeners be called when the innerDiv is clicked? A. displayInnerMessage, displayOuterMessage B. displayInnerMessage only C. displayOuterMessage only D. displayOuterMessage, displayInnerMessage

ANSWER: D. displayOuterMessage, displayInnerMessage Additional Info: Events in the target phase will trigger all listeners on an element in the order they were registered.

What are the two main properties of an error object that's passed as an argument to catch in a try...catch construct? A. name and stacktrace B. title and message C. title and stack D. name and message

ANSWER: D. name and message

What will the output be in the console for the following: const months = ['Jan', 'March', 'April', 'June']; months.splice(3, 1, 'May'); console.log(months);

ANSWER: ["Jan", "March", "April", "May"] Additional Info: splice takes the position [3], notes if you should delete the number of items in the position [1] (this is why June was removed), and adds the item in the splice position [ 'May'].

What's the output? function sum(a, b) { return a + b; } sum(1, '2'); A: NaN B: TypeError C: "12" D: 3

ANSWER: D: "12" Additional Info: JavaScript is a dynamically typed language: we don't specify what types certain variables are. Values can automatically be converted into another type without you knowing, which is called implicit type coercion. Coercion is converting from one type into another. In this example, JavaScript converts the number 1 into a string, in order for the function to make sense and return a value. During the addition of a numeric type (1) and a string type ('2'), the number is treated as a string. We can concatenate strings like "Hello" + "World", so what's happening here is "1" + "2" which returns "12".

What are the three phases of event propagation? A: Target > Capturing > Bubbling B: Bubbling > Target > Capturing C: Target > Bubbling > Capturing D: Capturing > Target > Bubbling

ANSWER: D: Capturing > Target > Bubbling Additional Info: During the capturing phase, the event goes through the ancestor elements down to the target element. It then reaches the target element, and bubbling begins.

What's the output? const person = { name: 'Lydia' }; function sayHi(age) { return `${this.name} is ${age}`; } console.log(sayHi.call(person, 21)); console.log(sayHi.bind(person, 21)); A: undefined is 21 Lydia is 21 B: function function C: Lydia is 21 Lydia is 21 D: Lydia is 21 function

ANSWER: D: Lydia is 21 function Additional Info: With both, we can pass the object to which we want the this keyword to refer to. However, .call is also executed immediately! .bind. returns a copy of the function, but with a bound context! It is not executed immediately.

What's the output? let person = { name: 'Lydia' }; const members = [person]; person = null; console.log(members); A: null B: [null] C: [{}] D: [{ name: "Lydia" }]

ANSWER: D: [{ name: "Lydia" }] Additional Info: First, we declare a variable person with the value of an object that has a name property. Then, we declare a variable called members. We set the first element of that array equal to the value of the person variable. Objects interact by reference when setting them equal to each other. When you assign a reference from one variable to another, you make a copy of that reference. (note that they don't have the same reference!) Then, we set the variable person equal to null. We are only modifying the value of the person variable, and not the first element in the array, since that element has a different (copied) reference to the object. The first element in members still holds its reference to the original object. When we log the members array, the first element still holds the value of the object, which gets logged.

What will the output be in the console for the following: let message = { hello : 'Hello', names : ['Sue', 'Joe'], showMessage: function() { this.names.forEach(name => { console.log(this.hello + ' ' + name); }); } } message.showMessage();

ANSWER: Hello Sue Hello Joe Additional Info: The arrow function that ES6 introduced has the lexical scope built in.

What will the output be in the console for the following: let message = { hello : 'Hello', names : ['Sue', 'Joe'], showMessage: function() { let self = this; this.names.forEach(function(name) { console.log(self.hello + ' ' + name); }); } } message.showMessage();

ANSWER: Hello Sue Hello Joe Additional Info: The self variable references what is known as the "lexical scope," because it was defined within the showMessage function.

Which collections of data are ordered by a key?

ANSWER: Map and set objects.

What will the output be in the console for the following: console.log(x); let x = 10;

ANSWER: ReferenceError Additional Info: let and const do not do hoisting.

What will the output be in the console for the following: let s_prim = 'foo' let s_obj = new String(s_prim) console.log(typeof s_prim) console.log(typeof s_obj)

ANSWER: String Object

What will the output be in the console for the following: function showContact (firstName, lastName, ...titles) { console.log(firstName + ' ' + lastName + ', ' + titles[0] + ' and ' + titles[1]); } showContact('Sue', 'Johnson', 'Developer', 'Architect');

ANSWER: Sue Johnson, Developer and Architect Additional Info: ... allows you to take an unknown number of parameters in that space

What are the different data types used in JavaScript?

ANSWER: There are 8 basic data types in JavaScript: 1. Number for numbers of any kind: integer or floating-point, integers are limited by ±((2^53)-1). 2. BigInt is for integer numbers of arbitrary length. 3. String for strings. A string may have zero or more characters, there's no separate single-character type. 4. Boolean for true/false. 5. NULL for unknown values - a standalone type that has a single value null. Note, typeof null returns "object" even though it is NOT and object. 6. Undefined for unassigned values - a standalone type that has a single value undefined. 7. Object for more complex data structures. 8. Symbol for unique identifiers.

What will the output be in the console for the following: import { printMsg } from './module1.js'; import { msg1, msg2 } from './module2.js'; msg1 = 'Did this variable change?'; printMsg(msg1 + msg2);

ANSWER: TypeError: Assignment to constant variable. Additional Info: You CANNOT reassign the exported value. It can only be changed from inside the module it was exported from.

What is the proper syntax for adding placeholders in template literals?

ANSWER: Use a dollar sign followed by curly brackets: ${expression}. Additional Info: let name = "John"; // embed a variable alert( `Hello, ${name}!` ); // Hello, John! // embed an expression alert( `the result is ${1 + 2}` ); // the result is 3 Note this only works if you use backticks, `, and not single(') or double(") quotes otherwise the results will be shown as literal, ie: Hello, ${name}!

A developer is not able to use a variable outside a function that is defined inside a function. What could be causing this?

ANSWER: Variables defined INSIDE a function cannot be accessed from anywhere OUTSIDE the function, because the variable is defined only in the scope of the function.

When using the `const` identifier to create an instance of an object, are the properties changeable?

ANSWER: Yes. An object declared as `const` can be modified. The `const` fixes the value of the object, but NOT its contents.

What will the output be in the console for the following: const months = ['Jan', 'March', 'April', 'June']; months.splice(1, 0, 'Feb'); console.log(months);

ANSWER: ["Jan", "Feb", "March", "April", "June"] Additional Info: splice takes the position [1], notes if you should delete the number of items in the position [0], and adds the item in the splice position [ 'Feb'].

What will the output be in the console for the following: const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.'; const regex = /[A-Z]/g; const found = paragraph.match(regex); console.log(found);

ANSWER: ["T","I"] Additional Info: If the g flag is used, all matches will be returned. If the g flag is NOT used, then only the first match will be returned.

What will the output be in the console for the following: const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.'; const regex = /[A-Z]/; const found = paragraph.match(regex); console.log(found);

ANSWER: ["T"] Additional Info: If the g flag is used, all matches will be returned. If the g flag is NOT used, then only the first match will be returned.

What will the output be in the console for the following: const arr = [1, 2, 3]; arr.push(6); console.log(arr); arr.pop(); console.log(arr); arr.shift(); console.log(arr); arr.unshift(8); console.log(arr);

ANSWER: [1,2,3,6] [1, 2, 3] [2,3] [8,2,3]

What will the output be in the console for the following: const arr = [1, 4, 9, 16]; const mapA = arr.map(x => x * 2); console.log(mapA);

ANSWER: [2,8,18,32]

What will the output be in the console for the following: const arr = [1, 4, 9, 16]; const mapA = arr.filter(x => x % 2); console.log(mapA);

ANSWER: [4,16]

What will the output be in the console for the following: const arr = [1, 4, 9, 16]; console.log(arr.slice(1,3));

ANSWER: [4,9]

What will the output be in the console for the following: [2, 5, 9].forEach(logArrayElements); function logArrayElements(element, index, array) { console.log('a[' + index + '] = ' + element); }

ANSWER: a[0] = 2, a[1] = 5, a[2] = 9

How would you alias msg1 as msg3 in the example below? import { msg2, msg1 } from './module2.js'; printMsg(msg1 + msg2);

ANSWER: import { msg2, msg1 as msg3 } from './module2.js'; printMsg(msg3 + msg2); Additional Info: If you try to use the msg1 variable name you get a reference error telling you that msg1 is not defined.

What will the output be in the console for the following: console.log(x); var x = 10;

ANSWER: undefined Additional Info: var is susceptible to hoisting.

What will the output be in the console for the following: let message = { hello : 'Hello', names : ['Sue', 'Joe'], showMessage: function() { this.names.forEach(function(name) { console.log(this.hello + ' ' + name); }); } } message.showMessage();

ANSWER: undefined Sue undefined Joe Additional Info: Referencing the 'this' keyword inside the nested function just refers to the scope in which the object was invoked, which in this case is global, meaning the variable hello does not exist.


Kaugnay na mga set ng pag-aaral

Brunner Chapter 43: Assessment of Digestive and Gastrointestinal Function

View Set

ОГЭ Part 2 Travel, Traditions, Holidays

View Set