Javascript object property detection - javascript

What is the least amount of code needed to do the following:
If an object exists and it has a required property and the property is not an empty string then set a variable to the value of the property else set the variable to a default string.
Assuming that the object variable can only be undefined or a valid object, it can never be a function, null, string or anything else. Also if the object has the required property it is a string and never anything else.
A solution to this maybe:
// obj is the object we are testing, prop is the name of the property, def is the default string
var result = def;
if (obj && obj[prop] && obj[prop].length) {
result = obj[prop];
}
Whether this is completely correct I am unsure.
But is there a shorter way?
Thanks,
AJ

If you want to shorten it, you can write:
result = (obj && obj[prop]) || def;
An empty string is falsy, so you don't need to check the length explicitly.
result = <val> || <default>;
is a common idiom for setting a variable to a value, with a default if the value is null.

Related

Checking if the property exist versus checking if it is null

Is it harder to check if a property exists in a JSON object versus checking if the property is null?
Can you do both at the same time?
You can use hasOwnProperty(prop) to determine if the property exists.
var a = { p: null };
a.p == null; // true
a.hasOwnProperty('p'); // true
The syntax for checking if a property exists is:
if ('prop' in obj)
or
if (obj.hasOwnProperty('prop'))
The syntax for checking if a property is null is:
if (obj.prop === null)
You can't in general do both in a single operation. If the property doesn't exist, obj.prop will be undefined, so === null will be false.
However, in many cases you know a priori what kind of values a property will contain. If you know that if it exists it will always be a truthy value, you can simply write:
if (obj.prop)
A common situation where this occurs is when the property always contains an object. We can take advantage of this in idioms like:
if (obj && obj.prop && obj.prop.subprop && obj.prop.subprop.number == 3)

Why can't I set object property to empty string in JavaScript?

I want to pass the values from my request body into a paramsDict object where I have defined constraint to test the parameters against. I don't require that all possible parameters are sent with every request and also, if a value is deleted on the client, it can be sent as an empty string.
So we pass the values to the dictionary like so
for ( p in paramsDict ) {
if ( container[p] ) {
paramsDict[p].value = container[p];
}
}
where container is set to req.body (in node.js express).
In the case where container[p] = "" the property paramsDict[p].value never gets set, i.e typeof paramsDict[p].value returns "undefined" (note: it does not exist on the object before I attempt to assign it here). This means adding an extra check which I would rather not have to:
if (typeof container[p] == "string" && container[p].length == 0){
paramsDict[p].value = "";
}
Investigating I see that paramsDict[p].value = "" and paramsDict[p].value = false both set the property to the empty string and false respectively (I include false because the empty string is falsey in JS).
typeof container[p] returns "string" when the value is the empty string so I am very surprised that is does not assign the empty string as the value.
Is this a decision that has been made for this implementation of JS or is it a bug?
Your check for the property [p] will return false even in the cases you care about (empty string or false). Instead of if (container[p]), you should use if (container.hasOwnProperty(p)).
You answered your own question: empty string is falsy, so this will evaluate to false when container[p] === '':
if ( container[p] ) {
So, assignment to paramsDict won't happen.

How to make shorter and readable comparison/logical lines to assign default values? in jQuery/JavaScript?

Consider the code at the bottom, inside a regular function, that checks if some argument was provided or not, and assigns a default value to a variable named message. If the argument is truthy or an empty string, It is simply converted to a string and is stored in the message variable, otherwise the type of argument will be stored in message.
I know it's possible to shorten if else statements to assign default values to variables, like:
var message = arguments[0] || jQuery.type(arguments[0]);
which if only the arguments[0] is truthy will be stored in message. But how to make an exception for an empty string which is a falsy value, without having to use a long if else statement?
if(arguments[0] || arguments[0] === '')
var message = arguments[0].toString();
else
var message = jQuery.type(arguments[0]);
var message = ((arguments[0] || arguments[0] === '') ? arguments[0].toString() : jQuery.type(arguments[0]));
It sounds like you're looking for a shorthand if/else. If so, you can find the answer to your question here. Basically what you need is a ternary operator.
Excerpt below:
var x = y !== undefined ? y : 1;

Set JavaScript variable = null, or leave undefined?

When declaring variables at the top of the JavaScript function, is it best practice to set them equal to null, or leave as 'undefined'? Another way to ask, what circumstances call for each option below?
Option A:
var a = null,
b = null;
Option B:
var a,
b;
It depends on the context.
"undefined" means this value does not exist. typeof returns "undefined"
"null" means this value exists with an empty value. When you use typeof to test for "null", you will see that it's an object. Other case when you serialize "null" value to backend server like asp.net mvc, the server will receive "null", but when you serialize "undefined", the server is unlikely to receive a value.
I declare them as undefined when I don't assign a value because they are undefined after all.
Generally, I use null for values that I know can have a "null" state; for example
if(jane.isManager == false){
jane.employees = null
}
Otherwise, if its a variable or function that's not defined yet (and thus, is not "usable" at the moment) but is supposed to be setup later, I usually leave it undefined.
Generally speak I defined null as it indicates a human set the value and undefined to indicate no setting has taken place.
I usually set it to whatever I expect to be returned from the function.
If a string, than i will set it to an empty string ='', same for object ={} and array=[], integers = 0.
using this method saves me the need to check for null / undefined. my function will know how to handle string/array/object regardless of the result.
The only time you need to set it (or not) is if you need to explicitly check that a variable a is set exactly to null or undefined.
if(a === null) {
}
...is not the same as:
if(a === undefined) {
}
That said, a == null && a == undefined will return true.
Fiddle
Be careful if you use this value to assign some object's property and call JSON.stringify later* - nulls will remain, but undefined properties will be omited, as in example below:
var a, b = null;
c = {a, b};
console.log(c);
console.log(JSON.stringify(c)) // a omited
*or some utility function/library that works in similar way or uses JSON.stringify underneath
There are two features of null we should understand:
null is an empty or non-existent value.
null must be assigned.
You can assign null to a variable to denote that currently that variable does not have any value but it will have later on. A null means absence of a value.
example:-
let a = null;
console.log(a); //null
You can use ''; to declaring NULL variable in Javascript

How to check both defined and parameter passed with JavaScript?

I have that function:
function(stringsVar) {
var stringRes = stringsVar || localize_en;
if('window.'+stringsVar === undefined) {
stringRes = localize_en;
}
...
}
and doesn't work. That was like that actually:
function(stringsVar) {
var stringRes = stringsVar || localize_en;
}
that function can take a parameter or not and the code above is checking it correctly. Parameter of that function will be a variable. I want to add that ability to my function. It will check whether that variable is defined or not. If not there is a defined variable at system, localize_en, it will be assigned as default.
How can I correct my code. The second part of my code will be that functionality:
i.e stringsVar is localize_ar and it is not a defined variable (I define that kind of variables with var keyword)
if(window.localize_ar === undefined){
alert('yes');}
else {
alert('no');
}
I will add that functionality as parametric.
Any ideas?
PS: localize_en and something like that variables are object.
EDIT: I am working on JQuery localizer plugin => source code.
I call it as
$('html').localize('localize_' + tr);
However it can not understand it as an object, it works as if I do:
$('html').localize(localize_tr);
It changes it into a string maybe the problem lays on there?
You can use the square bracket notation to refer to object members whose name is stored in a variable, so you're probably looking for this:
if (window[stringsVar] === undefined) {
}
Furthermore, the || operator will return the first truthy; what happens if an object is passed as the first parameter? That's truthy, but you specifically want a string, so whilst the || operator looks cool, you might find the following more appropiate:
if (typeof stringVar !== "string") {
stringVar = "localize_en";
}
It also looks like you're getting confused when to use a string to refer to the object your targeting, and when not to.
When you going to be doing something like:
window[someVar]
someVar needs to be a string.
It is possible to pass an object by reference in JavaScript, and after writing all the above to help you fix the problem you've currently got, a better approach will be to pass the object by reference in the first place and avoid the problem completely, rather than passing the name of the variable storing the object:
function(obj) {
if (typeof obj !== "object") {
obj = localize_en; // here we're wanting the object itself, rather than the name of the object, so we're not using a string.
};
// Now use `obj`. It'll be either the object the user passed, or the default (localize_en).
// You can even store this in a global variable if you want to:
window.selected_obj = obj;
}
Edit:
From your comment, try this:
function (stringsVar) {
if (typeof stringsVar !== "string" || typeof window[stringsVar] !== "object") {
stringsVar = "localize_en"; // Set the default of the argument, if either none is provided, or it isn't a string, or it doesn't point to a valid object
}
var stringRes = window[stringsVar];
// Now do *whatever* you want with stringRes. It will either be the *valid* localization type the parameter specified, or the default ("localize_en").
}
You should pass this function a string.

Categories