2

if (typeof (location.x != null) {

Using the above I run into the follow error: Uncaught TypeError: Cannot read property 'x' of null

I have tried console.log(location.x) which results in an example with null

10
  • May I ask where do you run this code? Commented Sep 24, 2014 at 14:13
  • 3
    using location tends to be a bad variable name because of window.location. One miss var and your "truthy" check will be true. Commented Sep 24, 2014 at 14:15
  • @epascarello—then why is it null? BTW, typeof always returns a string which is never == null. Commented Sep 24, 2014 at 14:16
  • @RobG: window.location and the local variable location, in this context, are different. Your confusion is precisely the reason for epascarello's comment. Commented Sep 24, 2014 at 14:18
  • 1
    @epascarello is 100% correct about the variable name being unwise, RobG makes a very important point (for the OP) about typeof returning a string. Commented Sep 24, 2014 at 17:03

3 Answers 3

8
if (location && location.x) {

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

3 Comments

hopefully x is not a falsey value.
in this case you use location.x!=undefined for condition in if statement
typeof myVariable !== 'undefined is safer IMO -- no terrorist jQuery plugin can redefine undefined on you if you use typeof.
2

You can just do:

if (location && location.x) {

}

2 Comments

Still results with Uncaught TypeError: Cannot read property 'x' of null
hopefully x is not a falsey value.
1

The x attribute can't be reached because your location variable is null

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.