Take a fresh look at your lifestyle.

How To Prevent Cannot Read Property Split Of Undefined

how To Prevent Cannot Read Property Split Of Undefined
how To Prevent Cannot Read Property Split Of Undefined

How To Prevent Cannot Read Property Split Of Undefined The split() method is a method of the string prototype object, so you can only call the method from a string type variable. the code below shows the right way to use the split() method on a string type value: let username = "nathan sebhastian"; let usernamearr = username.split(" "); console.log(usernamearr); output:. Assign an alternative value. if the variable the split () method is called on resolves to undefined, you can assign an alternative value to it. const samplestring = undefined; const result = samplestring || ‘ ’. return result.split() here, the sample variable is declared at undefined in line one.

how To Prevent Cannot Read Property Split Of Undefined
how To Prevent Cannot Read Property Split Of Undefined

How To Prevent Cannot Read Property Split Of Undefined We explicitly check that the variable doesn't store an undefined value if the variable doesn't store an undefined value, the if block runs, otherwise, the else block runs. # providing a fallback value if the variable stores undefined. 1. str.length is actually the number of letters in the string, while array is an array of words. that's why i can go up to 45, while your array has only 9 elements that's why when it tries to access array[10] it gets undefined and it can't split it. this should help: var array = str.split(" ");. First, split str into an array of individual words: function findlongestwordlength(str) { const array = str.split(" "); } create a variable to keep track of the longest word length and set it to zero: function findlongestwordlength(str) { const array = str.split(" "); let maxwordlength = 0; }. Following are the two ways how javascript engine treats a variable as undefined. when we assign undefined to a variable. let data = undefined; console.log(data.split(','); uncaught typeerror: cannot read properties of undefined (reading 'split') 2. when we declare a variable without assigning any value. let data;.

Comments are closed.