Configure javascript to rise error when pass json undefined member? - javascript

You have a json object.
By mistake you pass some element (property1) to a function and the value passed doesn't exists...
myFunction (json.propety1); // it must be 'property1' , with r
I'd like to set any configure element to say the browser "I can't pass undefined json properties, rise an error"
I think this is not possible, is't it ?
Thanks in advance

in myfunction you can check for undefined and then do something
like
function myFunction(jsonproperty){
if(jsonproperty === undefined){
//do something with the DOM to pass whatever you wanna say in the browser
}
}
Is that what you were trying to do? You could also throw an exception like this:
throw "json property was undefined"
but you would only see that in some kind of js debugger console. Nowadays all browser have one. Usually accessible with "F12"

Related

Console Script issue with localstorage

I have an application that has inside the local storage a variable named token.
I want to write a code that clears the console and the shows an alert(); with
the aforementioned variable.
This is what I have managed to do so far
clear(); if(localStorage){alert(localStorage.getItem("token"));}
But I keep getting the error that localStorage is not defined. More precisely:
Uncaught ReferenceError: localStorage is not defined
at <anonymous>:1:12
Any ideas?
I don't have the full context of your code, but if localStorage isn't defined then you can't check if it's value is defined.
For example, and that's true for any variable, if you don't define the variable bla, then the following code will throw the same error:
if (bla) console.log(bla);
You should use if (typeof localStorage !== "undefined") instead.
Furthermore, your browser doesn't necessarily support localStorage, so you should check that before. And using try-catch is also a good idea when working with localStorage.
In some cases, you cannot use "localStorage" as a boolean.
As Gilad Bar suggested, use if (typeof localStorage !== "undefined") instead.
Also, make sure that "token" isn't null or undefined.

Able to Get Value in Console, But Undefined When Called From Function in Angular 2 App

I am running into an issue in my Angular 2 app where I'm getting an undefined error that's not making sense to me. What's more perplexing is that, after getting the undefined error, I can effectively check the exact same value in the console and get it with no issues.
First off, here's a version of the function that DOES work:
public getApplicableResult()
{
if (!this.customer || !this.customer.services || !this.customer.services.getAt(0))
{
console.log('Services not available...');
return;
}
else if (this.customer && this.customer.services && this.customer.services.getAt(0))
{
console.log(this.customer.services.getAt(0));
}
When I run this function I get this in the console for my "console.dir" of my object literal:
CustomerServiceDetails
assignments:(...)
authorizations:(...)
If I then click on "assignments" in the console, I get this expanded result:
assignments:
CustomerAssignmentCollection
count:1
items:Array(1)
So all the data is seemingly there and available.
However, if, in my function, if I were to try and access these nested values more directly - such as the value for "count" above, I get an undefined error. That's what I'm not understanding. Perhaps it's something I misunderstand about how the console works. But if seems to me that if I can access the value for this property in the console, then I should be able to access it directly via my function.
Here's an example of the same function, slightly altered to get the result for "count" within assignments, that returns undefined:
public getApplicableResult()
{
if (!this.customer || !this.customer.services || !this.customer.services.getAt(0).assignments)
{
console.log('Services not available...');
return;
}
else if (this.customer && this.customer.services && this.customer.services.getAt(0).assignments)
{
console.dir(this.customer.services.getAt(0).assignments.count);
}
The specific error I get is:
Cannot read property 'assignments' of undefined;
To add some additional info, assignments is not an array, it's a collection.
Two questions here:
1.) Why isn't my first "if" clause handling the 'undefined' error? How could I adjust it to handle the situation better?
2.) Why can I call the first function, get a result, and then drill down from there in the console to get what I need, but if I try and access a more nested part of the object in the function itself, I get undefined as a result?
One additional detail, I was calling this via Angular's ngAfterViewChecked(). So what that should do, even if it's a timing issue, is return the first "if" else clause result until the value is available, and then it should show the result - i.e., it should execute the "else if" block - because AfterViewChecked() keeps checking. But this isn't happening. I'm just getting the undefined result I mentioned above.

Avoid declaring large object in getDefaultProps prior to an event

The title might not be the best way to describe the problem, but I was wondering if there was a better practice to declaring an object in getDefaultProps?
In my render method I call several keys from from a prop/state that get updated on a click event i.e. this.props.player.name. The problem is that on page load this.props.player is blank and calling .name errors out. I know I can do something like ...
getDefaultProps: function() {
return {
player: {
name: null,
team: null
position: null
}
};
}
but it doesn't feel right. I was hoping there might be something similar to how Ruby does .try() where it won't try to call a method on a undefined prop.
The problem is specifically that this.props.player is undefined, if you define an empty object it will prevent the error from occurring. It's not bad practice to stub out the keys you're anticipating, but setting the default value to {} will be enough to prevent it from throwing.
You can create your data from ImmutableJS. Then you can get any part of your data like this:
this.state.getIn(['player', 'name', ...])
or
this.state.get('player')
This will not throw error even player is not defined or other, it will return undefined (or null) I don't remember
The update and updateIn work the same
see the doc here
I'd like to add this vanilla JS solution too - var x = (user || {}).name;
Source

Passing values back to be rendered by Jade, using Express and Node

I asked a question yesterday, but I've kept going with it. Instead of calling next() and passing an an Error object, I worked out what it was doing, and tried to copy it. Now, when someone logs in and it fails, I do this:
res.render("pages/home",
{
flash:{"danger":["Login failed. Please enter your details and try again."]},
body:{},
section:"home",
locals : { userId : req.body.email }
}
This does exactly the same thing as the old code. I step through it, and I can see that the locals object contains a property called userId, with the value I expect. In the Jade template, I have this:
p it's #{typeof(userId)}
if(typeof(userId) != 'undefined')
p Welcome #{userId}
input(type='text', name='email', id="inputEmail", placeholder="Email", value="#{userId}")
else
input(type='text', name='email', id="inputEmail", placeholder="Email", value="")
This always renders as 'it's undefined' and then an empty text box. I have read several questions on this, and as far as I can see, they all say the same thing: if I set locals to be a JSON object, I can access it's properties by this syntax, but it does not work.
What am I doing wrong ?
You might first need to better understand how locals object actually work.
On the server-side, doing this:
res.render('view', { property: 'value' } );
would make property available in your views like so:
div Value = #{property}
You can also do the following to have the same effect:
res.locals.property = 'value';
res.render('views');
Note the usage of locals object. More info
Coming back to your issue, since you have
res.render("pages/home", { locals: { userId : req.body.email } })
to access userId in this case you would do:
p Welcome #{locals.userId}
So I'm guess you're confusing the two approaches ending up using locals object the wrong way.
OK - turns out that 'locals' doesn't mean anything any more. Leaving my code as it is, I needed to access 'locals.userId', but I could have just set the value of 'userId' and not had the 'locals' object at all.

Logging an error with offset().top, why?

I am trying to determine the top offset of an element and the console logs an error, even though JQuery's documentation says it should be written like this:
$('.myObject').offset().top
Error:
Uncaught TypeError: Cannot read property 'top' of undefined
Why does this happen?
Any solution for the problem?
This usually happens because $('.myObject') returns nothing. To protect your code from crashing, check if the element exists before calling .offset().top
var myObj = $('.myObject');
if (myObj.length){
myObj.offset().top
}
Since .top is a property and not a method, it is not handled by jQuery and, hence, will crash your script if it is not existing.
You'll have to check if the element exists.
e.g.
var myObjExists = $('.myObject').length > 0 ? true : false;
if you then console.log(myObjExists);, it should return true or false.
From here you can do some errorhandling to why it does not exist.
If you need more details, please also post the HTML that this code points to.

Categories

Resources