Predefined Functions Flashcards
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: 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()!.
“eval() - JavaScript | MDN” (developer.mozilla.org). Retrieved September 25, 2023.
What are the problems of using eval()
?
Using direct eval()
suffers from multiple problems:
-
Security risk -
eval()
executes the code it’s passed with the privileges of the caller. If you runeval()
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 througheval()
, 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 otherwiseeval()
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. If0
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
- 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.
“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
- value - The value to be tested.
“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('')
, andNumber()
return0
. -
parseInt(null)
,parseInt('')
andparseInt()
returnNaN.
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')
returns10
. -
Number(string)
will returnNaN
if the string contains any non-numeric characters. For example,Number('10px')
returnsNaN
.
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 returnsNaN
. For example,Number("abc")
returnsNaN
. -
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")
returnsNaN
, butparseInt("123abc")
returns123
.
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
- value - The value to be tested.
“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'); // 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
.
“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()
vsNumber.parseInt()
and -
parseFloat()
vsNumber.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
- 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
-
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
- 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
-
URIError
- Thrown if uriComponent contains a lone surrogate.
“encodeURIComponent() - JavaScript | MDN” (developer.mozilla.org). Retrieved October 9, 2023.