I have the following code...
function foo(type) {
if(foo.type == undefined) foo.type = 0;
}
What I'd like it to do is create a new property on the foo object for each "type" that comes through and set that property to zero (and later begin counting each time a "type" comes through). However, I hit a mental blip, in this case foo.type is probably evaluated as the property type, on foo and not whatever the variable type refers to.
I need to convert the value of type to a property, any ideas?
And yes I know this question's name sucks, if you think of something better just edit the quesiton.
function foo(type) {
if(foo[type] == undefined) foo[type] = 0;
}
You probably want to use === undefined so you won't get any unexpected results
if (typeof foo[type] === 'undefined') {
foo[type] = 0;
}
Related
canvas.getActiveObject().type returns the type of the currently active element in the canvas.
var type = canvas.getActiveObject().type;
if(type){
console.log(type);
}
But when no element is active, I get TypeError, which of course happens because no element is active so there is nothing to getActiveObject from.
TypeError: canvas.getActiveObject(...) is null
Why can't I assign a variable when the activeObject is null?
Same error happens, when I try
var type = '';
if(canvas.getActiveObject().type){
type = canvas.getActiveObject().type
}
canvas.getActiveObject() is returning null.
That means that canvas.getActiveObject().type is the same as null.type.
Referencing any member of null will throw an exception.
You can solve this any number of ways
Three lines of code:
let type = '';
if(canvas.getActiveObject()) {
type = canvas.getActiveObject().type;
}
Or a one-liner:
let type = canvas.getActiveObject()
? canvas.getActiveObject().type
: '';
Or a more compact one-liner:
let type = (canvas.getActiveObject() || { type: ''}).type;
You can't access a null value like an object, I think you should safely access the value like.
var type = '';
if(canvas.getActiveObject() && canvas.getActiveObject().type){
type = canvas.getActiveObject().type
}
It looks like you're trying to access the property type returned by the function getActiveObject(), but since the function returns null, accessing the type property is throwing an error. What you need to do instead is check the return value of getActiveObject() before trying to access any of its members.
The snippet below, which is based on your code, instead checks that the active object returned is not null before attempting to access the members that reside within it.
var activeObject = canvas.getActiveObject();
if (activeObject) {
console.log(activeObject.type);
}
Is it possible to write this in shorter and cleaner way?
I'm reading it from an XML, sometimes the URL value does not exist.
if (typeof(entry[i].getElementsByTagName("url")[0].childNodes[0]) !== "undefined") {
var foo = 'baar'
} else {
var foo = entry[i].getElementsByTagName("url")[0].childNodes[0]
}
It's been years it doesn't make sense anymore to use this construct (unless you don't know whether the variable, not the value, is undefined). undefined is now read only.
Simply use
if (entry[i].getElementsByTagName("url")[0].childNodes[0] === undefined) {
In almost all cases, typeof x === "undefined" is a bad practice.
In the specific case of a DOM element, you can also simply use
if (!entry[i].getElementsByTagName("url")[0].childNodes[0]) {
because you can't have a falsy node, and of course, when the goal is to apply a default value, just use
var foo = entry[i].getElementsByTagName("url")[0].childNodes[0] || 'baar';
(be careful that this test only works when all the parts before the the last [0] are present, it's usually convenient to use querySelector or a DOM selection API like jQuery to make everything less verbose).
var foo = entry[i].getElementsByTagName("url")[0].childNodes[0] || 'baar'
You can write in this way.
var ele = entry[i].getElementsByTagName("url");
if (ele && ele[0].childNodes[0]) {
var foo = 'baar'
} else {
//code
}
There is no need to check it explicitly for undefined.undefined is evaluated as false.
I'm wondering how to go about doing this. Not sure what the terminology is so I apologize for that. I've seen this behavior in jQuery when you use the .css() method. As you may know already, this method accepts a couple of options:
You can do the following:
$("#box").css("background-color", "red");//sets the bg color to red
$("#box").css("background-color");//returns the bg color of #box
var properties = {"background-color" : "red", "width" : 100};
$("#box").css(properties); //sets multiple properties in one call with literal object.
So, I'm not so much worried about the getter portion of this functionality. I'm most interested in it's ability to differentiate between a variable and a literal object. I'd like to create a plugin that has the same behavior based on the argument it receives. A simple example would be something like this:
function openWindow(URL_OR_OBJECT){
if(variable){
window.open(URL_OR_OBJECT);
return;
}
var opt = URL_OR_OBJECT;
window.open(opt.url, opt.title, opt.options, opt.replace);
}
You can inspect the type of the parameter with typeof
function openWindow(parameter){
if(typeof parameter == "string"){
window.open(parameter);
}
else if(typeof parameter == "object"){
window.open(parameter.url, parameter.title, parameter.options, parameter.replace);
}
}
You could use typeof to see if the argument is a string.
if ( typeof URL_OR_OBJECT === "string" ) {
window.open(URL_OR_OBJECT);
} else { /*...*/ }
You can to be a little cautious using this because typeof new String("hello") is "object". But I don't think too many people declare a string that way.
typeof docs on MDN: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/typeof
While I have not looked at the source code in particular, I presume it is structured something similar to this:
function css(bgcolor_or_obj, width, etc) {
var bgcolor;
if(typeof bgcolor_or_obj === 'object') {
// Expand configuration object here.
bgcolor = bgcolor_or_obj.bgcolor;
width = bgcolor_or_obj.width;
etc = bgcolor_or_obj.etc;
} else {
bgcolor = bgcolor_or_obj;
}
/* ... */
}
I am aware of no standardized way in Javascript to differentiate between an argument passed to a function as being a variable or a literal. It is more likely that the function in question is checking if the first argument is an object, as demonstrated above.
I have a javascript function that takes two parameters, 'key' and 'value'.
If only one parameter is given then the 'key' parameter is given a default value and the undefined 'value' parameter gets the 'key' parameter value.
function thingSet(key,value){
if(typeof value === 'undefined'){
value=key;
key='_default';
}
//... use key and value
}
The code works but I feel abit uneasy for some reason.
Are there better ways to do this?
You can refactor it like this:
function thingSet (key, value) {
key = key || '_default';
value = value || key;
//... use key and value
}
That's nice short-circuit evaluation allowing you to set default values easily there.
This is pretty standard and heavily used "overloading" mechanism in javascript. You'll find it all over the libraries like jQuery.
Like many dynamic language constructs, there is a gap between what compiler can check for you and what you have to keep as a convention, perhaps documenting it thouroughly.
The power comes at a price of robustness. If you use this kind of tricks, you have to make sure everybody understands the implied API and uses it accordingly.
You can set default values like this:
function thingSet(key,value){
key = key || '_default';
value = value || key;
//... use key and value
}
At least, that is what I make of your function. The unease may be due to the fact that in your function key may be undefined too, in which case the assignment after checking the condition if(typeof value === 'undefined') still may result in an undefined value
You can check for existence of at least one parameter using arguments.length.
function thingSet(key,value){
if (!arguments.length) {
alert('please supply at least one parameter');
return true;
}
key = key || '_default';
value = value || key;
//... use key and value
}
Seems fine to me. The only thing I'd have done differently would be a more direct comparison on value:
if(value == undefined){
I normally do this with JSON
myfunction = function(args){
args.key = (typof(args.key) == "undefined")?args.key = "_default":args.key;
args.value = (typof(args.value) == "undefined")?args.key:args.value;
}
myfunction({key:"something",value:"something else"})
that way you know which variable you are passing to the function and don't have to assume anything from within the function.
It's hard to discuss design questions on a dummy example, but I'd prefer a function that always accepts one parameter, which can be a simple value, or a hash of values. Consider this slightly more realistic example:
function setName(opt) {
if (typeof opt != "object") {
var p = opt.split(" ");
opt = { first: p[0], last: p[1] };
}
$.extend(this, opt);
}
This can be used as person.setName('John Doe') or person.setName({last:'Doe'})
How do I verify the existence of an object in JavaScript?
The following works:
if (!null)
alert("GOT HERE");
But this throws an Error:
if (!maybeObject)
alert("GOT HERE");
The Error:
maybeObject is not defined.
You can safely use the typeof operator on undefined variables.
If it has been assigned any value, including null, typeof will return something other than undefined. typeof always returns a string.
Therefore
if (typeof maybeObject != "undefined") {
alert("GOT THERE");
}
There are a lot of half-truths here, so I thought I make some things clearer.
Actually you can't accurately tell if a variable exists (unless you want to wrap every second line into a try-catch block).
The reason is Javascript has this notorious value of undefined which strikingly doesn't mean that the variable is not defined, or that it doesn't exist undefined !== not defined
var a;
alert(typeof a); // undefined (declared without a value)
alert(typeof b); // undefined (not declared)
So both a variable that exists and another one that doesn't can report you the undefined type.
As for #Kevin's misconception, null == undefined. It is due to type coercion, and it's the main reason why Crockford keeps telling everyone who is unsure of this kind of thing to always use strict equality operator === to test for possibly falsy values. null !== undefined gives you what you might expect. Please also note, that foo != null can be an effective way to check if a variable is neither undefined nor null. Of course you can be explicit, because it may help readability.
If you restrict the question to check if an object exists, typeof o == "object" may be a good idea, except if you don't consider arrays objects, as this will also reported to be the type of object which may leave you a bit confused. Not to mention that typeof null will also give you object which is simply wrong.
The primal area where you really should be careful about typeof, undefined, null, unknown and other misteries are host objects. They can't be trusted. They are free to do almost any dirty thing they want. So be careful with them, check for functionality if you can, because it's the only secure way to use a feature that may not even exist.
You can use:
if (typeof objectName == 'object') {
//do something
}
Two ways:
typeof for local variables
You can test for a local object using typeof:
if (typeof object !== "undefined") {}
window for global variables
You can test for a global object (one defined on the global scope) by inspecting the window object:
if (window.FormData) {}
If that's a global object, you can use if (!window.maybeObject)
You could use "typeof".
if(typeof maybeObject != "undefined")
alert("GOT HERE");
If you care about its existence only ( has it been declared ? ), the approved answer is enough :
if (typeof maybeObject != "undefined") {
alert("GOT THERE");
}
If you care about it having an actual value, you should add:
if (typeof maybeObject != "undefined" && maybeObject != null ) {
alert("GOT THERE");
}
As typeof( null ) == "object"
e.g. bar = { x: 1, y: 2, z: null}
typeof( bar.z ) == "object"
typeof( bar.not_present ) == "undefined"
this way you check that it's neither null or undefined, and since typeof does not error if value does not exist plus && short circuits, you will never get a run-time error.
Personally, I'd suggest adding a helper fn somewhere (and let's not trust typeof() ):
function exists(data){
data !== null && data !== undefined
}
if( exists( maybeObject ) ){
alert("Got here!");
}
I used to just do a if(maybeObject) as the null check in my javascripts.
if(maybeObject){
alert("GOT HERE");
}
So only if maybeObject - is an object, the alert would be shown.
I have an example in my site.
https://sites.google.com/site/javaerrorsandsolutions/home/javascript-dynamic-checkboxes
The thread was opened quite some time ago. I think in the meanwhile the usage of a ternary operator is the simplest option:
maybeObject ? console.log(maybeObject.id) : ""
I've just tested the typeOf examples from above and none worked for me, so instead I've used this:
btnAdd = document.getElementById("elementNotLoadedYet");
if (btnAdd) {
btnAdd.textContent = "Some text here";
} else {
alert("not detected!");
}
Apart from checking the existence of the object/variable you may want to provide a "worst case" output or at least trap it into an alert so it doesn't go unnoticed.
Example of function that checks, provides alternative, and catch errors.
function fillForm(obj) {
try {
var output;
output = (typeof obj !== 'undefined') ? obj : '';
return (output);
}
catch (err) {
// If an error was thrown, sent it as an alert
// to help with debugging any problems
alert(err.toString());
// If the obj doesn't exist or it's empty
// I want to fill the form with ""
return ('');
} // catch End
} // fillForm End
I created this also because the object I was passing to it could be x , x.m , x.m[z] and typeof x.m[z] would fail with an error if x.m did not exist.
I hope it helps. (BTW, I am novice with JS)
for me this worked for a DOM-object:
if(document.getElementsById('IDname').length != 0 ){
alert("object exist");
}
if (n === Object(n)) {
// code
}
if (maybeObject !== undefined)
alert("Got here!");
set Textbox value to one frame to inline frame using div alignmnt tabbed panel.
So first of all, before set the value we need check selected tabbed panels frame available or not using following codes:
Javascript Code :
/////////////////////////////////////////
<script>
function set_TextID()
{
try
{
if(!parent.frames["entry"])
{
alert("Frame object not found");
}
else
{
var setText=document.getElementById("formx").value;
parent.frames["entry"].document.getElementById("form_id").value=setText;
}
if(!parent.frames["education"])
{
alert("Frame object not found");
}
else
{
var setText=document.getElementById("formx").value;
parent.frames["education"].document.getElementById("form_id").value=setText;
}
if(!parent.frames["contact"])
{
alert("Frame object not found");
}
else
{
var setText=document.getElementById("formx").value;
parent.frames["contact"].document.getElementById("form_id").value=setText;
}
}catch(exception){}
}
</script>
zero and null are implicit pointers. If you arn't doing arithmetic, comparing, or printing '0' to screen there is no need to actually type it. Its implicit. As in implied. Typeof is also not required for the same reason. Watch.
if(obj) console.log("exists");
I didn't see request for a not or else there for it is not included as. As much as i love extra content which doesn't fit into the question. Lets keep it simple.
Think it's easiest like this
if(myobject_or_myvar)
alert('it exists');
else
alert("what the hell you'll talking about");
Or, you can all start using my exclusive exists() method instead and be able to do things considered impossible. i.e.:
Things like: exists("blabla"), or even: exists("foreignObject.guessedProperty.guessNext.propertyNeeded") are also possible...