Home > Net >  Why is this code returning a runtime error in line 8
Why is this code returning a runtime error in line 8

Time:10-07

/**
 * @param {number[]} nums
 * @return {boolean}
 */
var containsDuplicate = function(nums) {
    let base = nums.length;
    let diff = [...new Set(nums)].length;
    if base !== diff return true // <--- this line
    else {
        return false
    }
};

the console is saying there is an error with base in the 8th line. This is Leetcode question #217.

I've tried the following:

changing spelling from length and legnth
tried changing variablenames
tried switching return true and false
and changing the equation to !== instead of ====

CodePudding user response:

Found the answer

I forgot to put () after the if on line 8. Thanks to @tadman.

/**
 * @param {number[]} nums
 * @return {boolean}
 */
var containsDuplicate = function(nums) {
    let base = nums.length;
    let diff = [...new Set(nums)].length;
    if (base !== diff) return true
    else {
        return false
    }
};

CodePudding user response:

Ok here is the syntax of if-else condition:

 if(some condition){
   do that;
 }else{
   do that;
}

in your case it should look like that: if (base !== diff) return true else { return false } and make sure when you use !== you checks also data type I hope that was helpful

  • Related