Empty value for int property - javascript

I got the following class:
function Corpus(name){
this.name=name; // A string
this.recordings = []; // An array to fill
this.num = ... ; // A int number to set later
}
What is the best default value for my int value (num), when it is not defined ?

The best value candidate for a number is 0, so that the typed is predefined, but the value unknown.
This is because JavaScript has internal types, even though it seems weakly typed at our level.
More generally for different types:
String: ''
Object: null
Array: null
RegExp: null
As a side note, it is totally legit to leave it undefined as said in Shomz's answer of your question. It is up to you from here :)

Depends what you want to do with it. It's perfectly fine to leave it undefined, to set it to false, and if you plan to do some math with it, you can always set it to zero (0).
Note that all of the above values are falsy, so the loose typing in JS make it matter even less.
If you want to easily check whether it's been defined or not, then leave it undefined or false, but don't forget to compare by value AND type later to avoid errors:
this.num = false;
this.num == 0; // true - be careful with this
this.num === 0; // false - the way to go

Related

! operator in Javascript - use cases

I'm just starting to learn Javascript, and am using this reference: https://www.discovermeteor.com/blog/javascript-for-meteor/
There's an interesting commentary that I can't get my head around. I quote below.
An interesting consequence of the ! operator is that it always returns a boolean value, even if what comes after is not a boolean:
a = 12;
!a; // false
This means that if you want to convert a variable to boolean you can just use the ! operator twice (once to force the variable to boolean, a second time to revert the value back):
a = 12;
!!a; // true
Or:
a = 0;
!!a; // false
Can anyone help me makes sense of the wording?
Is it simply trying to say that any integer other than 0 gets assigned a Boolean value of True, and that you can return a Boolean value of True/False by using "!" and "!!" respectively?
Yes, !!something is a way to convert something into a boolean (essentially finding out whether something is truthy). 0 and NaN are the only number values that would convert to false with the !! operator (or Boolean() call). All other numbers will be true.
Similarly, +something is a way to convert something into a number.
I usually prefer the more explicit approach: Boolean(something) and Number(something).

By Default, What Is A JavaScript Variables's Boolean Value?

I am writing a script the utilizes a switch statement. When I declare the variables, they have a default boolean value of true, correct? Well, not so much when being utilized in a switch statement.
Here is the JavaScript I have: http://codepen.io/anon/pen/IDLqd/
Basically, what I am trying to do is ask the user what type of list-style they prefer based upon that data that is entered into a window.prompt() method. If they enter in a 1, 2, or 3, they will get a list based upon the directions in the prompt. But, if they do not enter in a valid integer, the variable validInput is set with a boolean value of false.
From here, an if statement is ran to check whether the validInput variable has a boolean value of true, if it does, then it outputs the values of the many variables to the screen, if not, it outputs text saying "Invalid Choice".
Why is it that the code will recognize validInput as only having a value of false in the if statement? When it is only assigned the value of false if a different value is entered into the prompt window? To get this program to run properly I have to explicitly define the validInput value as true in each switch case.
Why is this? Can someone explain, please?
Thank you!
Aaron
Javascript is a dynamic language and there is nothing like a default boolean value.
When you define a variable without a value it's default value is always undefined:
var variable; // variable is undefined
So you have to set the value:
var variable = true;
// or
var variable = false;
If you want to toggle this boolean value, you can do the following:
variable = !variable;
You are checking if the input is valid with
if (validInput == true) {
// Your code
}
The more common way of doing this would be
if (validInput) {
// Your code
}
What's the difference between these two?
The first checks if validInput is equal to true - nothing else will do (well, pretty much nothing else - you're using == rather than ===, which can sometimes have surprising results because of javascript's type conversion algorithm, but that's another question altogether).
To understand the second, you need to understand javascript's concept of "truthiness". If you put a value into the condition of an if statement, then javascript decides is it's "truth-y" or "false-y", and acts accordingly.
true is truthy, as is any non-zero number, any non-empty string, and any object. Other things are falsey, including false, 0, "", null and undefined.
The last of these is probably the most relevant to you, as variables are undefined until you set them to something.

Javascript Coding Practices: Empty Values in Objects

Just read this highly-related question, and then reflected on what I was using in my own code base for a project at work.
I wrote a simple function to demonstrate this question (using Google Apps Script, thus the calls to Logger.log()):
function emptyValueTest() {
var object = {
prop1: "real_data",
prop2: "",
prop3: undefined,
prop4: null
}
// What I have used in my code personally. All evaluate to TRUE
if (object.prop2 === "") Logger.log("prop2 was empty");
if (typeof object.prop3 === "undefined") Logger.log("prop3 was undefined");
if (object.prop4 === null) Logger.log("prop4 was null");
// The other solution I've seen. All evaluate to FALSE
if (object.prop2) Logger.log("prop2 was empty");
if (object.prop3) Logger.log("prop3 was undefined");
if (object.prop4) Logger.log("prop4 was null");
}
I've been building a system for the past few months with thousands of lines of code, and I often find myself back-tracking when I see a particular value, to remember what it's previous state was before a particular conditional expression.
Since I'm the one writing the code it isn't too difficult for me to figure it out, because I know the structure of the data, the values that are supposed to be there, etc.
However, this system will be taken over by another developer after I graduate from my university, so I wonder what the best practice is for representing that a property has no data.
For example, my use case is that I have event Objects which are initialized with empty data and, during the lifetime of a semester, are eventually filled with real data. Personally I use undefined because it makes more sense to me to read if (typeof data === "undefined"), having a similar semantic meaning to "if this data is undefined" (i.e. no value yet).
But I wonder, in industry, in libraries, and in personal projects, what are commonly-used methods to make code more readable, understandable? Though the length of the first three conditionals is longer than the latter three, I find the latter three to be ambiguous.
For example, prop2 could have a non-empty string like "data", or the value true, which would cause the latter conditional if (object.prop2) to evaluate to true in both cases, because everything in JavaScript is truthy except the following:
null
undefined
NaN
empty string ("")
0
false
And it is entirely possible that data could have "", 0, and false as valid values, whereas null, undefined and (especially) NaN are probably not typical values for real data.
Obviously I we know the structure of the data then we might impose more strict checks to disambiguate non-empty strings from true. But in a project with thousands of lines of code it seems to me that this gets out of hand fast, especially if the structure of the data changes over time.
So my question: Is there a preferred method of representing empty values in Javascript? And is there a particular reason for the preference (performance, readability, scalability, etc.)?
Javascript is especially insidious in the NaN constant:
alert(NaN==NaN?"isNaN":"isNotNaN"); // isNotNaN !
The most common way to represent empty object is the null constant. However, you can run into troubles using it:
var coords = null;
if(coords===null) alert("empty object");
if(coords.x==0 && coords.y==0) alert("[0,0]");
// Uncaught TypeError: Cannot read property 'x' of null
There is a design pattern called Null object: to create an object representing null value with correct properties:
var nullcoords = {x:-1,y:-1}; // null object
var coords = nullcoords;
if(coords===nullcoords) alert("empty coords");
if(coords.x==0 && coords.y==0) alert("[0,0]");
// no TypeError
As RobG points in the comment, you can afford this attitude iff
the nullobject default properties are not valid values
the default values don't spoil you operations
However, null is not a good idea for coords properties since it is not a numeric type and can mess some arithmetic operations (not in JS, though). The below code is more appropriate (and more sophisticated) solution with custom null object handler:
function nullCoordsHandler(obj) {
// any error handling you want
alert("setting default values...");
obj.x = obj.y = 0;
}
function coords() {
var _x, _y;
var defined = false;
Object.defineProperty(this,"x",{
enumerable: true,
get:function() { if(!defined) nullCoordsHandler(this); return _x; },
set:function(value) { defined = true; _x = value; }
});
Object.defineProperty(this,"y",{
enumerable: true,
get:function() { if(!defined) nullCoordsHandler(this); return _y; },
set:function(value) { defined = true; _y = value; }
});
};
var c = new coords();
if(c.x==0 && c.y==0) alert("[0,0]");
// nullCoordsHandler was called to handle the null object situation

Falsey values in JavaScript

I had an interesting interview question today that stumped me a little. I was asked about falsey values. So undefined, NaN, null, 0, and an empty string all evaluate to false. What is the reason this is useful to know in JavaScript? The only thing I can think of is instead of having to do this:
if (mystring === '' || mystring === undefined) { }
I can do this:
if (!mystring)
Is this the only useful application?
One dangerous issue of falsey values you have to be aware of is when checking the presence of a certain property.
Suppose you want to test for the availability of a new property; when this property can actually have a value of 0 or "", you can't simply check for its availability using
if (!someObject.someProperty)
/* incorrectly assume that someProperty is unavailable */
In this case, you must check for it being really present or not:
if (typeof someObject.someProperty == "undefined")
/* now it's really not available */
Also be aware that NaN isn't equal to anything, even not to itself (NaN != NaN).
There are two separate issues with 'falsey' values in JavaScript.
Firstly there is the official conversion scheme, which is what is returned by Boolean(x). This returns false when x is false or 0 or NaN or null or undefined or "" and true otherwise. This is the same behaviour as the
if (condition) {/*true path*/} else {/*false path*/}
that is, the false path is executed if Boolean(condition) would have returned false and the true path is executed otherwise. This behaviour is often used to check to see if a property is defined. However, doing that is not safe unless you are certain that the property would be an object or an array if it is defined. The safest way to test if a property is defined is to do
if (property != null) { /*property is defined*/}
which makes sure that the property is not null or undefined. If you only want to make sure the property is not undefined do
if (property !== undefined) { /*property is not undefined (but may be null)*/ }
(notice the extra = in !==).
Secondly, there are all the values that == false. This is everything that can be coerced to 0 (which is what false gets coerced to). This includes all the values that convert to false except NaN (which can't == false by virtue of it never == anything), null and undefined. But it also includes all objects that when converted to a string and then converted to a number are equal to 0. For example, this includes everything that when converted to a string is either the empty string "" or "0" or "-0" or "+0" or "0x00" or "000" or "0e0" or "0.0000"...., for example,
({toString: function() {return "-00.0e000";}}) == false
is true. Interestingly, this includes the empty array, and any nesting of arrays containing only a single other item that returns an empty or 0 string since arrays rendered as strings show only the contents without the surrounding brackets. That is,
[[[[0]]]] == false; // Because [[[[0]]]].toString() === "0"
[] == false;
[[[""]]] == false;
["0"] == false;
[[({toString: function() {return "0";}})]] == false;
The full algorithm for calculating == false is described here.
The reason this matters is because it can lead to subtle, difficult to find bugs if you don't understand most of these rules. Most important takeaways are probably how the if (condition) works and that using === avoids most of the other crazy stuff.
It's important to understand how this works in JS, so you're not surprised. Not necessarily just what is falsey, but what is truthy and how they compare to each other.
One example is that '0' is considered equal to 0 with ==, but it is not equal to '' - though 0 is. JavaScript comparison isn't always transitive.
So this means that just because (foo==bar && bar==fizz) is true, (foo==fizz) is not always true. To go with the above example, '0'==0, and 0=='', but '0'!='' - because you're comparing strings in the latter instance, so they are compared as strings and not coerced to numbers.
It is important to know that 0 evaluates to false to prevent doing things like:
if(str.indexOf('foo'))
It's useful to detect if a browser is has specific predefined objects:
if(!!navigator.geolocation){
// executes if the browser has geolocation support
}
if(!!document.createElement('canvas').getContext){
// executes if the browser supports <canvas>
}
Explanation: navigator.geolocation is an object or undefined. In the case it's an object !navigator.geolocation will return false, if it's undefined it'll return true. So, to check if a browser has geolocation enabled, you want to 'flip' the boolean once more, by adding another !.
They're also useful for setting default values...
function foo(bar){
alert(bar || "default");
}
I know a lot of people try to do
if (typeof(foo) === "undefined"){}
to get around falsiness, but that's got its own problems because
typeof(null) === "object"
for some reason

What is the purpose of new Boolean() in Javascript?

What is the use of:
var flag = new Boolean(false);
compared to:
var flag = false;
When would you actually use new Boolean?
The global function Boolean() can be used for type casting when called without new, eg
var foo = Boolean(bar); // equivalent to `var foo = !!bar`
When called with new, a wrapper object will be created additionally, which means that you can assign arbitrary properties to the object:
var foo = new Boolean(bar); // equivalent to `var foo = Object(Boolean(bar));`
foo.baz = 'quux';
alert(foo.baz);
This is not possible with primitive values as primitives can't hold properties:
var foo = true;
foo.baz = 'quux';
alert(foo.baz); // `foo.baz` is `undefined`
Assigning a property to a primitive doesn't produce an error because of auto-boxing, ie
foo.baz = 'quux';
will be interpreted as
// create and immediately discard a wrapper object:
(new Boolean(foo)).baz = 'quux';
To get the primitive value back, you'll have to invoke the valueOf() method. This is needed if you want to actually use the wrapped value, because objects always evaluate to true in boolean contexts - even if the wrapped value is false.
I've never come across a useful application of being able to assign properties to booleans, but boxing might be useful in cases where a reference to a primitive value is needed.
While others mentioned the theory, let me talk about the practical part:
Because Boolean objects (as objects in general) are always truthy, it is considered bad practice to use them. In many years of JS programming, I have never used them, and I can't remember seeing Booleans in other peoples' code either. Not even once.
Using primitive values will avoid confusion and will make your code a little bit shorter.
If you ever need a bool wrapped in an object, you might as well use an Object object like so:
foo = { value: false };
Also, calling the Boolean() constructor as a function (as in foo = Boolean(bar)) has the same effect as explicit typecasting using !!, and the latter is generally preferred over the former.
Before the above question first the Boolean function, Boolean ()
Boolean(10 > 4) // return true
Boolean(4 > 9) // return false
Next: everything with real value return true. E.g
100
-4
4.4
"hello"
"false" // note even the string value false return true.
everthing without real value return false E.g
NaN
var x = 10 / "H"; // Boolean(x); return false.
undefined
""
0
-0
false
null
Now the Boolean object is an object wrapper for a boolean value. The value passed as the first parameter is converted to a boolean value, if necessary. If value is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false. All other values, including any object or the string "false", create an object with an initial value of true.
This allows very powerful tricks.
Interesting question:
You use new Boolean to create a boolean object. There can be many scenarios but I have discussed below one scenario.
Suppose you want a comparison in your code where you want to match string value and its datatype and it has to bool (true/false) then you will use new boolean instead of assigning simple false value.
var flag = false;
var flag2 = new Boolean (false);
alert(typeof flag); //boolean object
alert(typeof flag2); //simple object
if (flag === flag2){
alert("Value and datatype match");
}
else{
alert("Value and datatype do not match");
}

Categories