0

I have looked up the solution for the palindrome question in Javascript.

There is a line of code that I dont really understand and I hope someone can enlighten me.

Here is the solution:

this.palindrom = function() {
            //two pointers to find the middle 
            // 1 slow pointer - move 1 at a time
            // 1 fast pointer - move 2 at a time 

        let slow = this.head
        let fast = this.head
        let start = this.head
        console.log('fast', fast)
        let length = 0 
       
        while( fast && fast.next) {
            fast = fast.next.next
            slow = slow.next 
            start = start.next
            length++
        }
        console.log(slow)
       let mid = this.reverse(slow)
        console.log('mid',mid)
        while (length !== 0) {
            length --
            if (mid.data !== start.data) return false 
            else return true 
        }

      }
    }

I do not understand why the parameters of the "while" loop is

while( fast && fast.next)

i typed while(fast.next) and there was an error saying cannot access null of next. I am wondering why fast && fast.next works instead.

2
  • because fast might be null and in that case the expression fast.next would throw a null reference exception. Instead using fast && fast.next, fast.next gets evaluated partecipating to the AND condition only if fast is not null. Commented May 5, 2022 at 10:00
  • Does this answer your question? Testing for null object using short-circuit logical operator Commented May 5, 2022 at 13:12

1 Answer 1

0

fast && fast.next is applying a safeguard to fast being null. If fast is null, then it would be an error to evaluate fast.next -- which is what you experienced when you "simplified" the condition.

If fast is null then the expression fast will be "falsy", and because of how the && operator works (short-circuiting), the evaluation will then stop and not attempt to evaluate fast.next. Instead it will consider the whole expression to be falsy, and exit the loop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.