{"record":{"id":"45595037aa2041b6","repo":"trekhleb/javascript-algorithms","slug":"either-dataset-or-labels-or-toclassify-were-not-se","errorCode":null,"errorMessage":"Either dataSet or labels or toClassify were not set","messagePattern":"Either dataSet or labels or toClassify were not set","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"src/algorithms/ml/knn/kNN.js","lineNumber":20,"sourceCode":" * Classifies the point in space based on k-nearest neighbors algorithm.\n *\n * @param {number[][]} dataSet - array of data points, i.e. [[0, 1], [3, 4], [5, 7]]\n * @param {number[]} labels - array of classes (labels), i.e. [1, 1, 2]\n * @param {number[]} toClassify - the point in space that needs to be classified, i.e. [5, 4]\n * @param {number} k - number of nearest neighbors which will be taken into account (preferably odd)\n * @return {number} - the class of the point\n */\n\nimport euclideanDistance from '../../math/euclidean-distance/euclideanDistance';\n\nexport default function kNN(\n  dataSet,\n  labels,\n  toClassify,\n  k = 3,\n) {\n  if (!dataSet || !labels || !toClassify) {\n    throw new Error('Either dataSet or labels or toClassify were not set');\n  }\n\n  // Calculate distance from toClassify to each point for all dimensions in dataSet.\n  // Store distance and point's label into distances list.\n  const distances = [];\n  for (let i = 0; i < dataSet.length; i += 1) {\n    distances.push({\n      dist: euclideanDistance([dataSet[i]], [toClassify]),\n      label: labels[i],\n    });\n  }\n\n  // Sort distances list (from closer point to further ones).\n  // Take initial k values, count with class index\n  const kNearest = distances.sort((a, b) => {\n    if (a.dist === b.dist) {\n      return 0;\n    }","sourceCodeStart":2,"sourceCodeEnd":38,"githubUrl":"https://github.com/trekhleb/javascript-algorithms/blob/85293e3e2b88f4d2ce330d956b139cf628aa1e82/src/algorithms/ml/knn/kNN.js#L2-L38","documentation":"kNN(dataSet, labels, toClassify, k) requires all three leading arguments to be truthy; if dataSet, labels or toClassify is null/undefined the function refuses to run. The three inputs are the training points, their per-point class labels, and the query point to classify. Truthiness means empty arrays pass this check and fail later, so this message specifically means one argument was not supplied at all.","triggerScenarios":"kNN(dataSet, labels) with toClassify forgotten; labels undefined because a parse or zip step failed; toClassify null when classifying optional records; destructuring a response with renamed keys producing undefined.","commonSituations":"Refactors that reorder or rename parameters, API responses with missing fields, CSV rows whose label column is absent, and optional classification requests where the query point is genuinely absent.","solutions":["Log all three arguments before the call to see which is falsy","Supply the missing argument - most often toClassify (the query point, e.g. [5, 4]) or a labels array aligned 1:1 with dataSet","Also guard the cases this check misses: dataSet.length === labels.length and toClassify.length === dataSet[0].length"],"exampleFix":"// before\nimport kNN from './src/algorithms/ml/knn/kNN';\nconst label = kNN(dataSet, labels);\n// toClassify missing -> throws\n\n// after\nconst label = kNN(dataSet, labels, [5, 4], 3);","handlingStrategy":"validation","validationCode":"if (!Array.isArray(dataSet) || !Array.isArray(labels) || !Array.isArray(toClassify)) {\n  throw new TypeError('kNN: dataSet, labels and toClassify must all be arrays');\n}\nif (dataSet.length === 0 || dataSet.length !== labels.length) {\n  throw new TypeError('kNN: dataSet and labels must be non-empty and aligned');\n}\nkNN(dataSet, labels, toClassify, k);","typeGuard":"const isKnnInput = (ds, ls, q) =>\n  Array.isArray(ds) && Array.isArray(ls) && Array.isArray(q)\n  && ds.length > 0 && ds.length === ls.length\n  && q.length === ds[0].length;","tryCatchPattern":"try {\n  cls = kNN(dataSet, labels, query, k);\n} catch (e) {\n  if (e.message === 'Either dataSet or labels or toClassify were not set') {\n    cls = null; // skip classification for this record\n  } else {\n    throw e;\n  }\n}","preventionTips":["Validate dataSet.length === labels.length once when training data is built","Unit-test the missing-middle-argument case; it is the most common regression","Consider an options object at wrapper level when call sites churn"],"tags":["machine-learning","knn","classification","missing-argument","validation"],"backgroundTag":"missing-required-argument","analyzedSha":"85293e3e2b88f4d2ce330d956b139cf628aa1e82","analyzedAt":"2026-08-24T05:59:10.417Z","schemaVersion":2},"datasetVersion":"2026-08-24T07:17:09.176Z"}