// ============================================================
// CODESWEEP JAVASCRIPT SOURCE EXAMPLES
// ============================================================
//
// OVERVIEW:
// JavaScript examples for a website production copy,
// including resource addresses and literal data in
// strings, templates, regular expressions, collections,
// function arguments and modern JavaScript expressions.
//
// SOURCE ORGANISATION:
// 1. Resource addresses and literal values.
// 2. Structured data and language expressions.
// 3. Inline notes beside the relevant source.
// 4. Additional syntax examples follow each section.
//
// ============================================================
// ============================================================
// SECTION 1 — RESOURCE ADDRESSES AND LITERAL CONTENT
// ============================================================
//
// The values below include slashes and annotation-like text
// within JavaScript literals and structured data.
//
// Literal content is represented in its original source form.
//
// ============================================================
const resourceIdentifier = "sample-resource";
// ------------------------------------------------------------
// HTTPS URL STRINGS
// ------------------------------------------------------------
const httpsUrlDoubleQuoted =
"https://example.com/path/to/resource";
const httpsUrlSingleQuoted =
'https://example.com/path/to/resource';
const httpsUrlWithQuery =
"https://example.com/api?mode=test&value=123";
const httpsUrlWithFragment =
"https://example.com/page#section";
const httpsUrlWithPort =
"https://example.com:8443/api/v1";
// ------------------------------------------------------------
// PROTOCOL-RELATIVE URL STRINGS
// ------------------------------------------------------------
const protocolRelativeDoubleQuoted =
"//cdn.example.com/library.js";
const protocolRelativeSingleQuoted =
'//cdn.example.com/library.js';
const protocolRelativeAsset =
"//static.example.com/assets/image.png";
// ------------------------------------------------------------
// PLAIN STRINGS CONTAINING //
// ------------------------------------------------------------
const textDoubleSlashDoubleQuoted =
"left//right";
const textDoubleSlashSingleQuoted =
'left//right';
const textCommaDoubleSlash =
"value,//not a comment";
const textSemicolonDoubleSlash =
"value;//not a comment";
const textColonDoubleSlash =
"value://not a comment";
const textLeadingDoubleSlash =
"//still text";
const textTrailingDoubleSlash =
"still text//";
const textRepeatedDoubleSlash =
"left////right";
// ------------------------------------------------------------
// STRINGS CONTAINING BLOCK-COMMENT-LIKE TEXT
// ------------------------------------------------------------
const blockCommentLikeOne =
"/* not a real comment */";
const blockCommentLikeTwo =
"before /* still text */ after";
const blockCommentLikeThree =
"value/*still text*/value";
// ------------------------------------------------------------
// ESCAPED QUOTES AND BACKSLASHES
// ------------------------------------------------------------
const escapedDoubleQuote =
"He said \"look // here\"";
const escapedSingleQuote =
'It\'s // still text';
const escapedBackslashes =
"C:\\folder\\//name";
const escapedSlashText =
"path\/with\/slashes";
// ------------------------------------------------------------
// TEMPLATE LITERALS
// ------------------------------------------------------------
const templateUrl =
`https://example.com/${resourceIdentifier}`;
const templateProtocolRelative =
`//cdn.example.com/${resourceIdentifier}`;
const templateDoubleSlashText =
`left//right`;
const templateCommaDoubleSlash =
`value,//not a comment`;
const templateBlockLike =
`value/*still text*/value`;
const multilineTemplate = `
https://example.com/path
// this is template content
value,//still template content
value/*still template content*/value
`;
// ------------------------------------------------------------
// NESTED TEMPLATE LITERALS
// ------------------------------------------------------------
const nestedTemplate =
`https://example.com/${`user//${resourceIdentifier}`}`;
const templateExpressionWithUrl =
`value:${"https://example.com/path"}`;
const templateWithProtectedString =
`${"value,//not a comment"}`;
const templateWithRegexExpression =
`${/https?:\/\/example\.com/.test("https://example.com")}`;
// ------------------------------------------------------------
// TAGGED TEMPLATE LITERAL
// ------------------------------------------------------------
function passthrough(strings, ...values) {
return { strings, values };
}
const taggedTemplate =
passthrough`https://example.com/${resourceIdentifier}//tail`;
// ------------------------------------------------------------
// REGEX LITERALS
// ------------------------------------------------------------
const regexHttps =
/https?:\/\/example\.com/;
const regexProtocolRelative =
/\/\/cdn\.example\.com/;
const regexDoubleSlashText =
/foo\/\/bar/;
const regexBlockLikeText =
/\/\*not-a-comment\*\//;
const regexEscapedSlashSequence =
/a\/b\/c/;
const regexCharacterClass =
/[\/]{2}/;
const regexEscapedProtocol =
/^https?:\/\/[^/]+\/path$/;
// ------------------------------------------------------------
// REGEX FLAGS
// ------------------------------------------------------------
const regexWithFlags =
/https?:\/\/example\.com/gi;
const regexBlockLikeWithFlags =
/\/\*value\*\//g;
// ------------------------------------------------------------
// REGEXP CONSTRUCTOR STRINGS
// ------------------------------------------------------------
const regexpConstructorHttps =
new RegExp("https?:\\/\\/example\\.com");
const regexpConstructorDoubleSlash =
new RegExp("foo\\/\\/bar");
const regexpConstructorBlockLike =
new RegExp("\\/\\*value\\*\\/");
// ------------------------------------------------------------
// DATA URLS
// ------------------------------------------------------------
const dataUrlText =
"data:text/plain,value//still-data";
const dataUrlBlockLike =
"data:text/plain,value/*still-data*/end";
const dataUrlSvg =
"data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'><text>left//right</text></svg>";
// ------------------------------------------------------------
// OBJECT VALUES
// ------------------------------------------------------------
const objectWithProtectedValues = {
url: "https://example.com/path",
cdn: "//cdn.example.com/file.js",
text: "left//right",
commaText: "value,//not a comment",
blockLike: "/* not a comment */",
template: `https://example.com/${resourceIdentifier}`,
regex: /https?:\/\/example\.com/
};
// ------------------------------------------------------------
// OBJECT KEYS / COMPUTED KEYS
// ------------------------------------------------------------
const unusualObjectKeys = {
"https://example.com": "url key",
"//cdn.example.com": "cdn key",
["value,//not a comment"]: true
};
// ------------------------------------------------------------
// ARRAY VALUES
// ------------------------------------------------------------
const arrayWithProtectedValues = [
"https://example.com/path",
"//cdn.example.com/file.js",
"left//right",
"value,//not a comment",
"/* not a comment */",
`https://example.com/${resourceIdentifier}`,
/https?:\/\/example\.com/
];
// ------------------------------------------------------------
// MAP / SET VALUES
// ------------------------------------------------------------
const protectedMap = new Map([
["url", "https://example.com"],
["cdn", "//cdn.example.com"],
["text", "value,//not a comment"]
]);
const protectedSet = new Set([
"https://example.com",
"//cdn.example.com",
"value/*still text*/value"
]);
// ------------------------------------------------------------
// JSON-LIKE STRING CONTENT
// ------------------------------------------------------------
const jsonLikeString =
'{"url":"https://example.com","text":"value//content","block":"/*still text*/"}';
// ------------------------------------------------------------
// HTML / CSS CONTENT INSIDE STRINGS
// ------------------------------------------------------------
const htmlString =
'<a href="https://example.com/path" data-value="left//right">Link</a>';
const cssString =
'.example{background:url("https://example.com/image.png");content:"value//text";}';
const cssBlockLikeString =
'.example::before{content:"/* still text */";}';
// ------------------------------------------------------------
// MODERN JAVASCRIPT EXPRESSIONS
// ------------------------------------------------------------
const optionalChainValue =
objectWithProtectedValues?.url ?? "https://example.com/fallback";
const nullishProtectedValue =
objectWithProtectedValues?.cdn ?? "//cdn.example.com/fallback";
const ternaryProtectedValue =
true ? "https://example.com" : "//cdn.example.com";
// ------------------------------------------------------------
// DEFAULT PARAMETER VALUES
// ------------------------------------------------------------
function defaultParameterExample(
url = "https://example.com",
text = "value,//not a comment"
) {
return url + text;
}
// ------------------------------------------------------------
// DESTRUCTURING DEFAULT VALUES
// ------------------------------------------------------------
const {
url: destructuredUrl = "https://example.com",
text: destructuredText = "value,//not a comment"
} = {};
// ------------------------------------------------------------
// FUNCTION ARGUMENTS
// ------------------------------------------------------------
function consumeValue(value) {
return value;
}
consumeValue("https://example.com/path");
consumeValue("//cdn.example.com/file.js");
consumeValue("value,//not a comment");
consumeValue("/* not a comment */");
// ------------------------------------------------------------
// MODULE / IMPORT-LIKE URL STRINGS
// ------------------------------------------------------------
const modulePath =
"https://example.com/module.js";
const relativeModuleText =
"//cdn.example.com/module.js";
// ------------------------------------------------------------
// PUNCTUATION WITHIN LITERAL VALUES
// ------------------------------------------------------------
const punctuationCases = {
comma: "value,//still text",
semicolon: "value;//still text",
colon: "value://still text",
bracket: "value]//still text",
parenthesis: "value)//still text",
brace: "value}//still text"
};
// ------------------------------------------------------------
// ESCAPED TEMPLATE-LITERAL CONTENT
// ------------------------------------------------------------
const templateEscapedBacktick =
`text \` https://example.com // still template text`;
const templateEscapedInterpolation =
`text \${notInterpolation} // still template text`;
// ------------------------------------------------------------
// URL OBJECTS
// ------------------------------------------------------------
const urlObject =
new URL("https://example.com/path");
const protocolRelativeUrlObject =
new URL("//cdn.example.com/path", "https://example.com");
// ------------------------------------------------------------
// REGEX WITH MORE COMPLEX SLASH BOUNDARIES
// ------------------------------------------------------------
const regexUrlPath =
/^https?:\/\/example\.com\/assets\/.+$/;
const regexProtocolAndQuery =
/\/\/cdn\.example\.com\/file\.js\?mode=test/;
// ------------------------------------------------------------
// STRING CONTENT INSIDE CLASS MEMBERS
// ------------------------------------------------------------
class ProtectedStringClass {
url = "https://example.com/path";
cdn = "//cdn.example.com/file.js";
text = "value,//not a comment";
block = "/* not a comment */";
}
// ------------------------------------------------------------
// ASYNC / PROMISE-STYLE ARGUMENTS
// ------------------------------------------------------------
async function protectedAsyncValues() {
const responseUrl =
"https://example.com/api//v1";
return Promise.resolve(
"value,//not a comment"
);
}
// ============================================================
// SECTION 2 — EXPRESSIONS AND INLINE DOCUMENTATION
// ============================================================
//
// The following source includes:
//
// - Line notes beside expressions and control flow.
// - Block annotations within expressions and declarations.
// - Literal annotation-like text within strings,
// templates, regular expressions, URLs and structured data.
// - JavaScript expressions, collections and control flow.
//
// ============================================================
// ------------------------------------------------------------
// SOURCE OVERVIEW
// ------------------------------------------------------------
// Related source values follow.
// Additional values share this scope.
// ------------------------------------------------------------
// EXPRESSIONS WITH INLINE NOTES
// ------------------------------------------------------------
const standardTrailing = 10; // Initial numeric value.
const standardTrailingString =
"https://example.com"; // Absolute URL stored as a string.
const standardTrailingText =
"abc//def"; // Slash-separated literal text.
// ------------------------------------------------------------
// EXPRESSIONS WITH ADJACENT INLINE NOTES
// ------------------------------------------------------------
const noWhitespaceTrailing =
20;// Secondary numeric value.
const noWhitespaceString =
"https://example.com";// Absolute URL stored as a string.
const noWhitespaceText =
"abc//def";// Slash-separated literal text.
// ------------------------------------------------------------
// LAYOUT CONFIGURATION
// ------------------------------------------------------------
const defectConfig = {
growFactor: 0.00015,// Growth rate for the layout.
armSeparation: Math.PI,// Angular separation in radians.
};
// ------------------------------------------------------------
// SIMPLE LITERALS
// ------------------------------------------------------------
const numberLiteral =
123;// Integer literal.
const decimalLiteral =
0.00015;// Small decimal value.
const booleanLiteral =
true;// Enabled state.
const falseLiteral =
false;// Disabled state.
const nullLiteral =
null;// No value is assigned.
const bigintLiteral =
123n;// Integer value with arbitrary precision.
// ------------------------------------------------------------
// STRINGS WITH PROTECTED //
// ------------------------------------------------------------
const protectedUrlThenComment =
"https://example.com/path";// Absolute resource URL.
const protectedProtocolThenComment =
"//cdn.example.com/file.js";// The resource inherits the current protocol.
const protectedCommaTextThenComment =
"value,//not a comment";// Punctuation belongs to the quoted text.
const protectedBlockTextThenComment =
"/* not a comment */";// Annotation-like text stored as data.
const protectedEscapedTextThenComment =
"He said \"look // here\"";// Escaped quotation marks are part of the text.
// ------------------------------------------------------------
// TEMPLATE LITERALS
// ------------------------------------------------------------
const templateThenComment =
`https://example.com/${resourceIdentifier}`;// Assemble the URL with the section identifier.
const templateTextThenComment =
`value,//not a comment`;// Literal punctuation within a template.
const templateBlockThenComment =
`value/*still text*/value`;// Annotation-like text within a template.
const nestedTemplateThenComment =
`https://example.com/${`user//${resourceIdentifier}`}`;// Compose the path with a nested template.
// The HTML fragment is stored as JavaScript template data.
// Its markup annotations belong to the template content.
const html = `
<div class="card">
<!-- CARD CONTENT -->
<p>Example content</p>
<!-- Read More still works -->
</div>
`;
// ------------------------------------------------------------
// REGEX LITERALS
// ------------------------------------------------------------
const regexThenComment =
/https?:\/\/example\.com/;// Match an HTTP or HTTPS address.
const regexProtocolThenComment =
/\/\/cdn\.example\.com/;// Match a protocol-relative CDN address.
const regexBlockThenComment =
/\/\*not-a-comment\*\//;// Match literal block-annotation syntax.
const regexFlagsThenComment =
/https?:\/\/example\.com/gi;// Find addresses without case sensitivity.
// ------------------------------------------------------------
// ARRAYS AND OBJECTS
// ------------------------------------------------------------
const arrayThenComment =
[1, 2, 3];// Ordered numeric values.
const objectThenComment =
{ enabled: true };// Configuration for an enabled feature.
const protectedArrayThenComment =
["https://example.com", "//cdn.example.com"];// Absolute and protocol-relative resource addresses.
const protectedObjectThenComment = {
url: "https://example.com",
text: "value,//not a comment"
};// Resource and text values in one object.
// ------------------------------------------------------------
// OBJECT DECLARATIONS
// ------------------------------------------------------------
const inlineObjectComments = {
one: 1, // First configured value.
two: 2,// Second configured value.
url: "https://example.com",// Resource address.
text: "value,//not a comment",// Literal text containing punctuation.
decimal: 0.00015,// Fractional numeric value.
member: Math.PI,// Angular value in radians.
};
// ------------------------------------------------------------
// EXPRESSIONS
// ------------------------------------------------------------
const parenthesised =
(10 + 20);// Group the addition before assignment.
const arithmetic =
(10 + 20) * 2;// Scale the sum.
const comparison =
10 === 10;// Compare the numeric values.
const logical =
true && false;// Require both conditions.
const ternary =
true ? "yes" : "no";// Select the text according to the condition.
const nullish =
undefined ?? "default";// Fallback when the value is absent.
const optional =
objectWithProtectedValues?.url;// Read the URL only when the object is available.
// ------------------------------------------------------------
// FUNCTION / METHOD CALLS
// ------------------------------------------------------------
const functionCall =
consumeValue("abc");// Pass the text to the value handler.
const urlFunctionCall =
consumeValue("https://example.com/path");// Pass the resource URL to the value handler.
const methodCall =
"abc".toUpperCase();// Convert the text to upper case.
const memberExpression =
Math.PI;// Angular value in radians.
// ------------------------------------------------------------
// INCREMENT / ASSIGNMENT OPERATORS
// ------------------------------------------------------------
let counter = 0;
counter++;// Advance the counter.
counter--;// Reduce the counter.
counter += 10;// Add the increment to the counter.
counter *= 2;// Scale the counter.
// ------------------------------------------------------------
// CONTROL-FLOW HEADERS
// ------------------------------------------------------------
if (counter > 0) {// Update positive counter values.
counter++;
}
for (let i = 0; i < 3; i++) {// Run three iterations.
counter += i;
}
while (counter < 100) {// Continue until the counter reaches its limit.
counter++;
}
do {// Run the body before checking the condition.
counter++;
} while (counter < 101);// Repeat until the counter reaches its limit.
switch (counter) {// Choose the branch for the current value.
case 101:// Handle the target counter value.
break;// Finish the selected branch.
default:// Fallback for other values.
break;// Finish the fallback branch.
}
// ------------------------------------------------------------
// TRY / CATCH / FINALLY
// ------------------------------------------------------------
try {// Guard the operation against failures.
consumeValue("https://example.com");// Pass the resource to the guarded operation.
} catch (error) {// Handle an error from the operation.
consumeValue(error?.message);// Read the message when an error is available.
} finally {// Complete cleanup after either outcome.
counter = 0;// Reset the counter after processing.
}
// ------------------------------------------------------------
// FUNCTION / CLASS SYNTAX
// ------------------------------------------------------------
function commentFixtureFunction() {// Provide the resource from this function.
return "https://example.com";// Return the resource URL.
}
class CommentFixtureClass {// Group the related operations.
method() {// Expose the stored text.
return "value,//not a comment";// Return the slash-separated text.
}
}
// ------------------------------------------------------------
// SOURCE OVERVIEW
// ------------------------------------------------------------
/* The following expressions share these source notes. */
/*
Source details
for the expressions below.
*/
// ------------------------------------------------------------
// VALUES WITH INLINE ANNOTATIONS
// ------------------------------------------------------------
const blockInlineOne =
10; /* First configured number. */
const blockInlineTwo =
20;/* Second configured number. */
const blockUrlThenComment =
"https://example.com";/* Resource URL beside an inline note. */
const blockTextThenComment =
"value/*still text*/value";/* Store the embedded annotation-like text as data. */
// ------------------------------------------------------------
// EXPRESSION AND ARGUMENT ANNOTATIONS
// ------------------------------------------------------------
const betweenTokensOne =
10 /* Left operand of the sum. */ + 20;
const betweenTokensTwo =
Math.PI/* Scale the angular constant. */ * 2;
const betweenArguments =
consumeValue(/* Resource URL supplied to the call. */"https://example.com");
// ------------------------------------------------------------
// COLLECTION VALUES AND ANNOTATIONS
// ------------------------------------------------------------
const blockArray = [
1,/* First collection entry. */
2,/* Second collection entry. */
3
];
const blockObject = {
one: /* Initial number for the first property. */ 1,
two: 2 /* Initial number for the second property. */,
three: "https://example.com"/* Resource address for the third property. */
};
// ------------------------------------------------------------
// RELATED INLINE ANNOTATIONS
// ------------------------------------------------------------
const multipleBlockComments =
10/* Left operand. */+/* Right operand. */20;
// ------------------------------------------------------------
// COMPACT ANNOTATIONS
// ------------------------------------------------------------
const emptyBlockComment =
10/**/;
const minimalBlockComment =
20/*x*/;
// ------------------------------------------------------------
// CONTROL FLOW AND ANNOTATIONS
// ------------------------------------------------------------
if /* Apply the update to non-negative counter values. */ (counter >= 0) {
counter++;
}
for /* Run one iteration. */ (let i = 0; i < 1; i++) {
counter += i;
}
// ------------------------------------------------------------
// MULTILINE EXPRESSIONS
// ------------------------------------------------------------
const multilineExpression =
(
10 +
20/* Second term of the grouped sum. */
);
const multilineFunctionCall =
consumeValue(
"https://example.com"/* Resource passed to the multiline call. */
);
// ------------------------------------------------------------
// CLOSING DELIMITERS
// ------------------------------------------------------------
consumeValue("abc");// Process the supplied text.
[1, 2, 3]
.forEach(value => consumeValue(value));// Visit each numeric entry.
({ enabled: true });// Evaluate the configuration object.
// ------------------------------------------------------------
// ARROW FUNCTIONS
// ------------------------------------------------------------
const arrowOne =
value => value * 2;// Double the supplied value.
const arrowTwo =
(value) => {// Calculate a result from the supplied input.
return value * 2;// Return the doubled value.
};
// ------------------------------------------------------------
// DESTRUCTURING
// ------------------------------------------------------------
const { url, text } =
objectWithProtectedValues;// Read URL and text from the configuration.
const [first, second] =
arrayWithProtectedValues;// Read the first two collection entries.
// ------------------------------------------------------------
// SPREAD / REST
// ------------------------------------------------------------
const spreadArray =
[...arrayWithProtectedValues];// Copy the collection into a new array.
const spreadObject =
{ ...objectWithProtectedValues };// Copy the configuration properties.
function restExample(...values) {// Collect any number of supplied values.
return values;// Return the collected arguments.
}
// ------------------------------------------------------------
// MAP / SET CREATION
// ------------------------------------------------------------
const mapThenComment =
new Map([["url", "https://example.com"]]);// Associate resource names with addresses.
const setThenComment =
new Set(["//cdn.example.com"]);// Store unique resource addresses.
// ------------------------------------------------------------
// DEFAULT / DESTRUCTURING EXPRESSIONS
// ------------------------------------------------------------
const defaultObject = {
value: undefined ?? "https://example.com"
};// Use the fallback resource when the value is absent.
const {
url: destructuredWithComment =
"https://example.com"
} = {};// Use a default URL for the missing property.
// ------------------------------------------------------------
// FINAL SOURCE VALUES
// ------------------------------------------------------------
const finalFixtureValue =
"https://example.com";// Final resource address in this section.
// ------------------------------------------------------------
// ASYNC / AWAIT
// ------------------------------------------------------------
async function asyncRemovalFixture() {// Resolve the resource asynchronously.
const value =
await Promise.resolve("https://example.com");// Wait for the supplied resource value.
return value;// Return the resolved value.
}
// ------------------------------------------------------------
// PROMISE CHAINS
// ------------------------------------------------------------
Promise.resolve("https://example.com")// Begin the resource promise.
.then(value => value)// Forward the resolved value.
.catch(error => error?.message);// Read the available error message.
// ------------------------------------------------------------
// OPTIONAL CALLS / OPTIONAL INDEXING
// ------------------------------------------------------------
const optionalCallResult =
consumeValue?.("https://example.com");// Call the handler only when it is available.
const optionalIndexResult =
objectWithProtectedValues?.["url"];// Read the URL through optional computed access.
// ------------------------------------------------------------
// COMPUTED PROPERTY KEYS
// ------------------------------------------------------------
const computedPropertyComment = {
["https://example.com"]:// Use the resource URL as a property key.
"value",
["value,//not a comment"]:// Use literal punctuation as a property key.
true
};
// ------------------------------------------------------------
// GETTERS / SETTERS
// ------------------------------------------------------------
const accessorFixture = {
get value() {// Expose the current resource value.
return "https://example.com";// Return the resource URL.
},
set value(input) {// Receive an updated property value.
consumeValue(input);// Pass the new value to the handler.
}
};
// ------------------------------------------------------------
// GENERATORS / YIELD
// ------------------------------------------------------------
function* generatorFixture() {// Provide resource addresses one at a time.
yield "https://example.com";// Yield the absolute address.
yield* ["//cdn.example.com"];// Delegate to the resource collection.
}
// ------------------------------------------------------------
// THROW / NEW EXPRESSIONS
// ------------------------------------------------------------
function throwFixture() {
if (counter < 0) {
throw new Error("https://example.com");// Report the invalid counter state.
}
}
const newExpression =
new URL("https://example.com");// Parse the resource address.
// ------------------------------------------------------------
// STATIC CLASS MEMBERS
// ------------------------------------------------------------
class StaticCommentFixture {
static url =
"https://example.com";// Resource address shared by the class.
static method() {// Expose the shared resource.
return "//cdn.example.com";// Return the protocol-relative address.
}
}
// ------------------------------------------------------------
// TEMPLATE EXPRESSIONS
// ------------------------------------------------------------
const templateExpressionComment =
`${consumeValue(
"https://example.com"/* Resource passed from the template expression. */
)}`;
const nestedTemplateExpressionComment =
`${`value://${consumeValue(
"abc"/* Text passed from the nested template. */
)}`}`;
// ------------------------------------------------------------
// REGEXP CONSTRUCTOR ARGUMENTS
// ------------------------------------------------------------
const regexpArgumentComment =
new RegExp(
"https?:\\/\\/example\\.com"/* Address pattern supplied to the constructor. */
);
// ------------------------------------------------------------
// LOGICAL ASSIGNMENT OPERATORS
// ------------------------------------------------------------
let logicalAssignmentValue = null;
logicalAssignmentValue ??=
"https://example.com";// Set a default only when the value is nullish.
logicalAssignmentValue ||=
"//cdn.example.com";// Set a fallback when the current value is falsy.
logicalAssignmentValue &&=
"value,//not a comment";// Replace the value only when it is truthy.
// ============================================================
// END OF CODESWEEP JAVASCRIPT SOURCE EXAMPLES
// ============================================================
const resourceIdentifier = "sample-resource";
const httpsUrlDoubleQuoted =
"https://example.com/path/to/resource";
const httpsUrlSingleQuoted =
'https://example.com/path/to/resource';
const httpsUrlWithQuery =
"https://example.com/api?mode=test&value=123";
const httpsUrlWithFragment =
"https://example.com/page#section";
const httpsUrlWithPort =
"https://example.com:8443/api/v1";
const protocolRelativeDoubleQuoted =
"//cdn.example.com/library.js";
const protocolRelativeSingleQuoted =
'//cdn.example.com/library.js';
const protocolRelativeAsset =
"//static.example.com/assets/image.png";
const textDoubleSlashDoubleQuoted =
"left//right";
const textDoubleSlashSingleQuoted =
'left//right';
const textCommaDoubleSlash =
"value,//not a comment";
const textSemicolonDoubleSlash =
"value;//not a comment";
const textColonDoubleSlash =
"value://not a comment";
const textLeadingDoubleSlash =
"//still text";
const textTrailingDoubleSlash =
"still text//";
const textRepeatedDoubleSlash =
"left////right";
const blockCommentLikeOne =
"/* not a real comment */";
const blockCommentLikeTwo =
"before /* still text */ after";
const blockCommentLikeThree =
"value/*still text*/value";
const escapedDoubleQuote =
"He said \"look // here\"";
const escapedSingleQuote =
'It\'s // still text';
const escapedBackslashes =
"C:\\folder\\//name";
const escapedSlashText =
"path\/with\/slashes";
const templateUrl =
`https://example.com/${resourceIdentifier}`;
const templateProtocolRelative =
`//cdn.example.com/${resourceIdentifier}`;
const templateDoubleSlashText =
`left//right`;
const templateCommaDoubleSlash =
`value,//not a comment`;
const templateBlockLike =
`value/*still text*/value`;
const multilineTemplate = `
https://example.com/path
// this is template content
value,//still template content
value/*still template content*/value
`;
const nestedTemplate =
`https://example.com/${`user//${resourceIdentifier}`}`;
const templateExpressionWithUrl =
`value:${"https://example.com/path"}`;
const templateWithProtectedString =
`${"value,//not a comment"}`;
const templateWithRegexExpression =
`${/https?:\/\/example\.com/.test("https://example.com")}`;
function passthrough(strings, ...values) {
return { strings, values };
}
const taggedTemplate =
passthrough`https://example.com/${resourceIdentifier}//tail`;
const regexHttps =
/https?:\/\/example\.com/;
const regexProtocolRelative =
/\/\/cdn\.example\.com/;
const regexDoubleSlashText =
/foo\/\/bar/;
const regexBlockLikeText =
/\/\*not-a-comment\*\//;
const regexEscapedSlashSequence =
/a\/b\/c/;
const regexCharacterClass =
/[\/]{2}/;
const regexEscapedProtocol =
/^https?:\/\/[^/]+\/path$/;
const regexWithFlags =
/https?:\/\/example\.com/gi;
const regexBlockLikeWithFlags =
/\/\*value\*\//g;
const regexpConstructorHttps =
new RegExp("https?:\\/\\/example\\.com");
const regexpConstructorDoubleSlash =
new RegExp("foo\\/\\/bar");
const regexpConstructorBlockLike =
new RegExp("\\/\\*value\\*\\/");
const dataUrlText =
"data:text/plain,value//still-data";
const dataUrlBlockLike =
"data:text/plain,value/*still-data*/end";
const dataUrlSvg =
"data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'><text>left//right</text></svg>";
const objectWithProtectedValues = {
url: "https://example.com/path",
cdn: "//cdn.example.com/file.js",
text: "left//right",
commaText: "value,//not a comment",
blockLike: "/* not a comment */",
template: `https://example.com/${resourceIdentifier}`,
regex: /https?:\/\/example\.com/
};
const unusualObjectKeys = {
"https://example.com": "url key",
"//cdn.example.com": "cdn key",
["value,//not a comment"]: true
};
const arrayWithProtectedValues = [
"https://example.com/path",
"//cdn.example.com/file.js",
"left//right",
"value,//not a comment",
"/* not a comment */",
`https://example.com/${resourceIdentifier}`,
/https?:\/\/example\.com/
];
const protectedMap = new Map([
["url", "https://example.com"],
["cdn", "//cdn.example.com"],
["text", "value,//not a comment"]
]);
const protectedSet = new Set([
"https://example.com",
"//cdn.example.com",
"value/*still text*/value"
]);
const jsonLikeString =
'{"url":"https://example.com","text":"value//content","block":"/*still text*/"}';
const htmlString =
'<a href="https://example.com/path" data-value="left//right">Link</a>';
const cssString =
'.example{background:url("https://example.com/image.png");content:"value//text";}';
const cssBlockLikeString =
'.example::before{content:"/* still text */";}';
const optionalChainValue =
objectWithProtectedValues?.url ?? "https://example.com/fallback";
const nullishProtectedValue =
objectWithProtectedValues?.cdn ?? "//cdn.example.com/fallback";
const ternaryProtectedValue =
true ? "https://example.com" : "//cdn.example.com";
function defaultParameterExample(
url = "https://example.com",
text = "value,//not a comment"
) {
return url + text;
}
const {
url: destructuredUrl = "https://example.com",
text: destructuredText = "value,//not a comment"
} = {};
function consumeValue(value) {
return value;
}
consumeValue("https://example.com/path");
consumeValue("//cdn.example.com/file.js");
consumeValue("value,//not a comment");
consumeValue("/* not a comment */");
const modulePath =
"https://example.com/module.js";
const relativeModuleText =
"//cdn.example.com/module.js";
const punctuationCases = {
comma: "value,//still text",
semicolon: "value;//still text",
colon: "value://still text",
bracket: "value]//still text",
parenthesis: "value)//still text",
brace: "value}//still text"
};
const templateEscapedBacktick =
`text \` https://example.com // still template text`;
const templateEscapedInterpolation =
`text \${notInterpolation} // still template text`;
const urlObject =
new URL("https://example.com/path");
const protocolRelativeUrlObject =
new URL("//cdn.example.com/path", "https://example.com");
const regexUrlPath =
/^https?:\/\/example\.com\/assets\/.+$/;
const regexProtocolAndQuery =
/\/\/cdn\.example\.com\/file\.js\?mode=test/;
class ProtectedStringClass {
url = "https://example.com/path";
cdn = "//cdn.example.com/file.js";
text = "value,//not a comment";
block = "/* not a comment */";
}
async function protectedAsyncValues() {
const responseUrl =
"https://example.com/api//v1";
return Promise.resolve(
"value,//not a comment"
);
}
const standardTrailing = 10;
const standardTrailingString =
"https://example.com";
const standardTrailingText =
"abc//def";
const noWhitespaceTrailing =
20;
const noWhitespaceString =
"https://example.com";
const noWhitespaceText =
"abc//def";
const defectConfig = {
growFactor: 0.00015,
armSeparation: Math.PI,
};
const numberLiteral =
123;
const decimalLiteral =
0.00015;
const booleanLiteral =
true;
const falseLiteral =
false;
const nullLiteral =
null;
const bigintLiteral =
123n;
const protectedUrlThenComment =
"https://example.com/path";
const protectedProtocolThenComment =
"//cdn.example.com/file.js";
const protectedCommaTextThenComment =
"value,//not a comment";
const protectedBlockTextThenComment =
"/* not a comment */";
const protectedEscapedTextThenComment =
"He said \"look // here\"";
const templateThenComment =
`https://example.com/${resourceIdentifier}`;
const templateTextThenComment =
`value,//not a comment`;
const templateBlockThenComment =
`value/*still text*/value`;
const nestedTemplateThenComment =
`https://example.com/${`user//${resourceIdentifier}`}`;
const html = `
<div class="card">
<!-- CARD CONTENT -->
<p>Example content</p>
<!-- Read More still works -->
</div>
`;
const regexThenComment =
/https?:\/\/example\.com/;
const regexProtocolThenComment =
/\/\/cdn\.example\.com/;
const regexBlockThenComment =
/\/\*not-a-comment\*\//;
const regexFlagsThenComment =
/https?:\/\/example\.com/gi;
const arrayThenComment =
[1, 2, 3];
const objectThenComment =
{ enabled: true };
const protectedArrayThenComment =
["https://example.com", "//cdn.example.com"];
const protectedObjectThenComment = {
url: "https://example.com",
text: "value,//not a comment"
};
const inlineObjectComments = {
one: 1,
two: 2,
url: "https://example.com",
text: "value,//not a comment",
decimal: 0.00015,
member: Math.PI,
};
const parenthesised =
(10 + 20);
const arithmetic =
(10 + 20) * 2;
const comparison =
10 === 10;
const logical =
true && false;
const ternary =
true ? "yes" : "no";
const nullish =
undefined ?? "default";
const optional =
objectWithProtectedValues?.url;
const functionCall =
consumeValue("abc");
const urlFunctionCall =
consumeValue("https://example.com/path");
const methodCall =
"abc".toUpperCase();
const memberExpression =
Math.PI;
let counter = 0;
counter++;
counter--;
counter += 10;
counter *= 2;
if (counter > 0) {
counter++;
}
for (let i = 0; i < 3; i++) {
counter += i;
}
while (counter < 100) {
counter++;
}
do {
counter++;
} while (counter < 101);
switch (counter) {
case 101:
break;
default:
break;
}
try {
consumeValue("https://example.com");
} catch (error) {
consumeValue(error?.message);
} finally {
counter = 0;
}
function commentFixtureFunction() {
return "https://example.com";
}
class CommentFixtureClass {
method() {
return "value,//not a comment";
}
}
const blockInlineOne =
10;
const blockInlineTwo =
20;
const blockUrlThenComment =
"https://example.com";
const blockTextThenComment =
"value/*still text*/value";
const betweenTokensOne =
10 + 20;
const betweenTokensTwo =
Math.PI * 2;
const betweenArguments =
consumeValue("https://example.com");
const blockArray = [
1,
2,
3
];
const blockObject = {
one: 1,
two: 2 ,
three: "https://example.com"
};
const multipleBlockComments =
10+20;
const emptyBlockComment =
10;
const minimalBlockComment =
20;
if (counter >= 0) {
counter++;
}
for (let i = 0; i < 1; i++) {
counter += i;
}
const multilineExpression =
(
10 +
20
);
const multilineFunctionCall =
consumeValue(
"https://example.com"
);
consumeValue("abc");
[1, 2, 3]
.forEach(value => consumeValue(value));
({ enabled: true });
const arrowOne =
value => value * 2;
const arrowTwo =
(value) => {
return value * 2;
};
const { url, text } =
objectWithProtectedValues;
const [first, second] =
arrayWithProtectedValues;
const spreadArray =
[...arrayWithProtectedValues];
const spreadObject =
{ ...objectWithProtectedValues };
function restExample(...values) {
return values;
}
const mapThenComment =
new Map([["url", "https://example.com"]]);
const setThenComment =
new Set(["//cdn.example.com"]);
const defaultObject = {
value: undefined ?? "https://example.com"
};
const {
url: destructuredWithComment =
"https://example.com"
} = {};
const finalFixtureValue =
"https://example.com";
async function asyncRemovalFixture() {
const value =
await Promise.resolve("https://example.com");
return value;
}
Promise.resolve("https://example.com")
.then(value => value)
.catch(error => error?.message);
const optionalCallResult =
consumeValue?.("https://example.com");
const optionalIndexResult =
objectWithProtectedValues?.["url"];
const computedPropertyComment = {
["https://example.com"]:
"value",
["value,//not a comment"]:
true
};
const accessorFixture = {
get value() {
return "https://example.com";
},
set value(input) {
consumeValue(input);
}
};
function* generatorFixture() {
yield "https://example.com";
yield* ["//cdn.example.com"];
}
function throwFixture() {
if (counter < 0) {
throw new Error("https://example.com");
}
}
const newExpression =
new URL("https://example.com");
class StaticCommentFixture {
static url =
"https://example.com";
static method() {
return "//cdn.example.com";
}
}
const templateExpressionComment =
`${consumeValue(
"https://example.com"
)}`;
const nestedTemplateExpressionComment =
`${`value://${consumeValue(
"abc"
)}`}`;
const regexpArgumentComment =
new RegExp(
"https?:\\/\\/example\\.com"
);
let logicalAssignmentValue = null;
logicalAssignmentValue ??=
"https://example.com";
logicalAssignmentValue ||=
"//cdn.example.com";
logicalAssignmentValue &&=
"value,//not a comment";