eval() function
The eval() function evaluates JavaScript code represented as a string and returns its completion value. The source is parsed as a script.
console.log(eval('2 + 2'));
// Expected output: 4WARNING: Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use eval(). See Never use eval()!.
“eval() - JavaScript | MDN” (developer.mozilla.org). Retrieved September 25, 2023.
What are the problems of using eval()?
Using direct eval() suffers from multiple problems:
eval() executes the code it’s passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user’s machine with the permissions of your webpage / extension.eval() will force the browser to do long expensive variable name lookups to figure out where the variable exists in the machine code and set its value. Additionally, new things can be introduced to that variable through eval(), such as changing the type of that variable, forcing the browser to re-evaluate all of the generated machine code to compensate.eval(), because otherwise eval() cannot read the correct variable at runtime.“Never use eval()!” (developer.mozilla.org). Retrieved September 25, 2023.
Function() constructor
The Function() constructor: it evaluates the JavaScript source passed to it in the global scope without reading or mutating any local bindings, and therefore allows engines to do more optimizations than direct eval().
The difference between eval() and Function() is that the source string passed to Function() is parsed as a function body, not as a script. There are a few nuances — for example, you can use return statements at the top level of a function body, but not in a script.
“Function - JavaScript | MDN” (developer.mozilla.org). Retrieved September 25, 2023.
Is it safe to use Function() instead of eval()
No. Both eval() and Function() implicitly evaluate arbitrary code, and are forbidden in strict CSP settings.
“Never use eval()!” (developer.mozilla.org). Retrieved September 25, 2023.
parseInt() function
The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
Syntax
parseInt(string) parseInt(string, radix)
Values
string - A string starting with an integer. Leading whitespace in this argument is ignored.radix Optional - An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string. It is converted to a 32-bit integer; if it’s nonzero and outside the range of [2, 36] after conversion, the function will always return NaN. If 0 or not provided, the radix will be inferred based on string’s value. Be careful — this does not always default to 10.Return value
An integer parsed from the given string, or NaN when
The radix as a 32-bit integer is smaller than 2 or bigger than 36, or
The first non-whitespace character cannot be converted to a number.
“parseInt() - JavaScript | MDN” (developer.mozilla.org). Retrieved September 29, 2023.
parseFloat() function
The parseFloat() function parses a string argument and returns a floating point number.
Syntax
parseFloat(string)
Parameters
string - The value to parse, coerced to a string. Leading whitespace in this argument is ignored.Return value
A floating point number parsed from the given string, or NaN when the first non-whitespace character cannot be converted to a number.
“parseFloat() - JavaScript | MDN” (developer.mozilla.org). Retrieved September 29, 2023.
Number constructor
The Number() constructor creates Number objects. When called as a function, it returns primitive values of type number.
Note: Number() can be called with or without new, but with different effects.
Parameters
Return value
When Number is called as a constructor (with new), it creates a Number object, which is not a primitive.
When Number is called as a function, it coerces the parameter to a number primitive. BigInts are converted to numbers. If the value can’t be converted, it returns NaN.
Warning: You should rarely find yourself using Number as a constructor.
“Number() constructor - JavaScript | MDN” (developer.mozilla.org). Retrieved September 29, 2023.
isFinite() function
The isFinite() function determines whether a value is finite, first converting the value to a number if necessary. A finite number is one that’s not NaN or ±Infinity. Because coercion inside the isFinite() function can be surprising, you may prefer to use Number.isFinite().
Syntax
isFinite(value)
Parameters
“isFinite() - JavaScript | MDN” (developer.mozilla.org). Retrieved October 2, 2023.
Differences between parseInt() and Number()?
Let’s summarize the key points:
Semantic Differences:
Number(): Performs type conversion. It converts the input to a number, handling different notations like exponential notation.parseInt(): Performs parsing. It extracts an integer from the beginning of a string, based on the specified radix (number base).Handling Different Bases:
Number(): Doesn’t handle implicit octals but can detect explicit octal notation like "0o10".parseInt(): Can handle both implicit octals (e.g., “010”) and explicit octal notation (e.g., “0o10”).Handling Hexadecimal Notation:
Both Number and parseInt can handle numbers in hexadecimal notation (e.g., "0xF").
Conversion of Undefined or Null:
Number(null), Number(''), and Number() return 0.parseInt(null), parseInt('') and parseInt() return NaN.Handling Non-Numeric Characters:
parseInt(string) will convert a string containing non-numeric characters to a number, as long as the string begins with numeric characters. For example, parseInt('10px') returns 10.Number(string) will return NaN if the string contains any non-numeric characters. For example, Number('10px') returns NaN.Floating-Point Numbers:
Both Number and parseInt can handle floating-point numbers as well. For instance, Number("3.14") and parseInt("3.14") will both convert the string to the floating-point number 3.14. However, parseInt will only return the integer part when parsing.
NaN Handling:
Number(): When passed a value that cannot be converted to a number, it returns NaN. For example, Number("abc") returns NaN.parseInt(): If the parsing encounters a character that can’t be part of the specified number base, it stops parsing and returns the integer value parsed up to that point. For example, parseInt("abc") returns NaN, but parseInt("123abc") returns 123.Type Coercion:
The behavior of parseInt can be affected by JavaScript’s type coercion rules. For example, parseInt(true) will return NaN because true is coerced to the string "true". While Number(true) will return 1
Edge Cases:
JavaScript’s parsing can have some edge cases and quirks, such as parseInt("0x") returning 0 and parseInt("0x123", 8) returning 0 because the parsing is interrupted. While Number('0x123') returns 291.
Important
It’s important to note that parseInt and Number serve different purposes, and choosing one over the other depends on your specific use case. If you need to extract an integer from the beginning of a string, parseInt is more suitable. If you want to convert a value to a number, Number is the appropriate choice. Additionally, specifying the radix when using parseInt is important to avoid unexpected results, especially when dealing with numbers in different bases.
“What is the difference between parseInt(string) and Number(string) in JavaScript?” (Stack Overflow). Retrieved October 2, 2023.
isNaN() function
The isNaN() function determines whether a value is NaN, first converting the value to a number if necessary. Because coercion inside the isNaN() function can be surprising, you may prefer to use Number.isNaN().
Syntax
isNaN(value)
Parameters
“isNaN() - JavaScript | MDN” (developer.mozilla.org). Retrieved October 9, 2023.
Difference between isFinite and Number.isFinite()
Number.isFinite() doesn’t first convert the parameter to a number. This means only values of the type number and are finite return true, and non-numbers always return false.
isFinite("0"); // true; coerced to number 0
Number.isFinite("0"); // false
isFinite(null); // true; coerced to number 0
Number.isFinite(null); // false
isFinite('23px'); // false
Number.isFinite('23px'); // falseNote: When the argument to the isFinite() function is not of type Number, the value is first coerced to a number, and the resulting value is then compared against isFinite. For non-numeric arguments can be confusing! For example, an empty string is coerced to 0, while a boolean is coerced to 0 or 1; If the argument contains letters it gets coerced to NaN.
“Difference between Number.isFinite() and global isFinite()” (developer.mozilla.org). Retrieved October 9, 2023.
Difference between isNaN and Number.isNaN()
Number.isNaN() doesn’t attempt to convert the parameter to a number, so non-numbers always return false. The following are all false:
Number.isNaN("NaN");
Number.isNaN(undefined);
Number.isNaN({});
Number.isNaN("blabla");
Number.isNaN(true);
Number.isNaN(null);
Number.isNaN("37");
Number.isNaN("37.37");
Number.isNaN("");
Number.isNaN(" ");The global isNaN() coerces its parameter to a number:
isNaN("NaN"); // true
isNaN(undefined); // true
isNaN({}); // true
isNaN("blabla"); // true
isNaN(true); // false, this is coerced to 1
isNaN(null); // false, this is coerced to 0
isNaN("37"); // false, this is coerced to 37
isNaN("37.37"); // false, this is coerced to 37.37
isNaN(""); // false, this is coerced to 0
isNaN(" "); // false, this is coerced to 0“Difference between Number.isNaN() and global isNaN()” (developer.mozilla.org). Retrieved October 9, 2023.
Differences between:
parseInt() vs Number.parseInt() andparseFloat() vs Number.parseFloat()None. Number methods have the same functionality as the globals parseInt() and parseFloat() functions.
Its purpose is modularization of globals.
Number.parseInt === parseInt; // true Number.parseFloat === parseFloat; // true
“Number.parseFloat vs. parseFloat” (developer.mozilla.org). Retrieved October 9, 2023.
encodeURI() function
encodeURI() function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character. Compared to encodeURIComponent(), this function encodes fewer characters, preserving those that are part of the URI syntax.
It escapes all characters except:
A–Z a–z 0–9 - _ . ! ~ * ' ( ) ; / ? : @ & = + $ , #
Syntax
encodeURI(uri)
Parameters
string to be encoded as a URI (a path, query string, fragment, etc.). Other values are converted to strings.Return value
A new string representing the provided uri encoded as a URI.
Exceptions
URIError - Thrown if uri contains a lone surrogate.“encodeURI() - JavaScript | MDN” (developer.mozilla.org). Retrieved October 10, 2023.
encodeURIComponent() function
encodeURIComponent() function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character. Compared to encodeURI(), this function encodes more characters, including those that are part of the URI syntax.
It escapes all characters except:
A–Z a–z 0–9 - _ . ! ~ * ' ( )
Syntax
encodeURIComponent(uriComponent)
Parameters
string to be encoded as a URI component (a path, query string, fragment, etc.). Other values are converted to strings.Return value
A new string representing the provided uriComponent encoded as a URI component.
Exceptions
URIError - Thrown if uriComponent contains a lone surrogate.“encodeURIComponent() - JavaScript | MDN” (developer.mozilla.org). Retrieved October 9, 2023.
encodeURI() vs. encodeURIComponent()
encodeURI() differs from encodeURIComponent() as follows:
const set1 = ";/?:@&=+$,#"; // Reserved Characters const set2 = "-.!~*'()"; // Unreserved Marks const set3 = "ABC abc 123"; // Alphanumeric Characters + Space console.log(encodeURI(set1)); // ;/?:@&=+$,# console.log(encodeURI(set2)); // -.!~*'() console.log(encodeURI(set3)); // ABC%20abc%20123 (the space gets encoded as %20) console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24%23 console.log(encodeURIComponent(set2)); // -.!~*'() console.log(encodeURIComponent(set3)); // ABC%20abc%20123 (the space gets encoded as %20)
“encodeURI() vs. encodeURIComponent()” (developer.mozilla.org). Retrieved October 10, 2023.
When to use encodeURI() and when to use encodeURIComponent()?
If you’re encoding a string to put in a URL component (a query string parameter), you should use encodeURIComponent, and if you’re encoding an existing URL, use encodeURI.
Let’s see a few examples:
encodeURI a URL (OK)encodeURI("https://www.example.com/my file has special & 8=-/*characters.html")
// Output: https://www.example.com/my%20file%20has%20special%20&%208=-/*characters.htmlencodeURIComponent a query parameter (OK)let param = encodeURIComponent('special */- parameter')
let url = "https://example.com/?foo=" + param + "&bar=xyz";
//Output: https://example.com/?foo=special%20*%2F-%20parameter&bar=xyzencodeURIComponent entire URL (WRONG!)encodeURIComponent('https://www.example.com/my file has special & 8=-/*characters.html')
// Ouput: 'https%3A%2F%2Fwww.example.com%2Fmy%20file%20has%20special%20%26%208%3D-%2F*characters.html'“When to use encodeURI() and encodeURIComponent()? | phpGrid - PHP Datagrid” (phpGrid - PHP Datagrid). Retrieved October 10, 2023.
What is a URI and how is it different from a URL?
In short,
URI identifies, URL identifies and locateURL is a subset of URIClear as mud? Let’s put semantic out of the way.
The URI is anything that uniquely identifies a resource, such as a name, or an ISBN number. A URL identifies a resource and describes how to access it (the protocol). Although all URLs are URIs, not all URIs are also URLs.
“When to use encodeURI() and encodeURIComponent()? | phpGrid - PHP Datagrid” (phpGrid - PHP Datagrid). Retrieved October 10, 2023.
Why do we need to encode URLs
This is because only characters from the standard 128-character ASCII set are allowed in URLs. Many special characters, such as spaces and slashes, are not permitted.
For example, characters such as ~!@#$&*()=:/,;?+’ are special characters need to be encoded in URL.
“When to use encodeURI() and encodeURIComponent()? | phpGrid - PHP Datagrid” (phpGrid - PHP Datagrid). Retrieved October 10, 2023.
decodeURI() function
The decodeURI() function decodes a Uniform Resource Identifier (URI) previously created by encodeURI() or a similar routine.
The decodeURI() function decodes the URI by treating each escape sequence in the form %XX as one UTF-8 code unit (one byte). If decodeURI() fails to find the expected number of sequences, or if the escape sequences don’t encode a valid UTF-8 character, a URIError is thrown.
Syntax
decodeURI(encodedURI)
Parameters
encodedURI - A complete, encoded Uniform Resource Identifier.Return value
Exceptions
URIError - Thrown if encodedURI contains a % not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character.“decodeURI() - JavaScript | MDN” (developer.mozilla.org). Retrieved October 10, 2023.
decodeURIComponent() function
The decodeURIComponent() function decodes a Uniform Resource Identifier (URI) component previously created by encodeURIComponent() or by a similar routine.
decodeURIComponent() uses the same decoding algorithm as described in decodeURI(). It decodes all escape sequences, including those that are not created by encodeURIComponent, like -.!~*'().
Syntax
decodeURIComponent(encodedURI)
Parameters
encodedURI - An encoded component of a Uniform Resource Identifier.Return value
Exceptions
URIError - Thrown if encodedURI contains a % not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character.“decodeURIComponent() - JavaScript | MDN” (developer.mozilla.org). Retrieved October 11, 2023.
structuredClone() function
The global structuredClone() method creates a deep clone of a given value using the structured clone algorithm.
The method also allows transferable objects in the original value to be transferred rather than cloned to the new object. Transferred objects are detached from the original object and attached to the new object; they are no longer accessible in the original object.
Syntax
structuredClone(value) structuredClone(value, options)
Parameters
value - The object to be cloned. This can be any structured-cloneable type.
options Optional - An object with the following properties:
Return value
The returned value is a deep copy of the original value.
ExceptionsDataCloneError DOMException - Thrown if any part of the input value is not serializable.
Example - Cloning an object
In this example, we clone an object with one member, which is an array. After cloning, changes to each object do not affect the other object.
const mushrooms1 = {
amanita: ["muscaria", "virosa"],
};
const mushrooms2 = structuredClone(mushrooms1);
mushrooms2.amanita.push("pantherina");
mushrooms1.amanita.pop();
console.log(mushrooms2.amanita); // ["muscaria", "virosa", "pantherina"]
console.log(mushrooms1.amanita); // ["muscaria"]Example - Transfering an object
In this example we create an ArrayBuffer and then clone the object it is a member of, transferring the buffer. We can use the buffer in the cloned object, but if we try to use the original buffer we will get an exception.
// Create an ArrayBuffer with a size in bytes
const buffer1 = new ArrayBuffer(16);
const object1 = {
buffer: buffer1,
};
// Clone the object containing the buffer, and transfer it
const object2 = structuredClone(object1, { transfer: [buffer1] });
// Create an array from the cloned buffer
const int32View2 = new Int32Array(object2.buffer);
int32View2[0] = 42;
console.log(int32View2[0]);
// Creating an array from the original buffer throws a TypeError
const int32View1 = new Int32Array(object1.buffer);“structuredClone() global function - Web APIs | MDN” (developer.mozilla.org). Retrieved October 11, 2023.
setTimeout function
The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.
Syntax
setTimeout(code) setTimeout(code, delay) setTimeout(functionRef) setTimeout(functionRef, delay) setTimeout(functionRef, delay, param1) setTimeout(functionRef, delay, param1, param2) setTimeout(functionRef, delay, param1, param2, /* …, */ paramN)
Parameters
0 is used, meaning execute “immediately”, or more accurately, the next event cycle.Note that in either case, the actual delay may be longer than intended; see Reasons for delays longer than specified below.
Also note that if the value isn’t a number, implicit type coercion is silently done on the value to convert it to a number — which can lead to unexpected and surprising results.
Return value
The returned timeoutID is a positive integer value which identifies the timer created by the call to setTimeout(). This value can be passed to clearTimeout() to cancel the timeout.
It is guaranteed that a timeoutID value will never be reused by a subsequent call to setTimeout() or setInterval() on the same object (a window or a worker). However, different objects use separate pools of IDs.
“setTimeout() global function - Web APIs | MDN” (developer.mozilla.org). Retrieved October 20, 2023.
clearTimeout function
The global clearTimeout() method cancels a timeout previously established by calling setTimeout().
If the parameter provided does not identify a previously established action, this method does nothing.
Syntax
clearTimeout(timeoutID)
Parameters
It’s worth noting that the pool of IDs used by setTimeout() and setInterval() are shared, which means you can technically use clearTimeout() and clearInterval() interchangeably. However, for clarity, you should avoid doing so.
Return value
undefined).“clearTimeout() global function - Web APIs | MDN” (developer.mozilla.org). Retrieved October 20, 2023.