This question already has answers here:
Why does reading a property sometimes throw an error in javascript?
(5 answers)
Closed 1 year ago.
In which specific cases does property access throw an error in JavaScript?
In Node.js, this prints undefined:
x = 3
console.log( x.thing );
This throws an error:
x = null;
console.log( x.thing );
What exactly is the semantics here? Property access is normal behavior for almost all values—even functions—but on undefined and null it throws an error.
I can't for the life of me find confirmation that those are the only cases. Can anybody confirm that?
undefined and null are not references to objects, nor are they primitive values that can be implicitly boxed in object wrappers. Thus, any attempt to reference a property is going to fail.
When you use a number (3), the runtime boxes that as a Number instance, but of course there's no "thing" property so the value is undefined.
Also, functions are first-class objects, so references to properties on functions are not really "weird" in any sense.
Related
This question already has answers here:
Access Javascript nested objects safely
(14 answers)
Closed 6 months ago.
If customer_id doesn't exist in the Shopify JavaScript object, I get the error Uncaught TypeError: Cannot read properties of undefined (reading 'customer_id'):
function () {
if ("customer_id" in Shopify !== "undefined") {
return Shopify.checkout.customer_id;
} else {
return ShopifyAnalytics.meta.page.customerId;
}
};
When it does exist, the function works. When it doesn't, it produces the Uncaught TypeError.
If the conditional statement is if ("customer_id" in Shopify) { then when the property exists, it fails the condition.
If the conditional statement is if ("customer_id" in Shopify.checkout) { then when the property exists, it meets the condition. But when the property doesn't exist, it produces the Uncaught TypeError.
The hasOwnProperty() method is not used because I need to check for inherited properties in the object. What's the right way to check if an inherited property exists in an object?
"customer_id" in Shopify
This will always resolve to a boolean, never to undefined, afaik so you need to remove the !== 'undefined' part on the check.
Also the way you have structured that, in case the property is not found on the first, you force the other, while it may well be null or undefined there as well, and this is the error you are having.
ShopifyAnalytics.meta.page.customerId // meta.page could be undefined
Somewhere during runtime you evaluate "undefined.anything" and so you get the " can not read property anything from undefined"
This question already has answers here:
How can I directly access [[PrimitiveValue]] value in JavaScript [closed]
(2 answers)
What is an "internal slot" of an object in JavaScript?
(2 answers)
What do double brackets mean in javascript and how to access them
(7 answers)
Closed 2 years ago.
In JavaScript, Object Class is the center of all happenings regarding data-type. One of the children of Object Class is Number Class. On making or creating a variable of type number its __proto__ will point to Number Class which then (via Prototypal Inheritance) makes a set of properties readily available to be used (eg: toExponential, toFixed, toString, etc.)
When I went through the whole list, I found at the end 2 more properties -- __proto__ and [[PrimitiveValue]] Now, just like the other properties, these 2 must also be readily avialable. So, I tried ... Now, to my dissapointment out of all these properties, the last one [[PrimitiveValue]] is giving error on Usage! Now, my surprise is, if via prototypal_Inheritance all the other properties are available and give some result, then what the heck is with this last property? I am simply tring to access it and ideally it should retrun me 0. That's all, so why the error???
Snippet:
This question already has answers here:
Dynamic variable name in loop
(3 answers)
Javascript use variable as object name
(15 answers)
Closed 4 years ago.
I have the following jQuery snippet which sets the 'selectedIndex' property of six select elements to '0'.
for (m = 1; m <= 6; m++) {
$("#po"+eval("leafWId"+m)).prop("selectedIndex", 0);
}
In the snippet scope there are among others the following variables defined:
leafWId1, leafWId2, leafWId3, leafWId4 with each one of these set to a different number, so the part
eval("leafWId"+m)
in each iteration, is equivalent to
eval("leafWId1"), eval("leafWId2"), eval("leafWId3")........
and thus, evaluates to each of the numbers referred above, and the snippet
$("#po"+eval("leafWId"+m))
returns a jQuery object consisting of select elements with id value of the type: "po345" for example.
Now, when the 'm' variable is set through the iteration to value '5', I get an Uncaught Reference Error, reporting that "leafWId5 is not defined" (as expected, since only four variables are defined, ie, leafWId1, leafWId2, leafWId3, leafWId4 as mentioned above).
I want to add a conditional statement that will check for an undefined variable whose name will be the result of the evaluation
eval("leafWId"+m)
and if is defined, then use the prop() method, if not, skip this, so I dont' get the Reference Error.
Or as an alternative, maybe check for the length of the jQuery object below
$("#po"+eval("leafWId"+m))
and proceed with the prop() method only when it's length is greater than zero.
Actually, the problem I face is that when m variable is set to '5', the part
eval("leafWId"+m)
evaluates to 'leafWId5', a variable that is not defined, and the snippet does not let me check for 'undefined' value in advance, because the eval() function gives an error, so any conditional statement I have used that checks for existing variable and uses the eval() function does not work.
This question already has answers here:
Using the variable "name" doesn't work with a JS object
(4 answers)
Closed 6 years ago.
In Firefox 45 on OSX, when I fetch an item from localStorage from a key that does not exist, the function call returns null. I tested this in the console.
If I instead assign the call result to a variable, and print its value in the console, I get "null", i.e. a string.
Why does a variable assignment of a previously not defined variable cast a call result to a String?
Used code (in the console):
localStorage.getItem("non-existing-key"); // returns null
var x = localStorage.getItem("non-existing-key");
x // returns "null"
Edit: both versions seem to behave correctly on Chrome 50.0.2661.86 on OSX (both return null)
Edit2: my mistake. I used another variable name in my tests (specifically: var name). Now, if I let the console return the value of the variable name, it returns window.name, which is a property of window of the type String, defaulting to "null". So, it's not an assignment that causes a cast, but instead its that I got a String property defined by window.
I made a mistake. The specific code I used was the following:
var name = localStorage.getItem("non-existing-key");
name
Now, getItem does return null and not a String. What then happens is that by letting the console print the value of name it does in fact get window.name (see window.name on MDN), which by default is "null" (a String).
This question already has an answer here:
Error when passing undefined variable to function?
(1 answer)
Closed 9 years ago.
Consider the following Javascript:
function getType(obj){
return(typeof(obj))
}
alert(typeof(obj)) //alerts "undefined" correctly
alert(getType(obj)) //throws an error: ReferenceError: obj is not defined
Why might this be happening? Is there any workaround? I am trying to write a function which checks if a variable exists.
The problem is nothing to do with typeof. The problem is that you cant pass undefined variables to functions.
function doNothing(obj){
}
doNothing(obj);
This code too results in the error: Uncaught ReferenceError: obj is not defined
So it doesn't matter what code you write inside your function, as it won't be called. The error happens before the function call.
typeof is an operator, not a function.
This is why it does not behave in the same way as functions.
typeof is an operator, not a function, and therefore has powers that a function can't have. There's no way to do what you're trying to do.
Your function fails as soon as you try to pass an undefined object. You can't encapsulate the typeof() function. Well, you can, but it will always throw errors when passed undefined objects.