TheAlgorithms/JavaScript · error · TypeError
Arguments type are invalid
Error message
Arguments type are invalid
What it means
XORCipher rejects the call when str is not a string OR key is not an integer. It XORs each character's charCodeAt with the key bitwise, which only makes sense for a string input and a whole-number key; a float key or non-string str would yield undefined/garbled output.
Source
Thrown at Ciphers/XORCipher.js:14
/**
* @function XORCipher
* @description - Encrypt using an XOR cipher
* The XOR cipher is a type of additive cipher.
* Each character is bitwise XORed with the key.
* We loop through the input string, XORing each
* character with the key.
* @param {string} str - string to be encrypted
* @param {number} key - key for encryption
* @return {string} encrypted string
*/
const XORCipher = (str, key) => {
if (typeof str !== 'string' || !Number.isInteger(key)) {
throw new TypeError('Arguments type are invalid')
}
return str.replace(/./g, (char) =>
String.fromCharCode(char.charCodeAt() ^ key)
)
}
export default XORCipher
View on GitHub (pinned to 5c39e87a9a)
Solutions
- Pass a string and an integer key: XORCipher('msg', 42).
- Parse the key: Math.trunc(Number(rawKey)).
- Decode str buffers to utf8 first.
Example fix
// before
XORCipher(buffer, process.env.XOR_KEY) // Buffer + string
// after
XORCipher(buffer.toString('utf8'), Math.trunc(Number(process.env.XOR_KEY))) Defensive patterns
Strategy: validation
Validate before calling
function xorSafe(text, rawKey) {
const key = Math.trunc(Number(rawKey));
return XORCipher(String(text), key);
} Type guard
/** @param {unknown} s @param {unknown} k @returns {boolean} */
const validXorArgs = (s, k) => typeof s === 'string' && Number.isInteger(k); Try / catch
try { return XORCipher(text, key); }
catch (e) {
if (e instanceof TypeError && /Arguments type are invalid/.test(e.message)) {
return XORCipher(String(text), Math.trunc(Number(key)));
}
throw e;
} Prevention
- Parse the key with Math.trunc(Number(...)) at the boundary.
- Decode str Buffers to utf8 before ciphering.
- Validate str is a string and key is an integer separately for clarity.
When it happens
Trigger: str is a number/object/Buffer, or key is a float (e.g. 3.5), a string ("7"), NaN, undefined, or any non-integer.
Common situations: Key read from a config/env as a string, str passed as a Buffer from file/crypto input, or a computed key that ended up fractional.
Related errors
- Argument not an Integer
- Rule must be an integer between the values 0 and 255 (got ${
- Coefficient a, b should be number
- Argument str should be String
- Argument should be string
AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13).
Data as JSON: /api/errors/6df46bb38b50777f.
Report an issue: GitHub.