Cheking if variable is undefined - node.js

So I want to check if a variable is undefined in node.js. So far I work like this:
if(typeof object.data.items[1] === 'undefined')
{
break;
}
else
{
console.log("Defined");
}
But it gives me this error:
"TypeError: Cannot read property 'data' of undefined".
Any ideas on how to bypass this error while still checking if it's undefined?

check both object and object.data is defined first.
if(object && object.data && typeof object.data.items[1] === 'undefined')
{
break;
}
else
{
console.log("Defined");
}
or
if(!object || !object.data || typeof object.data.items[1] === 'undefined')
{
break;
}
else
{
console.log("Defined");
}

It seems that object variable is undefined too. Try the following code:
if(
typeof object === 'undefined' ||
typeof object.data === 'undefined' ||
typeof object.data.items[1] === 'undefined')
{
break;
}
else
{
console.log("Defined");
}

if(!_.get(object,['data','items',1]))
{
break;
}

When you try to access a property of JSON object you have to ensure that left side of your dot operator must have some value but not undefined or null. i.e.
If you want to access a.b.c.d then you have to make sure that each left side property has some value. You can use #rijin's answer.

Related

Combining nested conditional logical operators

I was wondering if any can help point me to resource to teach me more about logical operators, and answer a question for me. I would like (for the sake of satisfying my curiosity) to combine these nested conditional checks with logical operators into one statement.
if(obj1 != null && obj2 != null) {
if(obj1 != undefined && obj2 != undefined) {
//do something here
}
}
I have tried
if((obj1 != null || obj1 != undefined) && (obj2 != null || obj2 != undefined)) {
//do something here
}
But I don't think that works, since if obj1 or obj2 is equal to null or undefined than the or statement will evaluate to true. So the above code in the conditional would be executed if obj1 was null or undefined AND obj2 was null or undefined, which is definitely not what I want.
So how could I combine the nested conditional into one line?
Thanks!
:)
You might be overthinking. Code like
if (a) {
if (b) {
// stuff
}
}
executes stuff only if a and b are both true, so it is simply equivalent to
if (a && b) {
// stuff
}
Thus all you have to do is take your existing conditions and connect them with &&. You can write
if((obj1 != null && obj2 != null) && (obj1 != undefined && obj2 != undefined)) {
//do something here
}

How do I open files in the most recently active Atom editor window instead of the Atom window I first opened?

Using Atom editor on Linux, I can't seem to find any option for opening files (using my file manager) in the most recent Atom window that was active. Instead, it always opens in the very first Atom window that was created.
How do I fix this?
There is an option for this:
-a, --add Open path as a new project in last used window. [boolean]
…but anyway, it does not work as expected. However, I`ve found a workaround.
This code is located somewhere around line 862 of src/main-process/atom-application.js:
if (existingWindow == null) {
if (currentWindow = window != null ? window : this.lastFocusedWindow) {
if (addToLastWindow || currentWindow.devMode === devMode && (stats.every(function(stat) {
return typeof stat.isFile === "function" ? stat.isFile() : void 0;
}) || stats.some(function(stat) {
return (typeof stat.isDirectory === "function" ? stat.isDirectory() : void 0) && !currentWindow.hasProjectPath();
}))) {
existingWindow = currentWindow;
}
}
}
Comment out the first line and its former closing bracket:
// if (existingWindow == null) {
if (currentWindow = window != null ? window : this.lastFocusedWindow) {
if (addToLastWindow || currentWindow.devMode === devMode && (stats.every(function(stat) {
return typeof stat.isFile === "function" ? stat.isFile() : void 0;
}) || stats.some(function(stat) {
return (typeof stat.isDirectory === "function" ? stat.isDirectory() : void 0) && !currentWindow.hasProjectPath();
}))) {
existingWindow = currentWindow;
}
}
// }
…aaaand voilà!
It`s a hackable text editor, after all ^_^

How to solve type error when I add new fields to object in nodejs

I created an object. But when I try to set some values in it an error is thrown.
See code below:
function CheckStatus(oldJob, newJob) {
var obj = {};
if(newJob && newJob.Status) {
if (oldJob.Status.total !== newJob.Status.total) {
obj.Status.total = newJob.Status.total;
}
if (oldJob.Status.charge_description && oldJob.Status.charge_description !== newJob.Status.charge_description) {
obj.Status.charge_description = newJob.Status.charge_description;
}
}
}
TypeError: Cannot set property 'total' of undefined
Well your definition of obj is an empty object. So before setting obj.Status.total you need to define obj.Status, either in the original declaration like so:
var obj = {
Status: {}
}
or later like so:
obj.Status = {}
Your obj variable has nos property status ! you must create his real structure before !
use lodash _.set :
const _ = require('lodash');
function CheckStatus(oldJob, newJob) {
let obj = {};
if (newJob && newJob.Status) {
if (oldJob.Status.total !== newJob.Status.total) {
_.set(obj, 'Status.total', newJob.Status.total);
}
if (oldJob.Status.charge_description && (oldJob.Status.charge_description !== newJob.Status.charge_description)) {
_.set(obj, 'Status.charge_description', newJob.Status.charge_description);
}
}
}
FYI it return a mutated object not a new object ! ;)

Ignore "document is not defined" error

The following line belongs to a 3rd party library I'm using in a Nodejs script:
if (document === undefined) return false;
source
it is raising
ReferenceError: document is not defined
I could get around it by wrapping the if statement in a try catch block:
try {
if (document === undefined) return false;
} catch (e) {
return false;
}
Is there another option that doesn't require modifying the library code?
It's a hack but I guess you just set it before you call into the library.
console.log(document === undefined) //error
global.document = undefined
console.log(document === undefined) //true

Node if statement execution order

I am confused why this if statement will throw a JS error. Why isn't the function running as soon as it returns true?
res.locals.user = null;
console.info(res.locals.user === null); //true
if (res.locals.user === null && res.locals.user.level > 5) {
The && in your if statement is analogous to this:
res.locals.user = null;
console.info(res.locals.user === null); //true
if (res.locals.user === null) {
// at this point you know that res.locals.user is null
if (res.locals.user.level > 5) {
// won't get here because res.locals.user.level will throw an exception
}
}
If the first part of an && comparison evaluates to truthy, then the second part will also be evaluated since for the whole statement to be true, both pieces of the statement must be truthy.
It appears that you may want this instead:
res.locals.user = null;
console.info(res.locals.user === null); //true
if (res.locals.user === null || res.locals.user.level > 5) {
// will get here because only the first term will be evaluated
// since when the first term evaluates to true, the || is already satisfied
}
Or since I'm not quite sure which logic you want, maybe you wanted this:
res.locals.user = null;
console.info(res.locals.user === null); //true
if (res.locals.user !== null && res.locals.user.level > 5) {
// will not get here because res.locals.user doesn't pass the first test
// won't throw an exception because 2nd term won't be evaluated
}
Because the first part of the evaluation is true, so it goes on to evaluate the next part which will then always throw an exception as the first part was true. It's like a paradox :)
There are languages where the the && only executes the second comparison if the first is true (like java). However, what you wrote would fail in any language. You can't be null and level>5 all at once.

Resources