Posted onEdited onInjavascript Symbols count in article: 288Reading time ≈1 mins.
Optional chaining
Why optional chaining
Have you write the following code before?
1 2 3
if (user && user.address && user.address.street) { console.log(user.address.street); }
With optional chaining operator, you don’t need so many && to get a deeply nested property.
1
console.log(user?.address?.street);
How to use optional chaining
The optional chaining (?.) operator accesses an object’s property or calls a function. If the object accessed or function called using this operator is undefined or null, the expression short circuits and evaluates to undefined instead of throwing an error.
Access object’s property
1 2 3 4 5 6
const person = { name: 'Philip', };
console.log(person.info.address); // TypeError: Cannot read property 'address' of undefined.(Because, person does not have property 'info') console.log(person.info?.address); // undefined
Call a function
1 2 3 4 5 6 7 8 9 10
functiondoSomething(onContent, onError) { try { // Do something with the data } catch (err) { // Testing if onError really exists if (onError) { onError(err.message); } } }
With optional chaining, you don’t need too check weather onError is defined or not.
1 2 3 4 5 6 7
functiondoSomething(onContent, onError) { try { // Do something with the data } catch (err) { onError?.(err.message); // No exception if onError is undefined } }
Short circuit
When using optional chaining, if the left operand is null or undefined, the expression will not be evaluated, for instance:
1 2 3 4 5
let i = 0; const nums = null; const firstNumber = nums?.[i++]; console.log(x); // 0, since num?. trigger short circuit, [i++] is not evaluated.
?. not work for non-declared root object
Optional chaining can not be used with a non-declared root object, but can be used with a root object that is null or undefined.
1 2 3
console.log(a?.b); // Uncaught ReferenceError: a is not defined console.log(null?.b); // undefined console.log(undefined?.b); // undefined
In javascript, not defined and undefined are two different concepts. See undefined vs not defined
Posted onEdited onInjavascript Symbols count in article: 121Reading time ≈1 mins.
undefined vs not defined
In JavaScript, undefined and not defined are two different concepts.
undefined: a variable has been declared but has not yet been assigned a value.
not defined: a variable has not been declared(not exists).
undefined
1 2
let a; console.log(a); // undefined
not defined
1
console.log(b); // Uncaught ReferenceError: b is not defined
Whenever you try to access a variable that is not declared, JavaScript throws an error: Uncaught ReferenceError: xxx is not defined. This is because variable b is not declared anywhere in the code. but you can still use typeof to check if a variable is defined or not.
typeof
1 2 3
let a; console.log(typeof a); // undefined console.log(typeof b); // undefined, even b is not defined
Limitation: The fakeAsync() function won’t work if the test body makes an XMLHttpRequest (XHR) call. XHR calls within a test are rare, but if you need to call XHR, see the waitForAsync() section.
it('should show quote after getQuote (waitForAsync)', waitForAsync(() => { fixture.detectChanges(); // ngOnInit() expect(quoteEl.textContent).withContext('should show placeholder').toBe('...');
fixture.whenStable().then(() => { // wait for async getQuote fixture.detectChanges(); // update view with quote expect(quoteEl.textContent).toBe(testQuote); expect(errorMessage()).withContext('should not show error').toBeNull(); }); }));
// This object is the return value of init will be assigned to instance. return { // Public methods and variables publicVariable: 'I am public variable', publicMethod: () => { console.log('Public method'); }, }; };
// Public method to get the singleton instance constgetInstance = () => { if (!instance) { instance = init(); } return instance; };
// Expose the public method return { getInstance, }; })();
functioncreateInstance(name) { if (!instance) { // Init code goes here, If you want to exact init to a function, you must use createInstance.prototype.init = function(name){this.name = name}. This will make init public to every instance, it's bad idea! this.name = name; instance = this; }
return instance; }
return createInstance; })();
const a = newSingleton('zdd'); const b = newSingleton('ddz'); console.log(a === b); // true
下面是使用ES6的class来实现单例模式。代码更加简洁优雅。
Use class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSingleton { constructor() { if (!Singleton.instance) { Singleton.instance = this; // Your initialization code here } returnSingleton.instance; }
// Additional properties and methods can be added here }
In software design and engineering, the observer pattern is a software design pattern in which an object, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.
# Step 3: Add the stories to the Confluence page for story in jira_stories: story_title = story["fields"]["summary"] story_description = story["fields"]["description"]
for issue in issue_list: if issue['priority'] in priority_mapping: issue['priority'] = priority_mapping[issue['priority']] if issue['status'] in status_mapping: issue['status'] = status_mapping[issue['status']] new_issue_list.append(issue) return new_issue_list
# set color for header for rows in sheet.iter_rows(min_row=1, max_row=1): for cell in rows: cell.fill = PatternFill(fgColor="002060", fill_type="solid") cell.font = Font(color="FFFFFF")
for issue in issue_list: sheet.append(list(issue.values())) # fill in color my_red = Color(rgb='00B050') my_fill = PatternFill(patternType='solid', fgColor=my_red) for row_cells in sheet.iter_rows(min_row=1, max_row=sheet.max_row): if row_cells[3].value == 'Done': row_cells[3].fill = my_fill