Javascript, how to check if object exists - javascript

I am making a script in Javascript script that gets a SQL response, then processes it. Basically, I want to check if the username value exists in result[1]. When it checks, it errors out and says that it does not exist. If it does not exist, I want it to return false, not stop the program.
Here is the code:
if (result[1].username != undefined) {
return true;
} else {
return false;
}
I have tried using typeof(result1) == undefined, but it gives me the same error.

First, you have to make sure the result exists, otherwise you'd be indexing into undefined which would crash your application.
Second, you can make that check less verbose with:
return (result[1] && result[1].username)
which will return a falsey value if it doesn't exist, and whatever the username is, if it does.
In case you need an explicit true to be what the function returns, you can coerce it:
return (result[1] && (result[1].username && true))
I would make sure to refactor for readability, but that's the gist.

You could use the in operator. For example:
let trueObj = { username: 'Foo' };
let falseObj = { };
if ('username' in trueObj) {
console.log('username found in trueObj');
} else {
console.log('username not found in trueObj')
}
if ('username' in falseObj) {
console.log('username found in falseObj');
} else {
console.log('username not found in falseObj')
}

First of all please check whether the result itself exists or not and make the corresponding & operator and i think this will definitely help
if (result && result[1] && result[1].username) {
return true;
} else {
return false;
}
But if you don't want to make your code complex then you can try lodash library.
https://lodash.com/

Related

How do I make node respond with error if payload is empty

I need a code to respond with error if payload is empty. How do I do this?
if(req.body !== {}){
res.json(newUser)
}else{
res.status(400).json('fill in the necessary information')
}
The check req.body !== {} will ALWAYS be true, since you can't compare objects. You could check if it's undefined, and then check for keys to know if it's empty. Something like this:
if(req.body && Object.keys(req.body).length !== 0){
res.json(newUser)
} else {
res.status(400).json('fill in the necessary information')
}
Read more about object's equality here.
if(req.body){
res.json(newUser)
}else{
res.status(400).json('fill in the necessary information')
}

Why aren't i successfully getting the embedded "if" in the second code section to do its job?

var checking_location = "none"
const getentitiesByType = (arr, type) => {
for (let i in arr) {
if (arr[i].type === type) {
checking_location = "exists"
return arr[i].entity
}
}
return null;
}
if (!meeting.location) {
if (checking_location != 'exists') {
rl.question('where is the location ', function(answer) {
// session.send("The location you gave:" answer);
rl.close();
session.send(answer)
// console.log(tryagain(answer, 'Calendar.Location'));
session.send(tryagain(answer, 'Calendar.Location'));
});
}
} else {
next();
}
What i'm trying to do here is to have a loop in the if (!meeting.location) if checking_location stays equal to none. Basically i want to check if a certain Json field exists, if it doesn't i want to keep asking the question in rl.question.My issues is that the code is only working the first time, then even if i give another input not containing the required field i don't get that question.Also note that this is not the entire code but it's more than enough to understand the possible issue spots in my implementation.
getentitiesByType needs to be called somewhere, simply assigning it to a variable will not make the function run: getentitiesByType(youArr, yourType).
Also, as a side note, instead of using string values for checking_location just rename the variable and use a boolean value. Ex: var hasLocation = false.

user authorization with equals() in javascript

I made a blog in which a user can only edit it the blogs they created. But now I want to make an admin that can edit and delete any post he wants.
if(foundBlog.author.id.equals(
req.user._id ||
foundBlog.author.username === "ADMIN"
)) {
next();
} else {
res.redirect("back");
}
But my code doesn't work.
equals() is not a valid String function except you have implemented this yourself. If you haven't and want to, you could do something as simple as
String.prototype.equals = function(str){
return this.toString() === str;
}
and then
"hello".equals("hello") // gives true
"hello".equals("kitty") // gives false
However, I would advice against poisoning the prototype of a well-known/built-in object or any shared global space for that matter cause that is a recipe for disaster.
With that said, I'll just go for the strict equality comparison.
if(foundBlog.author.id === req.user._id || foundBlog.author.username === "ADMIN")
No harm no foul.

JavaScript / AJAX / Servlet compare Strings

I am trying to compare a string that is returned from servlet
Servlet page returns this:
out.println("pass");
JavaScript:
function Return() {
if (ajax.responseText === "pass") {
document.getElementById("pass").innerHTML = "This is valid number!";}
Now I have output the ("ajax.responseText") and it returns "pass" but I can't still validate it in the IF statement.
I tried using (.equal("pass") i tried with == and I even tried "var value = ajax.responseText; and then tried value === "pass")
Yes I also tried .toString()..
It just never validates it correctly it always goes to ELSE statement...
println usually appends a line break at the end of the string (the "ln" in println stands for "line") and thus the string value returned by the server is actually "print\n" (or something similar), which is not equal to "pass".
If available, use
out.print("pass");
which doesn't append a line break.
Or trim the response before comparison.
Instead of your original function Return (which doesn't explicitly return)
function Return() { // Why not checkPassword?
if (ajax.responseText === "pass") { // exactly equal
document.getElementById("pass").innerHTML = "This is valid number!";
}
}
Try something like this (e.g. presumably it should be true or false, so do so explicitly)...
function checkPassword() { // probably should pass arguments what the function does.
if (ajax.responseText.trim() == "pass") { // trim the response string
// ('pass\n' != 'pass')
console.log('Got a match!'); // Try logging it.
document.getElementById("pass").innerHTML = "This is valid number!";
return true; // return a value?
} else {
// Again, I would try adding some debug logging.
console.log('Did not match! ' + ajax.responseText);
}
return false; // default to false.
}

Check if localStorage is available

I know there has been many questions about checking for localStorage but what if someone manually shuts it off in their browser? Here's the code I'm using to check:
localStorage.setItem('mod', 'mod');
if (localStorage.getItem('mod') != null){
alert ('yes');
localStorage.removeItem('mod');
} else {
alert ('no');
}
Simple function and it works. But if I go into my Chrome settings and choose the option "Don't Save Data" (I don't remember exactly what it's called), when I try to run this function I get nothing but Uncaught Error: SecurityError: DOM Exception 18. So is there a way to check if the person has it turned off completely?
UPDATE: This is the second function I tried and I still get no response (alert).
try {
localStorage.setItem('name', 'Hello World!');
} catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
alert('Quota exceeded!');
}
}
Use modernizr's approach:
function isLocalStorageAvailable(){
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
if(isLocalStorageAvailable()){
// available
}else{
// unavailable
}
It's not as concise as other methods but that's because it's designed to maximise compatibility.
The original source: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js
Working example: http://jsfiddle.net/6sm54/2/
I'd check that localStorage is defined prior to any action that depends on it:
if (typeof localStorage !== 'undefined') {
var x = localStorage.getItem('mod');
} else {
// localStorage not defined
}
UPDATE:
If you need to validate that the feature is there and that it is also not turned off, you have to use a safer approach. To be perfectly safe:
if (typeof localStorage !== 'undefined') {
try {
localStorage.setItem('feature_test', 'yes');
if (localStorage.getItem('feature_test') === 'yes') {
localStorage.removeItem('feature_test');
// localStorage is enabled
} else {
// localStorage is disabled
}
} catch(e) {
// localStorage is disabled
}
} else {
// localStorage is not available
}
Feature-detecting local storage is tricky. You need to actually reach into it. The reason for this is that Safari has chosen to offer a functional localStorage object when in private mode, but with it's quotum set to zero. This means that although all simple feature detects will pass, any calls to localStorage.setItem will throw an exception.
Mozilla's Developer Network entry on the Web Storage API's has a dedicated section on feature detecting local storage. Here is the method recommended on that page:
function storageAvailable(type) {
try {
var storage = window[type],
x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
}
catch(e) {
return false;
}
}
And here is how you would use it:
if (storageAvailable('localStorage')) {
// Yippee! We can use localStorage awesomeness
}
else {
// Too bad, no localStorage for us
}
If you are using NPM, you can grab storage-available using
npm install -S storage-available
then use the function like so:
if (require('storage-available')('localStorage')) {
// Yippee! We can use localStorage awesomeness
}
Disclaimer: Both the documentation section on MDN and the NPM package were authored by me.
MDN updated the storage detect function. In 2018, it's more reliable:
function storageAvailable() {
try {
var storage = window['localStorage'],
x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
}
catch(e) {
return e instanceof DOMException && (
// everything except Firefox
e.code === 22 ||
// Firefox
e.code === 1014 ||
// test name field too, because code might not be present
// everything except Firefox
e.name === 'QuotaExceededError' ||
// Firefox
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
// acknowledge QuotaExceededError only if there's something already stored
storage && storage.length !== 0;
}
}
Browsers that support localStorage will have a property on the window object named localStorage. However, for various reasons, just asserting that property exists may throw exceptions. If it does exist, that is still no guarantee that localStorage is actually available, as various browsers offer settings that disable localStorage. So a browser may support localStorage, but not make it available to the scripts on the page. One example of that is Safari, which in Private Browsing mode gives us an empty localStorage object with a quota of zero, effectively making it unusable. However, we might still get a legitimate QuotaExceededError, which only means that we've used up all available storage space, but storage is actually available. Our feature detect should take these scenarios into account.
See here for a brief history of feature-detecting localStorage.
With this function you can check if localstorage is available or not, and you keep under control the possible exceptions.
function isLocalStorageAvailable() {
try {
var valueToStore = 'test';
var mykey = 'key';
localStorage.setItem(mykey, valueToStore);
var recoveredValue = localStorage.getItem(mykey);
localStorage.removeItem(mykey);
return recoveredValue === valueToStore;
} catch(e) {
return false;
}
}
It is better to check availability of localStorage in conjunction with cookies, because if cookie is enabled the browser could detect that localStorage is available and type it as object, but provide no possibility to work with it. You use the next function to detect both localStorage and cookies:
const isLocalStorage = () => {
try {
if (typeof localStorage === 'object' && navigator.cookieEnabled) return true
else return false
} catch (e) {
return false
}
}
You can try this method
Anytime validate the content of the localstore
const name = localStorage.getItem('name');
if(name){
console.log('Exists');
}else
{
console.log('Not found');
}
I tried this solution in Chrome, Firefox and Edge and it worked correctly.
if (localStorage.getItem('itemName') === null )
{
// your code here ...
}
if the local variable on localStorage do not exist it will brind false.
You can create a checker function which tries to get a non existing item from the localStorage. When the localStorage is turned on you will normally get null returned. But when the localStorage is turned off an error will be thrown. You don't have to set any item for the checking.
const checkLocalStorage = () => {
try {
localStorage.getItem("x");
return true;
} catch {
return false;
}
}
Modifying Joe's answer to add a getter makes it easier to use. With the below you simply say: if(ls)...
Object.defineProperty(this, "ls", {
get: function () {
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
});
Here is an easy check:
if(typeof localStorage === 'undefined'){
Use this to check localStorage is set or not. Its help you to get status of Localstorage.
if( window.localStorage.fullName !== undefined){
//action
}else{
}

Categories