"||" operator is not working when assigning value to a variable - javascript

What is wrong with this code?
var sha = 6;
var secondParameter = dan || sha;
alert(secondParameter);
I tried it with many browsers. No alert.
If I add var dan like this:
var sha = 6;
var dan = 5;
var secondParameter = dan || sha;
alert(secondParameter);
the alert will happen. So the problem in "||". I saw many codes where it use the operator like this! So I have no idea..

You don't have the dan defined. Execution stops at that error. Check the browser console for errors.
When you define dan, execution continues, but that's probably not what you want.
The purpose of such code in JavaScript is to say if dan has a falsy value (any value that evaluates to a false value, i.e. 0, '', null, false, undefined, or NaN), then use the value of sha.
IF defining dan is beyond your responsibility, (i.e some other script should have set it), then you can check for its existence using a construct like follows:
secondParameter = typeof(dan) == 'undefined' ? sha : dan;
(Not tested, hopefully it works. :) anyways, it should give you an idea)
Check here for documentation on logical operators.
Also, this question might give you more insight: Javascript || or operator with a undefinded variable

var sha = 6;
var dan = null;
var secondParameter = dan || sha;
alert(secondParameter);
Try this. You can coalesce using the || operator, but all variables have to be declared in order to be referenced

This is used in a situation where it is given as something like a parameter but isn't assigned a value or it is falsy
falsy being 0, false, null or undefined
For example:
var sha = 6;
var dan = undefined;
var secondParameter = dan || sha;
alert(secondParameter);
You will get 6
A good example to use this would be something like this:
function funcWithCallback(callback){
callback = callback || function(){};
callback();
}
In this example if callback is undefined (or falsy) then set callback as a new instance of a function
Using it in a situation like this will ensure no error

There is a difference in how JavaScript handles undeclared variables (undefined variable) and undefined values. In the following example the variable dan is declared but never set so it's value is undefined the || returns the first true value it can find so if I pass anything but an empty string, 0, false, NaN, undefined or NULL it'll console.log the passed value. Else it'll log "default value".
function test(dan){
console.log(dan || "default value");
return dan===undefined;
}
console.log(test());//default value, then true
console.log(test(22));//22 then false
A more robust way of checking if a variable was passed would be to see if the variable's value is undefined:
function test(dan){
dan = (typeof(dan)==='undefined')?"default value":dan;
}
In your example the variable dan is not declared at all (variable is undefined), that's why you get error "dan is not defined" because dan is not declared at all.
function test(){
return dan===undefined;//ReferenceError: dan is not defined
}
console.log(test());
You could change your code to this:
var sha = 6, dan;//dan is declared here but no value is set
var secondParameter = dan || sha;
console.log(dan===undefined);//true
console.log(secondParameter);//6
If you want to check if a certain object has a property then it'll not throw an error:
function test(){
return window.neverSetOrDeclared===undefined;
}
console.log(test());//true
It will throw an error when you try to check a property of undefined or null:
null.something//throws error
undefined.something//throws error
window.neverSetOrDeclared===undefined//throws error

Explanation: the way this || works is : if first condition is false then it checks second condition. So in order to display second parameter, you'll have to make first parameter null.

Related

Check if value is assigned [duplicate]

Which method of checking if a variable has been initialized is better/correct?
(Assuming the variable could hold anything (string, int, object, function, etc.))
if (elem) { // or !elem
or
if (typeof elem !== 'undefined') {
or
if (elem != null) {
You want the typeof operator. Specifically:
if (typeof variable !== 'undefined') {
// the variable is defined
}
The typeof operator will check if the variable is really undefined.
if (typeof variable === 'undefined') {
// variable is undefined
}
The typeof operator, unlike the other operators, doesn't throw a ReferenceError exception when used with an undeclared variable.
However, do note that typeof null will return "object". We have to be careful to avoid the mistake of initializing a variable to null. To be safe, this is what we could use instead:
if (typeof variable === 'undefined' || variable === null) {
// variable is undefined or null
}
For more info on using strict comparison === instead of simple equality ==, see:Which equals operator (== vs ===) should be used in JavaScript comparisons?
In many cases, using:
if (elem) { // or !elem
will do the job for you!... this will check these below cases:
undefined: if the value is not defined and it's undefined
null: if it's null, for example, if a DOM element not exists...
empty string: ''
0: number zero
NaN: not a number
false
So it will cover off kind of all cases, but there are always weird cases which we'd like to cover as well, for example, a string with spaces, like this ' ' one, this will be defined in javascript as it has spaces inside string... for example in this case you add one more check using trim(), like:
if(elem) {
if(typeof elem === 'string' && elem.trim()) {
///
Also, these checks are for values only, as objects and arrays work differently in Javascript, empty array [] and empty object {} are always true.
I create the image below to show a quick brief of the answer:
In JavaScript, a variable can be defined, but hold the value undefined, so the most common answer is not technically correct, and instead performs the following:
if (typeof v === "undefined") {
// no variable "v" is defined in the current scope
// *or* some variable v exists and has been assigned the value undefined
} else {
// some variable (global or local) "v" is defined in the current scope
// *and* it contains a value other than undefined
}
That may suffice for your purposes. The following test has simpler semantics, which makes it easier to precisely describe your code's behavior and understand it yourself (if you care about such things):
if ("v" in window) {
// global variable v is defined
} else {
// global variable v is not defined
}
This, of course, assumes you are running in a browser (where window is a name for the global object). But if you're mucking around with globals like this you're probably in a browser. Subjectively, using 'name' in window is stylistically consistent with using window.name to refer to globals. Accessing globals as properties of window rather than as variables allows you to minimize the number of undeclared variables you reference in your code (for the benefit of linting), and avoids the possibility of your global being shadowed by a local variable. Also, if globals make your skin crawl you might feel more comfortable touching them only with this relatively long stick.
In the majority of cases you would use:
elem != null
Unlike a simple if (elem), it allows 0, false, NaN and '', but rejects null or undefined, making it a good, general test for the presence of an argument, or property of an object.
The other checks are not incorrect either, they just have different uses:
if (elem): can be used if elem is guaranteed to be an object, or if false, 0, etc. are considered "default" values (hence equivalent to undefined or null).
typeof elem == 'undefined' can be used in cases where a specified null has a distinct meaning to an uninitialised variable or property.
This is the only check that won't throw an error if elem is not declared (i.e. no var statement, not a property of window, or not a function argument). This is, in my opinion, rather dangerous as it allows typos to slip by unnoticed. To avoid this, see the below method.
Also useful is a strict comparison against undefined:
if (elem === undefined) ...
However, because the global undefined can be overridden with another value, it is best to declare the variable undefined in the current scope before using it:
var undefined; // really undefined
if (elem === undefined) ...
Or:
(function (undefined) {
if (elem === undefined) ...
})();
A secondary advantage of this method is that JS minifiers can reduce the undefined variable to a single character, saving you a few bytes every time.
Check if window.hasOwnProperty("varname")
An alternative to the plethora of typeof answers;
Global variables declared with a var varname = value; statement in the global scope
can be accessed as properties of the window object.
As such, the hasOwnProperty() method, which
returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it)
can be used to determine whether
a var of "varname" has been declared globally i.e. is a property of the window.
// Globally established, therefore, properties of window
var foo = "whatever", // string
bar = false, // bool
baz; // undefined
// window.qux does not exist
console.log( [
window.hasOwnProperty( "foo" ), // true
window.hasOwnProperty( "bar" ), // true
window.hasOwnProperty( "baz" ), // true
window.hasOwnProperty( "qux" ) // false
] );
What's great about hasOwnProperty() is that in calling it, we don't use a variable that might as yet be undeclared - which of course is half the problem in the first place.
Although not always the perfect or ideal solution, in certain circumstances, it's just the job!
Notes
The above is true when using var to define a variable, as opposed to let which:
declares a block scope local variable, optionally initializing it to a value.
is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
At the top level of programs and functions, let, unlike var, does not create a property on the global object.
For completeness: const constants are, by definition, not actually variable (although their content can be); more relevantly:
Global constants do not become properties of the window object, unlike var variables. An initializer for a constant is required; that is, you must specify its value in the same statement in which it's declared.
The value of a constant cannot change through reassignment, and it can't be redeclared.
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.
Since let variables or const constants are never properties of any object which has inherited the hasOwnProperty() method, it cannot be used to check for their existence.
Regarding the availability and use of hasOwnProperty():
Every object descended from Object inherits the hasOwnProperty() method. [...] unlike the in operator, this method does not check down the object's prototype chain.
How to check if a variable exists
This is a pretty bulletproof solution for testing if a variable exists and has been initialized :
var setOrNot = typeof variable !== typeof undefined;
It is most commonly used in combination with a ternary operator to set a default in case a certain variable has not been initialized :
var dark = typeof darkColor !== typeof undefined ? darkColor : "black";
Problems with encapsulation
Unfortunately, you cannot simply encapsulate your check in a function.
You might think of doing something like this :
function isset(variable) {
return typeof variable !== typeof undefined;
}
However, this will produce a reference error if you're calling eg. isset(foo) and variable foo has not been defined, because you cannot pass along a non-existing variable to a function :
Uncaught ReferenceError: foo is not defined
Testing whether function parameters are undefined
While our isset function cannot be used to test whether a variable exists or not (for reasons explained hereabove), it does allow us to test whether the parameters of a function are undefined :
var a = '5';
var test = function(x, y) {
console.log(isset(x));
console.log(isset(y));
};
test(a);
// OUTPUT :
// ------------
// TRUE
// FALSE
Even though no value for y is passed along to function test, our isset function works perfectly in this context, because y is known in function test as an undefined value.
Short way to test a variable is not declared (not undefined) is
if (typeof variable === "undefined") {
...
}
I found it useful for detecting script running outside a browser (not having declared window variable).
There is another short hand way to check this, when you perform simple assignments and related checks. Simply use Conditional (Ternary) Operator.
var values = typeof variable !== 'undefined' ? variable : '';
Also this will be helpful, when you try to declare the Global variable with instance assignment of the reference variable.
If you wanted to check variable shouldn't be undefined or null. Then perform below check.
When the variable is declared, and if you want to check the value, this is even Simple: and it would perform undefined and null checks together.
var values = variable ? variable : '';
It depends if you just care that the variable has been defined or if you want it to have a meaningful value.
Checking if the type is undefined will check if the variable has been defined yet.
=== null or !== null will only check if the value of the variable is exactly null.
== null or != null will check if the value is undefined or null.
if(value) will check if the variable is undefined, null, 0, or an empty string.
Try-catch
If variable was not defined at all (for instance: external library which define global variable is not yet loaded - e.g. google maps), you can check this without break code execution using try-catch block as follows (you don't need to use strict mode)
try{
notDefinedVariable;
} catch(e) {
console.log('detected: variable not exists');
}
console.log('but the code is still executed');
notDefinedVariable; // without try-catch wrapper code stops here
console.log('code execution stops. You will NOT see this message on console');
BONUS: (referring to other answers) Why === is more clear than == (source)
if( a == b )
if( a === b )
The highest answer is correct, use typeof.
However, what I wanted to point out was that in JavaScript undefined is mutable (for some ungodly reason). So simply doing a check for varName !== undefined has the potential to not always return as you expect it to, because other libs could have changed undefined. A few answers (#skalee's, for one), seem to prefer not using typeof, and that could get one into trouble.
The "old" way to handle this was declaring undefined as a var to offset any potential muting/over-riding of undefined. However, the best way is still to use typeof because it will ignore any overriding of undefined from other code. Especially if you are writing code for use in the wild where who knows what else could be running on the page...
if (typeof console != "undefined") {
...
}
Or better
if ((typeof console == "object") && (typeof console.profile == "function")) {
console.profile(f.constructor);
}
Works in all browsers
To contribute to the debate, if I know the variable should be a string or an object I always prefer if (!variable), so checking if its falsy. This can bring to more clean code so that, for example:
if (typeof data !== "undefined" && typeof data.url === "undefined") {
var message = 'Error receiving response';
if (typeof data.error !== "undefined") {
message = data.error;
} else if (typeof data.message !== "undefined") {
message = data.message;
}
alert(message);
}
..could be reduced to:
if (data && !data.url) {
var message = data.error || data.message || 'Error receiving response';
alert(message)
}
To check if a variable has been declared/set I did this dirty trick.
I haven't found a way to extract the code to a function, even with eval. Se this comment below for an explanation about why.
"use strict";
// var someVar;
var declared;
try {
someVar;
declared = true;
} catch(e) {
declared = false;
}
if (declared) {
console.log("someVar is declared; now has the value: " + someVar);
} else {
console.log("someVar is not declared");
}
The most robust 'is it defined' check is with typeof
if (typeof elem === 'undefined')
If you are just checking for a defined variable to assign a default, for an easy to read one liner
you can often do this:
elem = elem || defaultElem;
It's often fine to use, see: Idiomatic way to set default value in javascript
There is also this one liner using the typeof keyword:
elem = (typeof elem === 'undefined') ? defaultElem : elem;
Null is a value in JavaScript and typeof null returns "object"
Therefore, accepted answer will not work if you pass null values. If you pass null values, you need to add an extra check for null values:
if ((typeof variable !== "undefined") && (variable !== null))
{
// the variable is defined and not null
}
In the particular situation outlined in the question,
typeof window.console === "undefined"
is identical to
window.console === undefined
I prefer the latter since it's shorter.
Please note that we look up for console only in global scope (which is a window object in all browsers). In this particular situation it's desirable. We don't want console defined elsewhere.
#BrianKelley in his great answer explains technical details. I've only added lacking conclusion and digested it into something easier to read.
It is difficult to distinguish between undefined and null. Null is a value you can assign to a variable when you want to indicate that the variable has no particular value. Undefined
is a special value which will be the default value of unassigned variables.
var _undefined;
var _null = null;
alert(_undefined);
alert(_null);
alert(_undefined == _null);
alert(_undefined === _null);
you can use the typeof operator.
For example,
var dataSet;
alert("Variable dataSet is : " + typeof dataSet);
Above code snippet will return the output like
variable dataSet is : undefined.
I use two different ways depending on the object.
if( !variable ){
// variable is either
// 1. '';
// 2. 0;
// 3. undefined;
// 4. null;
// 5. false;
}
Sometimes I do not want to evaluate an empty string as falsey, so then I use this case
function invalid( item ){
return (item === undefined || item === null);
}
if( invalid( variable )){
// only here if null or undefined;
}
If you need the opposite, then in the first instance !variable becomes !!variable, and in the invalid function === become != and the function names changes to notInvalid.
My preference is typeof(elem) != 'undefined' && elem != null.
However you choose, consider putting the check in a function like so
function existy (x) {
return typeof (x) != 'undefined' && x != null;
}
If you don't know the variable is declared then continue with typeof (x) != 'undefined' && x != null;
Where you know the variable is declared but may not be existy, you could use
existy(elem) && doSomething(elem);
The variable you are checking may be a nested property sometimes. You can use prop || {} to go down the line checking existance to the property in question:
var exists = ((((existy(myObj).prop1||{}).prop2||{}).prop3||{})[1]||{}).prop4;
After each property use (...' || {}').nextProp so that a missing property won't throw an error.
Or you could use existy like existy(o) && existy(o.p) && existy(o.p.q) && doSomething(o.p.q)
These answers (aside from the Fred Gandt solution ) are all either incorrect or incomplete.
Suppose I need my variableName; to carry an undefined value, and therefore it has been declared in a manner such as var variableName; which means it's already initialized; - How do I check if it's already declared?
Or even better - how do I immediately check if "Book1.chapter22.paragraph37" exists with a single call, but not rise a reference error?
We do it by using the most powerful JasvaScript operator, the in operator.:
"[variable||property]" in [context||root]
>> true||false
It depends on the situation. If you're checking for something that may or may not have been defined globally outside your code (like jQuery perhaps) you want:
if (typeof(jQuery) != "undefined")
(No need for strict equality there, typeof always returns a string.) But if you have arguments to a function that may or may not have been passed, they'll always be defined, but null if omitted.
function sayHello(name) {
if (name) return "Hello, " + name;
else return "Hello unknown person";
}
sayHello(); // => "Hello unknown person"
if (variable === undefined) {}
works just fine, and only checks for undefined.
You could use a try...catch block like the following:
var status = 'Variable exists'
try {
myVar
} catch (ReferenceError) {
status = 'Variable does not exist'
}
console.log(status)
A disadvantage is you cannot put it in a function as it would throw a ReferenceError
function variableExists(x) {
var status = true
try {
x
} catch (ReferenceError) {
status = false
}
return status
}
console.log(variableExists(x))
Edit:
If you were working in front-end Javascript and you needed to check if a variable was not initialized (var x = undefined would count as not initialized), you could use:
function globalVariableExists(variable) {
if (window[variable] != undefined) {
return true
}
return false
}
var x = undefined
console.log(globalVariableExists("x"))
console.log(globalVariableExists("y"))
var z = 123
console.log(globalVariableExists("z"))
Edit 2:
If you needed to check if a variable existed in the current scope, you could simply pass this to the function, along with the name of the variable contained in a string:
function variableExists(variable, thisObj) {
if (thisObj[variable] !== undefined) {
return true
}
return false
}
class someClass {
constructor(name) {
this.x = 99
this.y = 99
this.z = 99
this.v = 99
console.log(variableExists(name, this))
}
}
new someClass('x')
new someClass('y')
new someClass('z')
new someClass('v')
new someClass('doesNotExist')
I prefer this method for it's accuracy and succinctness:
var x
if (x === void 0) {
console.log(`x is undefined`)
} else {
console.log(`x is defined`)
}
As has been mentioned in other comments and answers, undefined isn't guaranteed to be undefined. Because it's not a keyword, it can be redefined as a variable in scopes other than the global scope. Here's little example that demonstrates this nuance:
var undefined = 'bar'
console.log(`In the global scope: ${undefined}`)
function foo() {
var undefined = 'defined'
var x
if (x === undefined) {
console.log(`x === undefined`)
} else {
console.log(`x !== undefined`)
}
if (x === void 0) {
console.log(`x === void 0`)
} else {
console.log(`x !== void 0`)
}
}
foo()
See void for compatibility (supported in IE5!?!! Wow!).
I'm surprised this wasn't mentioned yet...
here are a couple of additional variations using this['var_name']
the benefit of using this method that it can be used before a variable is defined.
if (this['elem']) {...}; // less safe than the res but works as long as you're note expecting a falsy value
if (this['elem'] !== undefined) {...}; // check if it's been declared
if (this['elem'] !== undefined && elem !== null) {...}; // check if it's not null, you can use just elem for the second part
// these will work even if you have an improper variable definition declared here
elem = null; // <-- no var here!! BAD!
In ReactJS, things are a bit more complicated! This is because it is a compiled environment, which follows ESLint's no-undef rule since react-scripts#2.0.3 (released Oct. 1st, 2018). The documentation here is helpful to anyone interested in this problem...
In JavaScript, prior to ES6, variable and function declarations are hoisted to the top of a scope, so it's possible to use identifiers before their formal declarations in code....
This [new] rule [of ES6] will warn when it encounters a reference to an identifier that has not yet been declared.
So, while it's possible to have an undefined (or "uninitialized") variable, it is not possible to have an undeclared variable in ReactJS without turning off the eslint rules.
This can be very frustrating -- there are so many projects on GitHub that simply take advantage of the pre-ES6 standards; and directly compiling these without any adjustments is basically impossible.
But, for ReactJS, you can use eval(). If you have an undeclared variable like...
if(undeclaredvar) {...}
You can simply rewrite this part as...
if(eval('typeof undeclaredvar !== "undefined"')) {...}
For instance...
if(eval("false")) {
console.log("NO!");
}
if(eval("true")) {
console.log("YEAH!");
}
For those importing GitHub repositories into a ReactJS project, this is simply the only way to check if a variable is declared. Before closing, I'd like to remind you that there are security issues with eval() if use incorrectly.
For the if condition to work correctly, we have to use the keyword let for creating variables.
let name = undefined;
if (name) {
alert('valid')
};

Meaning of || in javascript argument [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does “options = options || {}” mean in Javascript?
What is the meaning of the || in the second argument?
var obj = this;
var settings = $.extend({
param: 'defaultValue'
}, options || {});
Also would be nice if anyone knows how to search that character("|") here or in google! Thank you
That would be the logical OR. The statement will return the first truth-y value it finds.
In this case, if options is null (or any other value that isn't truth-y) it will evaluate to false. The || will then return the empty object.
That is some kind of fallback value or default value. So if the object is null or false the second value is used.
More importantly in that scenario, if options is not defined then an empty object {} is passed as an argument. Its kind of a side-effect use case of the logical OR operator. More specifically, it uses short circuiting. For example in the below case
a || b
if a is true then b never gets executed, but if a is false then b gets executed. Hence in the example you have shown, if options is not defined and thus false, then {} gets executed and thus passed as a parameter.
|| = or
As in the comparison operator.
|| = "OR". Example:
alert(false || false || false || "I'm valid!"); // alerts "I'm valid"
In your question, the example above demonstrates that the function requires an object for it's options. In this case, if the local variable "options" is not available, then just pass an empty object. Later, in the function that's being called, it's probably setting default values in that new object.

Best Way for Conditional Variable Assignment

Which is the better way for conditional variable assignment?
1st method
if (true) {
var myVariable = 'True';
} else {
var myVariable = 'False';
}
2nd Method
var myVariable = 'False';
if (true) {
myVariable = 'True';
}
I actually prefer 2nd one without any specific technical reason. What do you guys think?
try this
var myVariable = (true condition) ? "true" : "false"
There are two methods I know of that you can declare a variable's value by conditions.
Method 1: If the condition evaluates to true, the value on the left side of the column would be assigned to the variable. If the condition evaluates to false the condition on the right will be assigned to the variable. You can also nest many conditions into one statement.
var a = (true)? "true" : "false";
Nesting example of method 1: Change variable A value to 0, 1, 2 and a negative value to see how the statement would produce the result.
var a = 1;
var b = a > 0? (a === 1? "A is 1" : "A is not 1") : (a === 0? "A is zero" : "A is negative");
Method 2: In this method, if the value of the left of the || is equal to zero, false, null, undefined, or an empty string, then the value on the right will be assigned to the variable. If the value on the left of the || does not equal to zero, false, null undefined, or an empty string, then the value on the left will be assigned to the variable.
Although the value on the left can be an undefined value for JS to evaluate the condition but the variable has to be declared otherwise an exception will be produced.
var a = 0;
var b = a || "Another value";
An alternative way of doing this is by leveraging the ability of logical operators to return a value.
let isAnimal = false;
let isPlant = true;
let thing = isAnimal && 'animal' || isPlant && 'plant' || 'something else';
console.log(thing);
In the code above when one of the flags is true isAnimal or isPlant, the string next to it is returned. This is because both && and || result in the value of one of their operands:
A && B returns the value A if A can be coerced into false; otherwise, it returns B.
A || B returns the value A if A can be coerced into true; otherwise, it returns B.
Answer inspired by this article: https://mariusschulz.com/blog/the-and-and-or-operators-in-javascript
PS: Should be used for learning purposes only. Don't make life harder for you and your coworkers by using this method in your production code.
You could do a ternary, which is a lot shorter (and no darn curly braces):
var myVariable = (true) ? 'True' : 'False';
Another cool thing is that you can do multiple assignment based on a conditional:
let [long_str, short_str] = a.length > b.length ? [a, b] : [b, a]
Third way when you are storing only true false in variabel then use
var myVariable =(condition_written_in_if);
Just for completion, there is another way in addition to all the others mentioned here, which is to use a lookup table.
Say you have many possible values, you could declaratively configure a Map instead of using an if, switch or ternary statement.
Object map = {
key1: 'value1',
key2: 'value2,
keyX: 'valueX'
};
var myVariable = map[myInput];
This works even for booleans:
Object map = { true: 'value1', false: 'value2 };
var myVariable = map[myBoolean];
For booleans you would probably do it the 'normal' way though with logic operators specifically designed for that. Though sometimes it can be useful, such as:
portability: you can pass a map around
configurability: maybe the values come from a property file
readability: if you don't care it's a boolean or not, you just want to avoid conditional logic and reduce cognitive load that way
Note there is some overlap between the advantages using a lookup map and advantages of using a function variable (closure).
The first solution uses only one assignment instead of 1,5 by average in the second code snippet. On the other hand the first code snippet is less readable as people not familiar with JavaScript might not realize that the scope of a variable is not block oriented by function oriented - on other languages with C-like syntax myVariable would not be accessible outside if and else blocks.
In other words both solutions have disadvantages. What about ternary operator:
var myVariable = condition? 'True' : 'False';
or if you don't care about the camel-case (although I understand this is just an example, not a real code);
var myVariable = (!!condition).toString();
If you tired of ternary operator then use IIFE
Another way would be to use Immediately Invoked Function Expression. The good thing about it is that it can hold some logic and can be encapsulated from the outside world.
const direction = "n";
const directionFull= (() => {
switch(direction ){
case "n": return "north";
case "s": return "south";
case "w": return "west";
case "e": return "east";
}
})()
console.log(directionFull);
I would prefer 2nd option too, no technical reason but for the sake of easy to read code, readability is very important in code.
If you see the second option, from processing point of view only one check will ever be executed, saved some very minute processing time, so there is only one check in second case.
It depends on the use for me. If I have code that I only want to run if true, but with no extra code for false, I'll use the second. If I want to execute some code on true, and different on false, I use the first. It all depends on use, but the general rule for me is to write once. Keep it clean, keep it simple, and keep it short
Maybe you simply need && operator to check if boolean is true, if it is, assing "myVariable" to true.
var myVariable = 'False';
true && myVariable = 'True';
If all you need to do is convert a boolean to a string, you should do so explicitly:
var myBool = true;
var myVariable = myBool.toString(); // 'true'
// '' + myBool, ''.concat(myBool), etc. also work
If it's important that the first letter be capitalized, as in your example, that is not difficult to do; see e.g. this answer.
Another approach with Map and Object: (Maps are more flexible with key types and Objects are more readable IMHO)
const condition_var = 'e'
const options1 = new Map([ ['n','north'],['s','south'],['e','east'],['w','west']])
const myVar1 = options1.get(condition_var) || null
const options2 = {n:'north', s:'south', e:'east', w:'west'}
const myVar2 = options2[condition_var] || null
console.log(myVar1)
console.log(myVar2)

What reason is there to use null instead of undefined in JavaScript?

I've been writing JavaScript for quite a long time now, and I have never had a reason to use null. It seems that undefined is always preferable and serves the same purpose programmatically. What are some practical reasons to use null instead of undefined?
I don't really have an answer, but according to Nicholas C. Zakas, page 30 of his book "Professional JavaScript for Web Developers":
When defining a variable that is meant
to later hold an object, it is
advisable to initialize the variable
to null as opposed to anything else.
That way, you can explicitly check for the value null to determine if
the variable has been filled with an object reference at a later time
At the end of the day, because both null and undefined coerce to the same value (Boolean(undefined) === false && Boolean(null) === false), you can technically use either to get the job done. However, there is right way, IMO.
Leave the usage of undefined to the JavaScript compiler.
undefined is used to describe variables that do not point to a reference. It is something that the JS compiler will take care for you. At compile time the JS engine will set the value of all hoisted variables to undefined. As the engine steps through the code and values becomes available the engine will assign respective values to respective variables. For those variables for whom it did not find values, the variables would continue to maintain a reference to the primitive undefined.
Only use null if you explicitly want to denote the value of a variable as having "no value".
As #com2gz states: null is used to define something programmatically empty. undefined is meant to say that the reference is not existing. A null value has a defined reference to "nothing". If you are calling a non-existing property of an object, then you will get undefined. If I would make that property intentionally empty, then it must be null so you know that it's on purpose.
TLDR; Don't use the undefined primitive. It's a value that the JS compiler will automatically set for you when you declare variables without assignment or if you try to access properties of objects for which there is no reference. On the other hand, use null if and only if you intentionally want a variable to have "no value".
Sidebar: I, personally, avoid explicitly setting anything to undefined (and I haven't come across such a pattern in the many codebases/third party libs I've interacted with). Also, I rarely use null. The only times I use null is when I want to denote the value of an argument to a function as having no value, i.e.,:
function printArguments(a,b) {
console.log(a,b);
}
printArguments(null, " hello") // logs: null hello
null and undefined are essentially two different values that mean the same thing. The only difference is in the conventions of how you use them in your system. As some have mentioned, some people use null for meaning "no object" where you might sometimes get an object while undefined means that no object was expected (or that there was an error). My problem with that is its completely arbitrary, and totally unnecessary.
That said, there is one major difference - variables that aren't initialized (including function parameters where no argument was passed, among other things) are always undefined.
Which is why in my code I never use null unless something I don't control returns null (regex matching for example). The beauty of this is it simplifies things a lot. I never have to check if x === undefined || x === null, I can just check x === undefined. And if you're in the habit of using == or simply stuff like if(x) ... , stop it.
!x will evaluate to true for an empty string, 0, null, NaN - i.e. things you probably don't want. If you want to write javascript that isn't awful, always use triple equals === and never use null (use undefined instead). It'll make your life way easier.
undefined is where no notion of the thing exists; it has no type, and it's never been referenced before in that scope; null is where the thing is known to exist, but it has no value.
Everyone has their own way of coding and their own internal semantics, but over the years I have found this to be the most intuitive advice that I give people who ask this question: when in doubt, do what JavaScript does.
Let's say you are working with object properties like options for a jQuery plugin...ask yourself what value JavaScript gives a property that has yet to be defined -- the answer is undefined. So in this context, I would initialize these types of things with 'undefined' to be consistent with JavaScript (for variables, you can do var myVar; instead of var myVar = undefined;).
Now let's say you are doing DOM manipulation...what value does JavaScript assign to non-existent elements? The answer is null. This is the value I would initialize with if you are creating a placeholder variable that will later hold a reference to an element, document fragment, or similar that relates to the DOM.
If you're working with JSON, then a special case needs to be made: for undefined property values, you should either set them to "" or null because a value of undefined is not considered proper JSON format.
With this said, as a previous poster has expressed, if you find that you're initializing stuff with null or undefined more than once in a blue moon, then maybe you should reconsider how you go about coding your app.
You might adopt the convention suggested here, but there really is no good reason to. It is not used consistently enough to be meaningful.
In order to make the convention useful, you first must know that the called function follows the convention. Then you have to explicitly test the returned value and decide what to do. If you get undefined, you can assume that some kind of error occurred that the called function knew about. But if an error happened, and the function knew about it, and it is useful to send that out into the wider environment, why not use an error object? i.e. throw an error?
So at the end of the day, the convention is practically useless in anything other than very small programs in simple environments.
A few have said that it is ok to initialise objects to null. I just wanted to point out that destructuring argument defaults don't work with null. For example:
const test = ({ name } = {}) => {
console.log(name)
}
test() // logs undefined
test(null) // throws error
This requires performing null checks prior to calling the function which may happen often.
A useful property in null that undefined does not qualifies:
> null + 3
3
> undefined + 3
NaN
I use null when I want to 'turn off' a numeric value,
or to initialize some. My last use was manipulating css transform:
const transforms = { perspective : null, rotateX : null };
// if already set, increase, if not, set to x
runTimeFunction((x) => { trasforms.perspective += x; });
// still useful, as setting perspective to 0 is different than turning it off
runTimeFunction2((x) => { transforms.perspective = null; });
// toCss will check for 'null' values and not set then at all
runTimeFunction3(() => { el.style.transform = toCss(transforms); });
Not sure if I should use this property thought...
DOM nodes and elements are not undefined, but may be null.
The nextSibling of the last child of an element is null.
The previousSibling of the first child is null.
A document.getElementById reference is null if the element does not exist in the document.
But in none of these cases is the value undefined; there just is no node there.
Unknown variable: undefined.
Known variable yet no value: null.
You receive an object from a server, server_object.
You reference server_object.errj. It tells you it’s undefined. That means it doesn’t know what that is.
Now you reference server_object.err. It tells you it’s null. That means you’re referencing a correct variable but it’s empty; therefore no error.
The problem is when you declare a variable name without a value (var hello) js declares that as undefined: this variable doesn’t exist; whereas programmers mostly mean: “I’ve not given it a value yet”, the definition of null.
So the default behavior of a programmer—declaring a variable without a value as nothing—is at odds with js—declaring it as not existing. And besides, !undefined and !null are both true so most programmers treat them as equivalent.
You could of course ensure you always do var hello = null but most won’t litter their code as such to ensure type sanity in a deliberately loosely-typed language, when they and the ! operator treat both undefined and null as equivalent.
In JavaScript, the value null represents the intentional absence of any object value. null expresses a lack of identification, indicating that a variable points to no object.
The global undefined property represents the primitive value undefined.
undefined is a primitive value automatically assigned to variables.
undefined is meant to say that the reference is not existing.
I completely disagree that usage null or undefined is unnecessary.
undefined is thing which keeping alive whole prototype chaining process.
So compiler only with null can't check if this property just equal to null, or its not defined in endpoint prototype. In other dynamic typed languages(f.e. Python) it throws exception if you want access to not defined property, but for prototype-based languages compiler should also check parent prototypes and here are the place when undefined need most.
Whole meaning of using null is just bind variable or property with object which is singleton and have meaning of emptiness,and also null usage have performance purposes. This 2 code have difference execution time.
var p1 = function(){this.value = 1};
var big_array = new Array(100000000).fill(1).map((x, index)=>{
p = new p1();
if(index > 50000000){
p.x = "some_string";
}
return p;
});
big_array.reduce((sum, p)=> sum + p.value, 0)
var p2 = function(){this.value = 1, p.x = null};
var big_array = new Array(100000000).fill(1).map((x, index)=>{
p = new p2();
if(index > 50000000){
p.x = "some_string";
}
return p;
});
big_array.reduce((sum, p)=> sum + p.value, 0)
I'm working through this exact question right now, and looking at the following philosophy:
Any function that is intended to return a result should return null if it fails to find a result
Any function that is NOT intended to return a result implicitly returns undefined.
For me, this question is significant because anyone calling a function that returns a result should have no question as to whether to test for undefined vs null.
This answer does not attempt to address:
Property values of null vs undefined
Variables within your functions being null vs undefined
In my opinion, variables are your own business and not a part of your API, and properties in any OO system are defined and therefore should be defined with value different from what they would be if not defined (null for defined, undefined is what you get when accessing something that is not in your object).
Here's a reason: var undefined = 1 is legal javascript, but var null = 1 is a syntax error. The difference is that null is a language keyword, while undefined is, for some reason, not.
If your code relies on comparisons to undefined as if it's a keyword (if (foo == undefined) -- a very easy mistake to make) that only works because nobody has defined a variable with that name. All that code is vulnerable to someone accidentally or maliciously defining a global variable with that name. Of course, we all know that accidentally defining a global variable is totally impossible in javascript...
Just wanna add that with usage of certain javascript libraries, null and undefined can have unintended consequences.
For example, lodash's get function, which accepts a default value as a 3rd argument:
const user = {
address: {
block: null,
unit: undefined,
}
}
console.log(_.get(user, 'address.block', 'Default Value')) // prints null
console.log(_.get(user, 'address.unit', 'Default Value')) // prints 'Default Value'
console.log(_.get(user, 'address.postalCode', 'Default Value')) // prints 'Default Value'
Another example: If you use defaultProps in React, if a property is passed null, default props are not used because null is interpreted as a defined value.
e.g.
class MyComponent extends React.Component {
static defaultProps = {
callback: () => {console.log('COMPONENT MOUNTED')},
}
componentDidMount() {
this.props.callback();
}
}
//in some other component
<MyComponent /> // Console WILL print "COMPONENT MOUNTED"
<MyComponent callback={null}/> // Console will NOT print "COMPONENT MOUNTED"
<MyComponent callback={undefined}/> // Console WILL print "COMPONENT MOUNTED"
There are already some good answers here but not the one that I was looking for. null and undefined both "technically" do the same thing in terms of both being falsy, but when I read through code and I see a "null" then I'm expecting that it's a user defined null, something was explicitly set to contain no value, if I read through code and see "undefined" then I assume that it's code that was never initialized or assigned by anything. In this way code can communicate to you whether something was caused by uninitialized stuff or null values. Because of that you really shouldn't assign "undefined" manually to something otherwise it messes with the way you (or another developer) can read code. If another developer sees "undefined" they're not going to intuitively assume it's you who made it undefined, they're going to assume it's not been initialized when in fact it was. For me this is the biggest deal, when I read code I want to see what it's telling me, I don't want to guess and figure out if stuff has "actually" been initialized.
Not even to mention that using them in typescript means two different things. Using:
interface Example {
name?: string
}
Means that name can be undefined or a string, but it can't be null. If you want it null you have to explicitly use:
interface Example {
name: string | null
}
And even then you'll be forced to initialize it at least with "null".
That's of course only true if you're using "strictNullChecks": true in tsconfig.json.
Based on a recent breakage we ran into, the example below shows why I prefer to use undefined over null, unless there is a specific reason to do otherwise:
function myfunc (myArg) {
if (typeof myArg === 'string') {
console.log('a', myArg);
} else if (typeof abc === 'object') {
console.log('b', myArg);
if (myArg.id) {
console.log('myArg has an id');
} else {
console.log('myArg has an id');
}
} else {
console.log('no value');
}
}
The following values will play nicely:
'abc'
{}
undefined
{ id: 'xyz' }
On the other hand the assumption of null and undefined being equivalent here breaks the code. The reason being is that null is of type of object, where as undefined is of type undefined. So here the code breaks because you can't test for a member on null.
I have seen a large number of cases with code of similar appearance, where null is just asking for problems:
if (typeof myvar === 'string') {
console.log(myvar);
} else if (typeof myvar === 'object') {
console.log(myvar.id);
}
The fix here would be to explicitly test for null:
if (typeof myvar === 'string') {
console.log(myvar);
} else if (myvar !== null && typeof myvar === 'object') {
console.log(myvar.id);
}
My attitude is to code for the weaknesses of a language and the typical behaviours of programmers of that language, hence the philosophy here of going with 'undefined' bey default.
To write simple code you need to keep complexity and variation down. When a variable or a property on an object does not have a value it is undefined , and for a value to be null you need to assign it a null value.
Undeclared vs Null
null is both an Object "type" and one of the 7 unique primitive value types called null
undefined is both a global scope property and type called undefined and one of the 7 unique primitive value types called undefined (window.undefined) .
It is the primitive types we use as values we are interested in.
In the case of null, as a value type it means an empty value has been assigned to a variable, but the variable type (Number, String, etc) is still defined. It just has no value. That is what null means. It means a variable has an empty value but it is still a value. It also reinitializes the variable with some kind of value, but is not undefined as a type.
undefined is a special case. When you declare a variable (or use a missing value not yet declared) it is of type undefined, as the browser does not know what type of data has been assigned to it yet. If the variable is declared but not assigned a value is is assigned the primitive calue undefined by default prior to assigning a value, and implies the variable does not exist or exists but has no value assigned.
Like null, undefined is also a primitive value type. But unlike null it means the variable does not exist, where null means the value does not exist. That is why its always better to check if the variable exists and has been assigned a variable using undefined before checking if the value is null or empty. undefined implies no variable or object exists in the compilation at all. The variable has either not been declared or declared with a missing value so not initialized. So checking for undefined is a very good way to avoid many types of errors in JavaScript and supersedes null.
That is why I would not rely on "truthy" checks for true/false with null and undefined, even though they will both return a false response, as undefined implies an additional step for missing feature, object, or variable, not just a true/false check. It implies something more. If you have a missing undeclared variable, truthy statements will trigger an ERROR!
Let's look at undefined first:
//var check1;// variable doesnt even exist so not assigned to "undefined"
var check2;// variable declared but not initialized so assigned "undefined"
var check3 = 'hello world';// variable has a value so not undefined
console.log('What is undefined?');
//console.log(check1 === undefined);// ERROR! check1 does not exist yet so not assigned undefined!
console.log(check2 === undefined);// True
console.log(check3 === undefined);// False
console.log(typeof check1 === 'undefined');// True - stops the ERROR!
console.log(typeof check2 === 'undefined');// True
console.log(typeof check3 === 'undefined');// False
As you can see undeclared variables, or declared but not initialized, both are assigned a type of undefined. Notice declared variables that are not initialized are assigned a value of undefined, the primitive value type but variables that do not exist are undefined types.
null has nothing to do with missing variables or variables not yet assigned values, as null is still a value. So anything with a null is already declared and initialized. Also notice a variable assigned a null value is actually an object type unlike undefined types. For example...
var check4 = null;
var check5 = 'hello world';
console.log('What is null?');
console.log(check4 === undefined);// False
console.log(check5 === undefined);// False
console.log(typeof check4 === 'undefined');// False
console.log(typeof check5 === 'undefined');// False
console.log(typeof check4);// return 'object'
console.log(typeof check5);// return 'string'
As you can see each act differently and yet both are primitive values you can assign any variable. Just understand they represent different states of variables and objects.

"var variable" returns undefined?

When I run "var variable = true;" in chrome console I get "undefined" returned:
> var variable = true;
undefined
But when I run without "var" it returns true:
> variable = true;
true
Why is it returning "undefined" with "var"?
It's confusing cause I expected it would return true.
The first is a statement, while the second is an expression. While not quite the same, it is similar to C's rules:
// A statement that has no value.
int x = 5;
// An expression...
x = 10;
// ...that can be passed around.
printf("%d\n", x = 15);
var x = y; is a statement which returns no value. In the WebKit JS console, a statement that returns no value will show undefined as the result, e.g.
> if(1){}
undefined
> ;
undefined
> if(1){4} // this statement returns values!
4
The assignment is an expression which returns the value of the LHS. That means, this expression statement has a return value, and this will be shown.
An assignation returns the assignation's value, but with var this return is "consumed" (?)
Statements always return undefined.
var color = "red";
undefined
Expressions always return a value.
color = "orange";
"orange"
I'd like to point out, that the answer provided by kennytm should be the accepted answer, at least for pedagogical purposes. The accepted answer doesn't answer why this is the case or provide deeper understanding.
Like the null value in JavaScript, undefined indicates absence of value, but in a much deeper way. The following should be taken as complimentary to the above-mentioned answers:
undefined is the value of variables that haven't been initialized and the
value you get when you query the value of an object property or
array element that doesn't exist. This value is also returned by
functions that have no return value, and the value of function
parameters for which no argument is supplied. undefined is a predefined
global variable (not a language keyword like null) that is initialized
to the undefined value.
You might consider undefined to represent a system-level, unexpected,
or error-like absence of value and null to represent program-level,
normal, or expected absence of value.
-- Flanagan, David. JavaScript: The Definitive Guide: Activate Your Web
Pages (Definitive Guides) . O'Reilly Media. Kindle Edition.
Also, makes sure to check out both the accepted and the second most voted answer for further reference:
Chrome/Firefox console.log always appends a line saying undefined

Categories

Resources