Salesforce JavaScript Developer 1 Exam

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

In the latest version of Node.js what command is used to debug a file, code.js? (Exam Example)

--node --inspect code.js

Node.js server with error handling: let server = new Websocket(path, opts) server._____ _____ What is the rest? (Exam Example)

.on('error', (error) => { //handle error })

let myArray = new Array('1', '2', '3', '4', '5') myArray.splice(1, 3, 'a', 'b', 'c', 'd') myArray is now?

// myArray is now? ["1", "a", "b", "c", "d", "5"] // This code started at index one (or where the "2" was), // removed 3 elements there, and then inserted all consecutive // elements in its place.

let myArray = new Array('Wind', 'Rain', 'Fire') myArray.sort()

// sorts the array so that myArray = ["Fire", "Rain", "Wind"]

let myArray = new Array('a', 'b', 'c', 'd', 'e') myArray = myArray.slice(1, 4) // starts at index 1 and extracts all elementsWhat would this return?

// until index 3, returning [ "b", "c", "d"]

console.log('Hello, world!'); class Polygon { constructor() { this.name = 'yo'; } fred = function() { let x = 'y'; } } let p = new Polygon(); console.log('e: ' + p.fred); //(Possible Exam Example)

//Output: Hello, world! e: function() { let x = 'y'; }

JS Debugging: Name 3 ways to do this. (Exam Example)

1. set in chrome 2. debugger 3. console.log

const array1 = [1, 2, 3, 4]; const reducer = (accumulator, currentValue) => accumulator + currentValue; console.log(array1.reduce(reducer));

10

let fruit = [{type: 'Apple', price: 1.99, quantity: 3}, {type: 'Pear', price: 2.59, quantity: 2} ]; const cost = fruit.reduce((accumulator, currentValue) => {return(accumulator + currentValue.price *currentValue.quantity)}, 0);

11.15 (correct total)

How many parameters does a decorator have?

3 function decoratorFunc(target, property, descriptor)

console.log('e: ' + (true + 3 + 'hi' + null)); (Exam Example)

4hinull console.log('e: ' + (null + 'hi' + null)); // e: nullhinull console.log('e: ' + (null + 3 + 'hi' + null)); // e: 3hinull

What would the following output? let ratings = [5, 4, 3]; ratings.forEach((element) => { console.log(element) } ) ratings.forEach((element, index) => { console.log(index + ' : ' + element) } )

5 4 3 0 : 5 1 : 4 2 : 3

What is this an example of? app.get('/example/a', function (req, res) { res.send('Hello from A!') }) (Exam Example)

An express routing handler, a single callback function to handle a route If more than one parameter needs to be specified, use a semicolon, /example/:timePair Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).

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); }); (Trailhead Question) Would the following correctly execute the code? A p1.then((data) => p2(data)).then(result => result);

Correct. The method promise.then() is used to associate further action with a promise that becomes settled.

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

B arr.sort((a, b) => a - b); Correct. The compare function passed in sort() defines an alternative sort order.

What is wrong with this code? class Car { constructor(brand) { this.carname = brand; } } class Model { constructor(brand, mod) { this.model = mod; super(brand); } }

Child should always extend parent //class Model extends Car { super keyword should be used before the this property in a child class. By calling the super() method in the constructor method, we call the parent's constructor method and gets access to the parent's properties and methods.

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); }); (Trailhead Question) Would the following correctly execute the code? async function getResult() { const data = await p1; return await p2(data); } getResult();

Correct. Using await inside the function causes both to execute.

_________ is actually nothing more than functions that return another function

Decorators

What are some of the basic DOM data types?

Document, node, element, nodeList, attribute, and namedNodemap node - const node = document.createTextNode("This is a new paragraph."); nodeList - const myNodeList = document.querySelectorAll("p");

True or false: In JS arrays must only contain primitive data types.

False - arrays can contain values by reference

Where would the following be used? export {getAges} from './customer/utility.js';

In a passthrough module to allow other classes to easily access a number of different exported data, the from allows this to be done without writing an import line in the passthrough function itself, from like used during imports

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); }); (Trailhead Question) Would the following correctly execute the code? async function getResult() { const data = p1; const result = p2(data); } await getResult();

Incorrect. The await is outside the function calling the data.

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); }); Would the following correctly execute the code? p1().then(function() { p2().then(function(result) { return result; }); }); (Trailhead Question)

Incorrect. The syntax is wrong for calling p1 and p2. D as

Which collections of data are ordered by a key? (Trailhead)

Map and set objects.

When is await express used outside of the async expression? (Trailhead Question)

Never async function example { await... }

Looking at the export and import declarations below, would this work between two different JS files? export { myFunction }; import m from './test';

No, to rename the exported function default would need to be added export { myFunction as default };

backtrace, bt: Print backtrace of current execution frame list(5): List scripts source code with 5 line context (5 lines before and after) watch(expr): Add expression to watch list unwatch(expr): Remove expression from watch list watchers: List all watchers and their values (automatically listed on each breakpoint) repl: Open debugger's repl for evaluation in debugging script's context exec expr: Execute an expression in debugging script's context Execution control# run: Run script (automatically runs on debugger's start) restart: Restart script kill: Kill script Various# scripts: List all loaded scripts version: Display V8's version

Node.js

What is the technical error with this declaration? const userData = () => { return '${this.name} - ${this.getAge()}';}

None - arrow functions can be used to bind the this keyword to an object in the scope that does not depend on how function was invoked

What is wrong with this code? class Truck { constructor(brand) { this.truckname = brand; } sayName( ) { console.log('Truck: ' + this.truckname); }

The this property cannot be accessed by helper functions in class declarations, it can be accessed by the contrustor

Array.from() Creates a new Array instance from an array-like or iterable object. Array.isArray() Returns true if the argument is an array, or false otherwise. Array.of() Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.

Static methods for arrays

What is the symbol data type?

Symbol is a built-in object whose constructor returns a symbol primitive — also called a Symbol value or just a Symbol — that's guaranteed to be unique. Symbols are often used to add unique property keys to an object that won't collide with keys any other code might add to the object, and which are hidden from any mechanisms other code will typically use to access the object. That enables a form of weak encapsulation, or a weak form of information hiding. Every Symbol() call is guaranteed to return a unique Symbol. Every Symbol.for("key") call will always return the same Symbol for a given value of "key". When Symbol.for("key") is called, if a Symbol with the given key can be found in the global Symbol registry, that Symbol is returned. Otherwise, a new Symbol is created, added to the global Symbol registry under the given key, and returned.

What will need to be added since the prototype is lost during object instantiation. myFruits.prototype = Object.create(Fruits.prototype);

The constructor, inheritance will set a structure but the constructor need to be added manually. Object.defineProperty(myFruit.prototype, 'constructor', {value: myFruits, enumerable: false, wriable: true });

Using the History API, what do each of the following events do? - navigate - pushstate - change (Trailhead Question)

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 , , and elements.

What's the output of the code below? let promise = new Promise(function(resolve, reject) { resolve(1); setTimeout(() => resolve(2), 1000); }); promise.then(alert);

The output is: 1. The second call to resolve is ignored, because only the first call of reject/resolve is taken into account. Further calls are ignored. https://javascript.info/promise-basics

What does array.reduce do? const array1 = [1, 2, 3, 4]; const reducer = (accumulator, currentValue) => accumulator + currentValue; // 1 + 2 + 3 + 4 console.log(array1.reduce(reducer));

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value. const numbers = [175, 50, 25]; document.getElementById("demo").innerHTML = numbers.reduce(myFunc); function myFunc(total, num) { return total - num; }

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? (Trailhead Question)

There is a mismatch on the baz dependency that causes the warning. The bar versions are compatible, but the baz versions are not. bar does have a dependency on baz

Generator functions return a generator that can be used with .next allowing access to each item. This makes them idea repeated random number generation.

True

Only one parameter is passed to a decorator when used to decorate a class, this parameter is the target object which is the class that is being decorated.

True

True false: All items must be named when importing multiple from a module that names exports

True

True or False: SetTimeout( ) is only called if the stack is empty, all other messages have been processed, and then it is called x milliseconds after that.

True

True or false: Multiple decorators can be used on class methods and properties?

True

You can change properties of even constant declared objects console.log('Hello, world!') class Polygon { constructor() { this.name = 'yo'; } fred = function() { let x = 'y'; } } const p = new Polygon(); p.name = 'dude'; console.log('e: ' + p.name); (Exam Example)

True

True or false multiple decorators can be used in classes and in-class properties.

True This would handle exceptions thrown by the apiRequest class WidgetStore { @exceptionHandling @apiRequest

True or False: If the values are defined the following would run and import the needed data? export { cube, foo, graph }; // other file import { cube, foo, graph } from './my-module.js';

True, this would work

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

Use a dollar sign followed by curly brackets: ${expression}.

_____________: the class that represents an independent JavaScript execution thread. isMainThread : a boolean that is true if the code is not running inside of a Worker thread. parentPort : the MessagePort allowing communication with the parent thread If this thread was spawned as a Worker.

Worker

Combining two arrays: const cars = ["Saab", "Volvo", "BMW"]; var food = ["pizza", "tacos", "burgers"];

["Saab", "Volvo", "BMW", ...food];

__________ is an Array-like object accessible inside functions that contains the values passed to a function.

arguments function func1(a, b, c) { console.log(arguments[0]); function handle(request, Closure $next , ...guards) { When the function is called with more than 3 arguments, all the arguments after $next will be added to the $guards array.

Arguments object is an ________-like collections of values. The arguments object contains __________ values passed to the function. The arguments object is only available for _________________ functions.

array-like all the values non-arrow functions

Only one parameter is pass to decorator function if it is being used as a _______________ decorator.

class decorator

console.log('Hello, world!') function myIsNaN(num) { if(num == null){ return 0; } if(num2 == 3){ return 3; } } console.log('e: ' + myIsNaN(2)); console.log('e: ' + myIsNaN(2)(3));

errors

In JS, 0 == undefined

false

_____________ is a method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. (Exam Example)

flat( )

To display all properties of an object, debug code finish the following for statement. for (_______________________________) { console.log(`${i} -> ${connections[i]}`);

for (let i in connections) {

How could you import a method inside of a method called upon click?

import('./classDirectory/myClass.js').then(mod) => (mod.myNeededMethod());

The global property Infinity is a numeric value representing infinity.

infinity

A developer needs to pass an array as an argument, the current variable looks like an array but is not one. What can be used to convert this variable into an array?

let arrayVar = Array.from(myVar);

Destructing Assignment Syntax const hero = { name: 'Batman', realName: 'Bruce Wayne' }; const {_____________________ } = hero; name; // => 'Batman', realName; realName; // => 'Bruce Wayne'

name, realName

Given the following Animal constructor: function Animal(size, age) { this.size = size; this.age = age; this.canTalk = false; } How would you create a new instance of the object? (Trailhead Question)

new Animal('large', 10);

What would this return? let count = null; if(count == "" && count== null) { count = true; } return count;

null

let obj = JSON.parse(JSON.stringify(myObj)); obj.name = 'fred'; document.getElementById("demo").innerHTML = obj.name; (Exam Example)

output: fred

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? (Trailhead Question)

popstate Correct. A popstate event is dispatched to the window each time the active history entry changes between two history entries for the same document.

Refer to the code below: 01 const https = require('https'); 02 const server = https.createServer((req, res) => { 03 // code goes here 04 let reqData = JSON.parse(chunk); 05 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((chunk) => { C. req.data((chunk) =>

req.on('data', (chunk) => { Correct. The chunk argument is passed in for JSON.parse to use. B req.get((chunk) => { Incorrect. The get method is used with http requests. C req.data((chunk) => { Incorrect. Data is what is getting passed in, not a method. D req.on('get', (chunk) => { Incorrect. The get argument is not passed in so can not be used this way.

What do each of the following do? Object.seal( ); Object.freeze( ); Object.preventExtensions( ); Object.create( );

seal - can't add or delete , can change existing preventExtensions - can change properties or delete, cannot add new ones freeze - no changes create - new object

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

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.

JS decorator functions are passed three arguments, what are they?

target is the class that our object is an instance of. key is the property name, as a string, that we're applying the decorator to. descriptor is that property's descriptor object.

Name two methods used to access Coordinated Universal Time, method converts a date to a string.

toISOString(); toUTCString();

In JS, 0 == false

true

In JS, null == undefined

true

True or false: You can use strict mode inside of methods, it will not hoist to the top of the class. (Exam Example)

true

What would this return? let count = null; if(count == undefined && count== null) { count = true; } return count;

true So: undefined == null

What would this return? let num; if(num == '' || num == null) { num = true; } return num;

true let fake; console.log((fake == 0)); //false console.log((fake == null)) // true

True or False: A decorator function can extend class methods.

true - it can extend them

Object properties, besides a value, have three special attributes (so-called "flags"), what are they? (Exam Example)

writable - if true, the value can be changed, otherwise it's read-only. enumerable - if true, then listed in loops, otherwise not listed. configurable - if true, the property can be deleted and these attributes can be modified, otherwise not.


Kaugnay na mga set ng pag-aaral

MGMT 680 Ch 13 (Strategic Entrepreneurship_

View Set

Lifespan Review (previous quizzes)

View Set

8.04 Lesson Assessment: Field Study - Bulgaria Unit Test

View Set

Chapter 16 (Supporting Mobile Operating Systems)

View Set

Cardiovascular Emergencies (Chapter 16 EMT)

View Set