let result = json != null ? json.name : undefined;
Null Check
if a != null return a, else return default value
// Ternary Operator let result = a != null ? a : defaultValue;
// Logical Operator || // When it's used with non-boolean values, the || operator will return a non-boolean value of one of the specified expression or operands. let result = a || defaultValue;
// Nullish Coalescing Operator ?? let result = a ?? defaultValue;
2
if a != null and b != null return b; else return null;
let result = a != null && a.name != null ? a.name : null;
let result = a && a.name;
Statement
For Loop
for (let i = 0; i < arr.length; ++i) arr.forEach((value, index) => { /* ... */ }) for (let index in arr) for (const value of arr)
Print to console
console.log(obj1 [, obj2, ..., objN]);
console.log(obj) console.log(obj1, obj2) console.log("obj is: ", obj) console.log("obj is: ", obj, ". And my name is ", name) console.log("objects are: ", obj1, obj2) console.log("obj is: " + JSON.parse(JSON.stringify(obj)))
console.log(msg [, subst1, ..., substN]);
%oor%O Outputs a JavaScript object.
%dor%i Outputs an integer.
%s Outputs a string.
%f Outputs a floating-point value.
console.log("obj is %o", obj) console.log("Hello, %s. You've called me %d times.", "Bob", 1);
Object
Merge object fields
let json1 = {"name": "Jack"}; let json2 = { ...json1, age: 18 };
Deep copy
let json = {"name": "Jack"}; let copy = JSON.parse(JSON.stringify(json));
// iterates over all enumerable properties of an object. const jsonObj = {name: "Jack", age: 18} for (const key in jsonObj) { console.log(`${key}: ${jsonObj[key]}`); }
Object.entries() or Object.keys()
// to traverse a Javascript object const jsonObj = {name: "Jack", age: 18} Object.entries(jsonObj).forEach(([key, value]) => { console.log(key, value) });
Object.keys(obj).forEach(function(key) { var value = obj[key]; // ... });
to include non-enumerable properties
Object.getOwnPropertyNames(obj).forEach(function(key) { var value = obj[key]; // ... });
Array
Traversal
for (let i = 0; i < arr.length; ++i) arr.forEach((value, index) => { /* ... */ }) for (let index in arr) for (const value of arr)
forEach: executes a provided function once for each array element. another type of for loop.
NOTE: The forEach loop is another type of for loop in JavaScript. However, forEach() is actually an array method, so it can only be used exclusively with arrays. There is also no way to stop or break a forEach loop. If you need that type of behavior in your loop, you’ll have to use a basic for loop.
// creating regular expression from a string, you have to double-up your backslashes \\. const regex = newRegExp('^\\d{10}$'); const regex = newRegExp('^\\d{10}$', 'g');
/regex/mod
// if you use regex syntax, you need eacape / by \/ const regex = /^\d{10}$/; const regex = /^\d{10}$/g;
API
RegExp
regexp.exec(str) - Returns the first match info array. It likes [matched string, group 1, group 2, ...]. The flag g has no effect.
string.match(regexp) - Returns the first match info array [matched string, group 1, group 2, ...], or return an all matched string array [matched string 1, matched string 2, ...] when it uses the flag g.
let s = "hello1, hello2"; s.match(/hello(\d)/); // return the first match object ['hello1', '1', ...] s.match(/hello(\d)/g); // return all match strings ['hello1', 'hello2']
string.matchAll(regexp) - Returns all match info arrays. The regexp must use the flag g (global search).
let s = "hello1, hello2"; s.matchAll(/hello(\d)/); // Uncaught TypeError: String.prototype.matchAll called with a non-global RegExp argument for (const match of s.matchAll(/hello(\d)/g)) { console.log(match); // the match info array console.log(match[0]); // the matched string console.log(match[1]); // the group 1 of the matched string }
string.replace(regexp, replacement) - Returns a string with the first or all matched string replaced.
let s = "hello1, hello2"; s.replace(/hello(\d)/, 'hey'); // 'hey, hello2' s.replace(/hello(\d)/g, 'hey'); // 'hey, hey'
// replace with group let s = "hello1, hello2"; s.replace(/hello(\d)/, "hi$1"); // 'hi1, hello2' s.replace(/hello(\d)/g, "hi$1"); // 'hi1, hi2' // extract group s.replace(/hello(\d)/g, "$1"); // '1, 2'
string.replaceAll(regexp, replacement) - Returns a string with the all matched string replaced. The regexp must use the flag g (global search).
let s = "hello1, hello2"; s.replaceAll(/hello(\d)/, 'hey'); // Uncaught TypeError: String.prototype.replaceAll called with a non-global RegExp argument s.replaceAll(/hello(\d)/g, 'hey'); // 'hey, hey'
// replace with group. // replaceAll(/xxx/g, '') results are same with replace(/xxx/g, '') s.replaceAll(/hello(\d)/g, "hi$1"); // 'hi1, hi2' s.replaceAll(/hello(\d)/g, "$1"); // '1, 2'
string.search(regexp)
string.split(regexp)
Flags
Flag
Description
Corresponding property
d
Generate indices for substring matches.
hasIndices
g
Global search.
global
i
Case-insensitive search.
ignoreCase
m
Allows ^ and $ to match newline characters.
multiline
s
Allows . to match newline characters.
dotAll
u
“Unicode”; treat a pattern as a sequence of Unicode code points.
unicode
v
An upgrade to the u mode with more Unicode features.
unicodeSets
y
Perform a “sticky” search that matches starting at the current position in the target string.
Make sure to use the u flag at the end of the regex pattern (/.../u) to enable Unicode mode, which is necessary when working with Unicode property escapes.