JavaScript Developer I Cheat Sheet
JavaScript Developer I Cheat Sheet
OVERVIEW
Multiple Choice Questions: 65 ques (5 unscored), pass: 65%, duration: 105 mins (No questions from LWC)
Server Side Testing Variables, Trailmix: Prepare for your Salesforce JavaScript
JavaScript 7% Types, & Developer I Credential
8% Collections
23% Trail: Study for the Salesforce JavaScript Developer
I Exam
Asynchronous
Programming
13%
Debugging &
Error Handling
7% Objects, Lightning Web Components Specialist
Functions, & Superbadge
Browser & Classes
Events 25%
17%
Primitive falsey Object Wrapper & Type Casting Falsey always returns false typeof (‘99’) // “string” returns a
Boolean false Boolean b = new Boolean(‘false); string with a value
if(0){
Number 0 and Number num = new Number(9.08); //block never executes instanceof New String (‘Bat’);
(holds NaN let num2 = 9.08; } //checks value is of object
decimal, float, num === num2; //false instance.
integer, NaN) num == num2; //false; typeof(null); //”object”
Number (‘9’); // 9
String (““) or Type Coercion & Operator
(‘’) Number.parseFloat(‘9.09’); Precedence const p = Number (‘9’);
Number.parseInt(‘2’); p instanceof Number; //false
symbol 10 + ‘2’ + undefined; // “102undefined”
String str = new String(‘sun’); true + 10 * 2; //21 const q = new Number (‘10’);
null null ‘bat’ + null; // “batnull” q instanceof Number; //true
“35” – 5; //30
undefined undefined
Refer: Grammar & Types.
COLLECTIONS
ARRAYS [INDEXED COLLECTION] - Stores multiple values into single variable. Refer: Array
let fruits = [‘Apple’, ‘Banana’, ‘Orange’]; //single dimensional array //following creates array taking each character
let fruits = Array.from (‘Apple’); // [“A”, “p”, “p”, “l”, “e”],
let fruits = new Array (‘Apple’, ‘Banana’, ‘Orange’);
let arr = Array.of(5); //[5], here 5 is value of 0th index
let arr = [ [‘a’, 1], [‘b’, 2], [‘c’, 3]]; //multi-dimensional array let arr2 = Array (3); //[undefined, undefined, undefined] , creates array with size 3
Array.isArray(fruits); //true
Loop through an Array
for…in (index wise) for…of (element wise) Traditional for loop for…each (operates on function)
let fruits = ['Apple', 'Banana', 'Orange']; let fruits = ['Apple', const arr = [1, 4, 9, 16]; [2, 5, 9].forEach(logArrayElements);
'Banana', 'Orange'];
for (let x in fruits) { for (let i=0; i< arr.length; i++){ function logArrayElements(element, index,
console.log(fruits[x]); for (let x of fruits) { console.log(arr[i]); array) {
} console.log(x); } console.log('a[' + index + '] = ' + element);
// Apple, Banana, Orange } }
//1,4,9,16
//Apple, Banana, Orange //a[0] = 2, a[1] = 5, a[2] = 9
Creating and returning new Array (original array content does not change)
map function – creates an array based on filter – creates a new array with reduced number slice – returns shallow copy portion of an array
function’s operations on the conditions applied. into new Array object.
const arr = [1, 4, 9, 16]; const arr = [1, 4, 9, 16]; const arr = [1, 4, 9, 16];
// pass a function to map // pass a function to map console.log(arr.slice(1,3)); //final index omitted
const mapA = arr.map(x => x * 2); const mapA = arr.filter(x => x % 2);
// expected output: Array[4,9]
console.log(mapA); console.log(mapA);
// expected output: Array [2, 8, 18, 32] // expected output: Array[4,16]
Changing original array content
sort – returns sorted array splice – changes the content by reduce – executes reducer function on each push – add elements(s) at end.
adding or removing elements element resulting single output value.
const arr = [1, 4, 9, 16]; const arr = [1, 4, 9, 16]; const arr = [1, 4, 9, 16]; const arr = [1, 4, 9, 16];
const reducer = (acc, curr) => acc + curr; arr.push(25); //Array[1,4,9,16,25]
console.log(arr.sort()); //replaces first element with 5
//Array[1,16,4,9] arr.splice(0,1,5); // 1 + 4 + 9 + 16 arr.pop(); //removes last element
console.log(arr.reduce(reducer)); //output: 30
console.log(arr); //Array[5,4,9,10]
refer shift, unshift functions
JSON.parse – parse a JSON string and converts JavaScript value or JSON.stringify – converts JavaScript object or value to JSON String.
object.
const json = '{"result":true, "count":42}'; console.log(JSON.stringify([new Number(3), new String('false'), new
const obj = JSON.parse(json); Boolean(false)]));
console.log(obj.result); //true
//expected output: "[3,"false", false]"
Using new operator from class Using literal Using function Using Prototype with Object.create
class Employee { let emp = { function createEmp (name, dept){ const employee = {
constructor() { return { name: '',
name: "Santanu",
this.name = ''; name: name, dept: ''
dept: "IT"
this.dept = 'general'; dept: dept }
}
} }
const emp = Object.create (employee);
} }
emp.name = 'Santanu';
let emp = new Employee(); let emp = createEmp('Santanu', 'IT'); emp.dept = 'IT';
emp.name = 'Santanu';
DEFINING AND USING PROPERTIES
Key/value using semi-colon Assigning hardcoded Dynamic assignment Using Object.defineProperty Using getter/setter
property
let emp = { let emp = { emp [dynamicValue] = Object.defineProperty(emp, 'DoJ', let emp = {
‘Kolkata’; { sname: '',
name: "Santanu", name: "Santanu",
value: new Date() get name(){
dept: "IT" dept: "IT" emp [‘id’] = 1001;
}); return this.sname;
} }
Refer: Enumerable, Configurable, },
emp.Id = “1001”;
Writable set name(str){
//to delete property
this.sname = str;
delete emp.name;
}
}
emp.name ='Santanu';
Object.keys – returns enumerable keys let emp = { console.log (Object.keys(emp)); // Array [“name”, “dept”]
console.log (Object.values(emp)); //Array [“Santanu”, “IT”]
Object.values – returns list of property values name: "Santanu",
const returnTarget = Object.assign(emp, {a:1, b:2});
dept: "IT"
Object.assign – copy objects/properties console.log(returnTarget); // Object { a:1,b:2,dept: “IT” ,name: “Santanu” }
}
Object.seal(emp);
Object.freeze – objects cannot be changed anymore
delete emp.name; //cannot delete
Object.seal – no new properties, existing properties Object.freeze(returnTarget);
will be non-configurable returnTarget.dept = “Finance” //cannot change property value
FUNCTIONS
DEFINING FUNCTIONS
Global Context, refers to Function with/out strict mode Function is called on an Object, this Function is used as Constructor; this refers to
window refers to Object instance itself newly created Object instance
console.log (this === function f1() { var o = { function myFunction() {
window); return this; prop: 10,
this.num = 10;
a = 45; }
myFunc: function() {
console.log(window.a); // In a browser: }
return this.prop;
//45 f1() === window; // true
} var o = new myFunction();
};
function f2() { console.log(o.num); // 10
'use strict'; console.log(o.myFunc()); // 10
return this;
}
f2() === undefined; // true
Arrow function holds this Example of Dynamic Binding Using call: specify this and pass Using apply: this and Using bind: this and
context parameters individually array as parameters receive a reference
var globalObject = this; let product = {name: "Prod1"} works.call(product, 'height', 'width'); works.apply(product, let prod =
['height', 'width']); works.bind(product);
var foo = (() => this); function works(arg1, arg2){
//Output: Prod1 has height and prod('height', 'width');
foo() === globalObject; console.log(`${this.name} has //Output: Prod1 has
width
// true ${arg1} and ${arg2}`); height and width
//Output: Prod1 has
} height and width
ASYNCHRONOUS PROGRAMMING
Not to prevent our applications to perform certain tasks that could be delayed due to other time-consuming operations, perform that in async way.
Callback function – is passed as param which is Promises – Putting aside a long running function, when Async – Typically used with Promise
being called at any point of time. Like, setInterval it is resolved or rejected and call stack is empty, we which resolves to a value and await is also
is calling myCallback in every second up to thrice then use its value. used with it.
var iCount = 1; let myPromise = new Promise((resolve, reject)=>{ const promise1 = Promise.resolve('First')
setTimeout(() => resolve("done"), 1000); const promise2 = Promise.reject('Second')
var intervalID = setInterval (myCallback, 1000,
setTimeout(() => reject("error"), 2000);
'Hello', 'World');
}); const runPromises = async () => {
function myCallback(a, b) { return await Promise.all([promise1,
myPromise.then(result => {console.log(result);}
promise2])
console.log(a,b); ).catch(error => console.log(error)
}
).finally(()=> console.log('finally'));
if (iCount ===3) clearInterval (intervalID);
runPromises()
iCount++; .then(res => console.log(res))
} //Output: done, finally [as resolve is returned first] .catch(err => console.log(err))
//Output: if we change reject timeout to 500 then output will be
Hello World error, finally //Output: Second, if we use Promise.race
Hello World Promise states – fulfilled, rejected, pending then First will be the output.
Hello World For Promise.allSettled, output will Array
Methods – all, allSettled, race. Refer: Promise with First and Second values.
CLASSES
Class is a template for an object and is a “syntactic sugar” on Prototype. It has properties and methods. JavaScript does not support multiple inheritance.
Create a class with height, width Extend Shape class and call parent class’ constructor and Difference with Prototype
property and calculateArea method methods by super keyword
class Shape { class Square extends Shape { 1. Function created by class labelled by special
constructor (height, width, name) { internal property
constructor (height, width) {
super(height, width);
this.height = height; [FunctionKind]]:"classConstructor"
this.name = name;
this.width = width; 2. Unlike regular function, it must be called with
}
} new keyword.
calculateArea(){
calculateArea(){ super.calculateArea(); 3. Methods of a class are non-enumerable. A class
console.log('Calculate Area'); console.log(`${this.name} area is`, this.height* this.width); definition sets enumerable flag to false to all the
} } methods in the prototype.
} } 4. Classes always run in strict mode. Refer Class
//instantiate class and call its method
let myShape = new Square(20,30,'Square Shape');
myShape.calculateArea();
//Output: Calculate Area, Square Shape area is 600
ERROR HANDLING
MODULES
Module is file which can be reused.
console.log – outputs a message to web console console.assert – writes an error message when assertion is false, if assertion is
true then nothing happens.
console.info - outputs an informational message to web console
console.assert(false, 'comparing values', !!true);
console.error - outputs an error message to web console
//Output: Assertion failed {“comparing values”} true
console.warn - outputs a warning message to web console
Refer: Console
console.table – displays data in tabular format
TYPES OF TESTING
White-box testing Black-box testing False positive – may not fail when we break
High Complexity. Testing Efficient for large segment of code. application code
Efficient in finding errors and problems. Code access is not required.
Helps to optimize code. Less complex. False negative – fail when we refactor code
Requires developer’s introspection. Separation between user and developer perspective.
REFERENCES
https://trailhead.salesforce.com/en/content/learn/trails/study-for-the-salesforce-javascript-developer-i-exam
https://javascript.info/js
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
FURTHER READING
Tips for passing Salesforce certified JavaScript Developer I Certification by Santanu Boral
ABOUT AUTHOR
Santanu Boral, Salesforce MVP, 23x certified (including Salesforce JavaScript Dev I certification)
Twitter: @santanuboral
Linkedin: Santanu Boral
My Blog: http://santanuboral.blogspot.com/