Predefined Functions Flashcards

1
Q

eval() function

A

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: 4

WARNING: 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()!.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the problems of using eval()?

A

Using direct eval() suffers from multiple problems:

  • Security risk - 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.
  • Performance implications - Modern JavaScript interpreters convert JavaScript to machine code. This means that any concept of variable naming gets obliterated. Thus, any use of 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.
  • No minification - Minifiers give up on any minification if the scope is transitively depended on by eval(), because otherwise eval() cannot read the correct variable at runtime.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Function() constructor

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Is it safe to use Function() instead of eval()

A

No. Both eval() and Function() implicitly evaluate arbitrary code, and are forbidden in strict CSP settings.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

parseInt() function

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

parseFloat() function

A

The parseFloat() function parses a string argument and returns a floating point number.

Syntax

parseFloat(string)

Parameters

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Number constructor

A

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

  • value - The numeric value of the object being created.

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

isFinite() function

A

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

  • value - The value to be tested.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Differences between parseInt() and Number()?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

isNaN() function

A

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

  • value - The value to be tested.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Difference between isFinite and Number.isFinite()

A

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'); // false

Note: 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Difference between isNaN and Number.isNaN()

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Differences between:

  • parseInt() vs Number.parseInt() and
  • parseFloat() vs Number.parseFloat()
A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

encodeURI() function

A

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

  • A 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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

encodeURIComponent() function

A

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

  • A 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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

encodeURI() vs. encodeURIComponent()

A

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)
17
Q

When to use encodeURI() and when to use encodeURIComponent()?

A

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.html
  • encodeURIComponent 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=xyz
  • encodeURIComponent 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'
18
Q

What is a URI and how is it different from a URL?

A

In short,

  • URI identifies, URL identifies and locate
  • URL is a subset of URI

Clear 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.

19
Q

Why do we need to encode URLs

A

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.

20
Q

decodeURI() function

A

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

  • A new string representing the unencoded version of the given encoded Uniform Resource Identifier (URI).

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.
21
Q

decodeURIComponent() function

A

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

  • A new string representing the decoded version of the given encoded Uniform Resource Identifier (URI) component.

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.
22
Q

structuredClone() function

A

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:

  • transfer- An array of transferable objects that will be moved rather than cloned to the returned object.

Return value
The returned value is a deep copy of the original value.

Exceptions
DataCloneError 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);
23
Q

setTimeout function

A

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

  • functionRef - A function to be executed after the timer expires.
  • delay Optional - The time, in milliseconds that the timer should wait before the specified function or code is executed. If this parameter is omitted, a value of 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.

  • param1, …, paramN Optional - Additional arguments which are passed through to the function specified by functionRef.

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.

24
Q

clearTimeout function

A

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

  • timeoutID - The identifier of the timeout you want to cancel. This ID was returned by the corresponding call to setTimeout().

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

  • None (undefined).
25
Q

setInerval function

A

The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.

This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().

Syntax

setInterval(code)
setInterval(code, delay)

setInterval(func)
setInterval(func, delay)
setInterval(func, delay, arg1)
setInterval(func, delay, arg1, arg2)
setInterval(func, delay, arg1, arg2, /* …, */ argN)

Parameters

  • func - A function to be executed every delay milliseconds. The first execution happens after delay milliseconds.
  • delay Optional - The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. Defaults to 0 if not specified.
  • arg1, …,argN Optional - Additional arguments which are passed through to the function specified by func once the timer expires.

Return value

The returned intervalID is a numeric, non-zero value which identifies the timer created by the call to setInterval(); this value can be passed to clearInterval() to cancel the interval.

Note: The delay argument is converted to a signed 32-bit integer. This effectively limits delay to 2147483647 ms, since it’s specified as a signed integer in the IDL.

26
Q

clearInterval() function

A

The global clearInterval() method cancels a timed, repeating action which was previously established by a call to setInterval(). If the parameter provided does not identify a previously established action, this method does nothing.

Syntax

clearInterval(intervalID)

Parameters

  • intervalID - The identifier of the repeated action you want to cancel. This ID was returned by the corresponding call to setInterval().

It’s worth noting that the pool of IDs used by setInterval() and setTimeout() are shared, which means you can technically use clearInterval() and clearTimeout() interchangeably. However, for clarity, you should avoid doing so.

Return value

  • None (undefined).
27
Q

What are the delay restrictions of setTimeout and setInterval in browsers?

A

It’s possible for intervals to be nested; that is, the callback for setInterval() or setTimeout() can in turn call again setInterval() or setTimeout() to start another interval/timout running, even though the first one is still going. To mitigate the potential impact this can have on performance, once intervals are nested beyond five levels deep, the browser will automatically enforce a 4 ms minimum value for the interval. Attempts to specify a value less than 4 ms in deeply-nested calls to setInterval() or setTimeout() will be pinned to 4 ms.

Browsers may enforce even more stringent minimum values for the interval under some circumstances, although these should not be common. Note also that the actual amount of time that elapses between calls to the callback may be longer than the given delay; see Reasons for delays longer than specified for examples.

28
Q

How can you Avoiding errors in encodeURI()?

A

encodeURI throws an error if the string passed is not well-formed. This can be avoided by using isWellFormed() to test the string before passing it to encodeURI().

Example

const illFormed = "https://example.com/search?q=\uD800";

try {
  encodeURI(illFormed);
} catch (e) {
  console.log(e); // URIError: URI malformed
}

if (illFormed.isWellFormed()) {
  console.log(encodeURI(illFormed));
} else {
  console.warn("Ill-formed strings encountered."); // Ill-formed strings encountered.
}