difference between "void 0 " and "undefined" - javascript

I'm using "Closure Compiler", when compiling my scripts I spend the following:
Before compiling:
// ==ClosureCompiler==
// #compilation_level SIMPLE_OPTIMIZATIONS
// #output_file_name default.js
// #formatting pretty_print,print_input_delimiter
// ==/ClosureCompiler==
var myObj1 = (function() {
var undefined; //<----- declare undefined
this.test = function(value, arg1) {
var exp = 0;
arg1 = arg1 == undefined ? true : arg1; //<----- use declare undefined
exp = (arg1) ? value * 5 : value * 10;
return exp;
};
return this;
}).call({});
var myObj2 = (function() {
this.test = function(value, arg1) {
var exp = 0;
arg1 = arg1 == undefined ? true : arg1; //<----- without declare undefined
exp = (arg1) ? value * 5 : value * 10;
return exp;
};
return this;
}).call({});
Compiled:
// Input 0
var myObj1 = function() {
this.test = function(b, a) {
a = a == void 0 ? true : a; //<-----
var c = 0;
return c = a ? b * 5 : b * 10
};
return this
}.call({}), myObj2 = function() {
this.test = function(b, a) {
a = a == undefined ? true : a; //<-----
var c = 0;
return c = a ? b * 5 : b * 10
};
return this
}.call({});
With this I believe the question of the use of "void 0 " and "undefined", is there any difference in the use or the two cases are well?.
Edit
if I define "var undefined" compiled with "void 0 ", if I did not define "undefined" compiled with "undedined. " then not a matter of number of characters between "undefined" and "void 0"
Test
Edit II: performance, based on this link
Code and Test
IE 8:
typeof: 228ms
undefined: 62ms
void 0: 57ms
Firefox 3.6:
typeof: 10ms
undefined: 3ms
void 0: 3ms
Opera 11:
typeof: 67ms
undefined: 19ms
void 0: 20ms
Chrome 8:
typeof: 3ms
undefined: 5ms
void 0: 3ms

From MDN:
The void operator evaluates the given expression and then returns undefined.
This operator allows inserting expressions that produce side effects into places where an expression that evaluates to undefined is desired.
The void operator is often used merely to obtain the undefined primitive value, usually using "void(0)" (which is equivalent to "void 0"). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value).
Closure Compiler swaps in void 0 because it contains fewer characters than undefined, therefore producing equivalent, smaller code.
Re: OP comment
yes, I read the documentation, but in the example I gave, "google closure" in a case using "void 0" and another "undefined"
I believe this is actually a bug in Google Closure Compiler!

The real only semantic difference between void expr and undefined is that on ECMAScript 3, the undefined property of the global object (window.undefined on browser environments) is writable, whereas the void operator will return the undefined value always.
A popular pattern that is often implemented, to use undefined without worries is simply declaring an argument, and not passing anything to it:
(function (undefined) {
//...
if (foo !== undefined) {
// ...
}
})();
That will allow minifiers to shrink the argument maybe to a single letter (even shorter than void 0 :), e.g.:
(function (a) {
//...
if (foo !== a) {
// ...
}
})();

Just a follow-up on all the answers before.
They look the same, but to the Compiler they are completely different.
The two code sections compile to different outputs because one is referring to a local variable (the var undefined), and the compiler simply in-lines it because it is used exactly once and is no more than one line. If it is used more than once, then this in-lining won't happen. The in-lining provides a result of "undefined", which is shorter to represent as "void 0".
The one without a local variable is referring to the variable called "undefined" under the global object, which is automatically "extern'ed" by the Closure Compiler (in fact, all global object properties are). Therefore, no renaming takes place, and no in-lining takes place. Voila! still "undefined".

There is no difference, Try it yourself:
void 0 === undefined
will evaluate to true.
undefined is 3 characters longer, I guess that is the reason why they use it that way.

Related

What does (append = false) mean in javascript? [duplicate]

I would like a JavaScript function to have optional arguments which I set a default on, which get used if the value isn't defined (and ignored if the value is passed). In Ruby you can do it like this:
def read_file(file, delete_after = false)
# code
end
Does this work in JavaScript?
function read_file(file, delete_after = false) {
// Code
}
From ES6/ES2015, default parameters are in the language specification.
function read_file(file, delete_after = false) {
// Code
}
just works.
Reference: Default Parameters - MDN
Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.
In ES6, you can simulate default named parameters via destructuring:
// the `= {}` below lets you call the function without any parameters
function myFor({ start = 5, end = 1, step = -1 } = {}) { // (A)
// Use the variables `start`, `end` and `step` here
···
}
// sample call using an object
myFor({ start: 3, end: 0 });
// also OK
myFor();
myFor({});
Pre ES2015,
There are a lot of ways, but this is my preferred method — it lets you pass in anything you want, including false or null. (typeof null == "object")
function foo(a, b) {
a = typeof a !== 'undefined' ? a : 42;
b = typeof b !== 'undefined' ? b : 'default_b';
...
}
function read_file(file, delete_after) {
delete_after = delete_after || "my default here";
//rest of code
}
This assigns to delete_after the value of delete_after if it is not a falsey value otherwise it assigns the string "my default here". For more detail, check out Doug Crockford's survey of the language and check out the section on Operators.
This approach does not work if you want to pass in a falsey value i.e. false, null, undefined, 0 or "". If you require falsey values to be passed in you would need to use the method in Tom Ritter's answer.
When dealing with a number of parameters to a function, it is often useful to allow the consumer to pass the parameter arguments in an object and then merge these values with an object that contains the default values for the function
function read_file(values) {
values = merge({
delete_after : "my default here"
}, values || {});
// rest of code
}
// simple implementation based on $.extend() from jQuery
function merge() {
var obj, name, copy,
target = arguments[0] || {},
i = 1,
length = arguments.length;
for (; i < length; i++) {
if ((obj = arguments[i]) != null) {
for (name in obj) {
copy = obj[name];
if (target === copy) {
continue;
}
else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
return target;
};
to use
// will use the default delete_after value
read_file({ file: "my file" });
// will override default delete_after value
read_file({ file: "my file", delete_after: "my value" });
I find something simple like this to be much more concise and readable personally.
function pick(arg, def) {
return (typeof arg == 'undefined' ? def : arg);
}
function myFunc(x) {
x = pick(x, 'my default');
}
In ECMAScript 6 you will actually be able to write exactly what you have:
function read_file(file, delete_after = false) {
// Code
}
This will set delete_after to false if it s not present or undefined. You can use ES6 features like this one today with transpilers such as Babel.
See the MDN article for more information.
Default Parameter Values
With ES6, you can do perhaps one of the most common idioms in JavaScript relates to setting a default value for a function parameter. The way we’ve done this for years should look quite familiar:
function foo(x,y) {
x = x || 11;
y = y || 31;
console.log( x + y );
}
foo(); // 42
foo( 5, 6 ); // 11
foo( 5 ); // 36
foo( null, 6 ); // 17
This pattern is most used, but is dangerous when we pass values like
foo(0, 42)
foo( 0, 42 ); // 53 <-- Oops, not 42
Why? Because the 0 is falsy, and so the x || 11 results in 11, not the directly passed in 0. To fix this gotcha, some people will instead write the check more verbosely like this:
function foo(x,y) {
x = (x !== undefined) ? x : 11;
y = (y !== undefined) ? y : 31;
console.log( x + y );
}
foo( 0, 42 ); // 42
foo( undefined, 6 ); // 17
we can now examine a nice helpful syntax added as of ES6 to streamline the assignment of default values to missing arguments:
function foo(x = 11, y = 31) {
console.log( x + y );
}
foo(); // 42
foo( 5, 6 ); // 11
foo( 0, 42 ); // 42
foo( 5 ); // 36
foo( 5, undefined ); // 36 <-- `undefined` is missing
foo( 5, null ); // 5 <-- null coerces to `0`
foo( undefined, 6 ); // 17 <-- `undefined` is missing
foo( null, 6 ); // 6 <-- null coerces to `0`
x = 11 in a function declaration is more like x !== undefined ? x : 11 than the much more common idiom x || 11
Default Value Expressions
Function default values can be more than just simple values like 31; they can be any valid expression, even a function call:
function bar(val) {
console.log( "bar called!" );
return y + val;
}
function foo(x = y + 3, z = bar( x )) {
console.log( x, z );
}
var y = 5;
foo(); // "bar called"
// 8 13
foo( 10 ); // "bar called"
// 10 15
y = 6;
foo( undefined, 10 ); // 9 10
As you can see, the default value expressions are lazily evaluated, meaning they’re only run if and when they’re needed — that is, when a parameter’s argument is omitted or is undefined.
A default value expression can even be an inline function expression call — commonly referred to as an Immediately Invoked Function Expression (IIFE):
function foo( x =
(function(v){ return v + 11; })( 31 )
) {
console.log( x );
}
foo(); // 42
that solution is work for me in js:
function read_file(file, delete_after) {
delete_after = delete_after || false;
// Code
}
I would highly recommend extreme caution when using default parameter values in javascript. It often creates bugs when used in conjunction with higher order functions like forEach, map, and reduce. For example, consider this line of code:
['1', '2', '3'].map(parseInt); // [1, NaN, NaN]
parseInt has an optional second parameter function parseInt(s, [radix=10]) but map calls parseInt with three arguments: (element, index, and array).
I suggest you separate your required parameters form your optional/default valued arguments. If your function takes 1,2, or 3 required parameters for which no default value makes sense, make them positional parameters to the function, any optional parameters should follow as named attributes of a single object. If your function takes 4 or more, perhaps it makes more sense to supply all arguments via attributes of a single object parameter.
In your case I would suggest you write your deleteFile function like this: (edited per instead's comments)...
// unsafe
function read_file(fileName, deleteAfter=false) {
if (deleteAfter) {
console.log(`Reading and then deleting ${fileName}`);
} else {
console.log(`Just reading ${fileName}`);
}
}
// better
function readFile(fileName, options) {
const deleteAfter = !!(options && options.deleteAfter === true);
read_file(fileName, deleteAfter);
}
console.log('unsafe...');
['log1.txt', 'log2.txt', 'log3.txt'].map(read_file);
console.log('better...');
['log1.txt', 'log2.txt', 'log3.txt'].map(readFile);
Running the above snippet illustrates the dangers lurking behind default argument values for unused parameters.
Just use an explicit comparison with undefined.
function read_file(file, delete_after)
{
if(delete_after === undefined) { delete_after = false; }
}
As an update...with ECMAScript 6 you can FINALLY set default values in function parameter declarations like so:
function f (x, y = 7, z = 42) {
return x + y + z
}
f(1) === 50
As referenced by - http://es6-features.org/#DefaultParameterValues
being a long time C++ developer (Rookie to web development :)), when I first came across this situation, I did the parameter assignment in the function definition, like it is mentioned in the question, as follows.
function myfunc(a,b=10)
But beware that it doesn't work consistently across browsers. For me it worked on chrome on my desktop, but did not work on chrome on android.
Safer option, as many have mentioned above is -
function myfunc(a,b)
{
if (typeof(b)==='undefined') b = 10;
......
}
Intention for this answer is not to repeat the same solutions, what others have already mentioned, but to inform that parameter assignment in the function definition may work on some browsers, but don't rely on it.
To anyone interested in having there code work in Microsoft Edge, do not use defaults in function parameters.
function read_file(file, delete_after = false) {
#code
}
In that example Edge will throw an error "Expecting ')'"
To get around this use
function read_file(file, delete_after) {
if(delete_after == undefined)
{
delete_after = false;
}
#code
}
As of Aug 08 2016 this is still an issue
If you are using ES6+ you can set default parameters in the following manner:
function test (foo = 1, bar = 2) {
console.log(foo, bar);
}
test(5); // foo gets overwritten, bar remains default parameter
If you need ES5 syntax you can do it in the following manner:
function test(foo, bar) {
foo = foo || 2;
bar = bar || 0;
console.log(foo, bar);
}
test(5); // foo gets overwritten, bar remains default parameter
In the above syntax the OR operator is used. The OR operator always returns the first value if this can be converted to true if not it returns the righthandside value. When the function is called with no corresponding argument the parameter variable (bar in our example) is set to undefined by the JS engine. undefined Is then converted to false and thus does the OR operator return the value 0.
function helloWorld(name, symbol = '!!!') {
name = name || 'worlds';
console.log('hello ' + name + symbol);
}
helloWorld(); // hello worlds!!!
helloWorld('john'); // hello john!!!
helloWorld('john', '(>.<)'); // hello john(>.<)
helloWorld('john', undefined); // hello john!!!
helloWorld(undefined, undefined); // hello worlds!!!
Use this if you want to use latest ECMA6 syntax:
function myFunction(someValue = "This is DEFAULT!") {
console.log("someValue --> ", someValue);
}
myFunction("Not A default value") // calling the function without default value
myFunction() // calling the function with default value
It is called default function parameters. It allows formal parameters to be initialized with default values if no value or undefined is passed.
NOTE: It wont work with Internet Explorer or older browsers.
For maximum possible compatibility use this:
function myFunction(someValue) {
someValue = (someValue === undefined) ? "This is DEFAULT!" : someValue;
console.log("someValue --> ", someValue);
}
myFunction("Not A default value") // calling the function without default value
myFunction() // calling the function with default value
Both functions have exact same behavior as each of these example rely on the fact that the parameter variable will be undefined if no parameter value was passed when calling that function.
ES6: As already mentioned in most answers, in ES6, you can simply initialise a parameter along with a value.
ES5: Most of the given answers aren't good enough for me because there are occasions where I may have to pass falsey values such as 0, null and undefined to a function. To determine if a parameter is undefined because that's the value I passed instead of undefined due to not have been defined at all I do this:
function foo (param1, param2) {
param1 = arguments.length >= 1 ? param1 : "default1";
param2 = arguments.length >= 2 ? param2 : "default2";
}
As per the syntax
function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
statements
}
you can define the default value of formal parameters.
and also check undefined value by using typeof function.
function throwIfNoValue() {
throw new Error('Missing argument');
}
function foo(argValue = throwIfNoValue()) {
return argValue ;
}
Here foo() is a function which has a parameter named argValue. If we don’t pass anything in the function call here, then the function throwIfNoValue() will be called and the returned result will be assigned to the only argument argValue. This is how a function call can be used as a default parameter. Which makes the code more simplified and readable.
This example has been taken from here
If for some reason you are not on ES6 and are using lodash here is a concise way to default function parameters via _.defaultTo method:
var fn = function(a, b) {
a = _.defaultTo(a, 'Hi')
b = _.defaultTo(b, 'Mom!')
console.log(a, b)
}
fn() // Hi Mom!
fn(undefined, null) // Hi Mom!
fn(NaN, NaN) // Hi Mom!
fn(1) // 1 "Mom!"
fn(null, 2) // Hi 2
fn(false, false) // false false
fn(0, 2) // 0 2
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Which will set the default if the current value is NaN, null, or undefined
Yes, using default parameters is fully supported in ES6:
function read_file(file, delete_after = false) {
// Code
}
or
const read_file = (file, delete_after = false) => {
// Code
}
but prior in ES5 you could easily do this:
function read_file(file, delete_after) {
var df = delete_after || false;
// Code
}
Which means if the value is there, use the value, otherwise, use the second value after || operation which does the same thing...
Note: also there is a big difference between those if you pass a value to ES6 one even the value be falsy, that will be replaced with new value, something like null or ""... but ES5 one only will be replaced if only the passed value is truthy, that's because the way || working...
Sounds of Future
In future, you will be able to "spread" one object to another (currently as of 2019 NOT supported by Edge!) - demonstration how to use that for nice default options regardless of order:
function test(options) {
var options = {
// defaults
url: 'defaultURL',
some: 'somethingDefault',
// override with input options
...options
};
var body = document.getElementsByTagName('body')[0];
body.innerHTML += '<br>' + options.url + ' : ' + options.some;
}
test();
test({});
test({url:'myURL'});
test({some:'somethingOfMine'});
test({url:'overrideURL', some:'andSomething'});
test({url:'overrideURL', some:'andSomething', extra:'noProblem'});
MDN reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
...meanwhile what Edge DOES support is Object.assign() (IE does not, but I really hope we can leave IE behind :) )
Similarly you could do
function test(options) {
var options = Object.assign({
// defaults
url: 'defaultURL',
some: 'somethingDefault',
}, options); // override with input options
var body = document.getElementsByTagName('body')[0];
body.innerHTML += '<br>' + options.url + ' : ' + options.some;
}
test();
test({});
test({url:'myURL'});
test({some:'somethingOfMine'});
test({url:'overrideURL', some:'andSomething'});
test({url:'overrideURL', some:'andSomething', extra:'noProblem'});
EDIT: Due to comments regarding const options - the problem with using constant options in the rest of the function is actually not that you can't do that, is just that you can't use the constant variable in its own declaration - you would have to adjust the input naming to something like
function test(input_options){
const options = {
// defaults
someKey: 'someDefaultValue',
anotherKey: 'anotherDefaultValue',
// merge-in input options
...input_options
};
// from now on use options with no problem
}
Just to showcase my skills too (lol), above function can written even without having named arguments as below:
ES5 and above
function foo() {
a = typeof arguments[0] !== 'undefined' ? a : 42;
b = typeof arguments[1] !== 'undefined' ? b : 'default_b';
...
}
ES6 and above
function foo(...rest) {
a = typeof rest[0] !== 'undefined' ? a : 42;
b = typeof rest[1] !== 'undefined' ? b : 'default_b';
...
}
Yes - proof:
function read_file(file, delete_after = false) {
// Code
console.log({file,delete_after});
}
// TEST
read_file("A");
read_file("B",true);
read_file("C",false);
Yeah this is referred to as a default parameter
Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.
Syntax:
function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
statements
}
Description:
Parameters of functions default to undefined However, in situations it might be useful to set a different default value. This is where default parameters can help.
In the past, the general strategy for setting defaults was to test parameter values in the body of the function and assign a value if they are undefined. If no value is provided in the call, its value would be undefined. You would have to set a conditional check to make sure the parameter is not undefined
With default parameters in ES2015, the check in the function body is no longer necessary. Now you can simply put a default value in the function head.
Example of the differences:
// OLD METHOD
function multiply(a, b) {
b = (typeof b !== 'undefined') ? b : 1;
return a * b;
}
multiply(5, 2); // 10
multiply(5, 1); // 5
multiply(5); // 5
// NEW METHOD
function multiply(a, b = 1) {
return a * b;
}
multiply(5, 2); // 10
multiply(5, 1); // 5
multiply(5); // 5
Different Syntax Examples:
Padding undefined vs other falsy values:
Even if the value is set explicitly when calling, the value of the num argument is the default one.
function test(num = 1) {
console.log(typeof num);
}
test(); // 'number' (num is set to 1)
test(undefined); // 'number' (num is set to 1 too)
// test with other falsy values:
test(''); // 'string' (num is set to '')
test(null); // 'object' (num is set to null)
Evaluated at call time:
The default argument gets evaluated at call time, so unlike some other languages, a new object is created each time the function is called.
function append(value, array = []) {
array.push(value);
return array;
}
append(1); //[1]
append(2); //[2], not [1, 2]
// This even applies to functions and variables
function callSomething(thing = something()) {
return thing;
}
function something() {
return 'sth';
}
callSomething(); //sth
Default parameters are available to later default parameters:
Params already encountered are available to later default parameters
function singularAutoPlural(singular, plural = singular + 's',
rallyingCry = plural + ' ATTACK!!!') {
return [singular, plural, rallyingCry];
}
//["Gecko","Geckos", "Geckos ATTACK!!!"]
singularAutoPlural('Gecko');
//["Fox","Foxes", "Foxes ATTACK!!!"]
singularAutoPlural('Fox', 'Foxes');
//["Deer", "Deer", "Deer ... change."]
singularAutoPlural('Deer', 'Deer', 'Deer peaceably and respectfully \ petition the government for positive change.')
Functions defined inside function body:
Introduced in Gecko 33 (Firefox 33 / Thunderbird 33 / SeaMonkey 2.30). Functions declared in the function body cannot be referred inside default parameters and throw a ReferenceError (currently a TypeError in SpiderMonkey, see bug 1022967). Default parameters are always executed first, function declarations inside the function body evaluate afterwards.
// Doesn't work! Throws ReferenceError.
function f(a = go()) {
function go() { return ':P'; }
}
Parameters without defaults after default parameters:
Prior to Gecko 26 (Firefox 26 / Thunderbird 26 / SeaMonkey 2.23 / Firefox OS 1.2), the following code resulted in a SyntaxError. This has been fixed in bug 777060 and works as expected in later versions. Parameters are still set left-to-right, overwriting default parameters even if there are later parameters without defaults.
function f(x = 1, y) {
return [x, y];
}
f(); // [1, undefined]
f(2); // [2, undefined]
Destructured paramet with default value assignment:
You can use default value assignment with the destructuring assignment notation
function f([x, y] = [1, 2], {z: z} = {z: 3}) {
return x + y + z;
}
f(); // 6
I've noticed a few answers mentioning that using default params isn't portable to other browsers, but it's only fair to point out that you can use transpilers like Babel to convert your code into ES5 syntax for browsers that have limited support for modern JS features.
So this:
function read_file(file, delete_after = false) {
// Code
}
would be transpiled as this (try it out in the Babel REPL -> https://babeljs.io/repl/):
"use strict";
function read_file(file) {
var delete_after =
arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
//Code...
}
Of course, if you have no intention of using transpilation, then setting default params in the body of the function like others have demonstrated is perfectly fine as well.
Just a different approach to set default params is to use object map of arguments, instead of arguments directly.
For example,
const defaultConfig = {
category: 'Animals',
legs: 4
};
function checkOrganism(props) {
const category = props.category || defaultConfig.category;
const legs = props.legs || defaultConfig.legs;
}
This way, it's easy to extend the arguments and not worry about argument length mismatch.
export const getfilesize = (bytes, decimals = 2) => {
if (bytes === 0){
return '0 Bytes';
}else{
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
}
def read_file(file, delete_after = false)
# code
end
Following code may work in this situation including ECMAScript 6 (ES6) as well as earlier versions.
function read_file(file, delete_after) {
if(delete_after == undefined)
delete_after = false;//default value
console.log('delete_after =',delete_after);
}
read_file('text1.txt',true);
read_file('text2.txt');
as default value in languages works when the function's parameter value is skipped when calling, in JavaScript it is assigned to undefined. This approach doesn't look attractive programmatically but have backward compatibility.
The answer is yes. In fact, there are many languages who support default parameters. Python is one of them:
def(a, enter="Hello"):
print(a+enter)
Even though this is Python 3 code due to the parentheses, default parameters in functions also work in JS.
For example, and in your case:
function read_file(file, deleteAfter=false){
console.log(deleteAfter);
}
read_file("test.txt");
But sometimes you don't really need default parameters.
You can just define the variable right after the start of the function, like this:
function read_file(file){
var deleteAfter = false;
console.log(deleteAfter);
}
read_file("test.txt");
In both of my examples, it returns the same thing. But sometimes they actually could be useful, like in very advanced projects.
So, in conclusion, default parameter values can be used in JS. But it is almost the same thing as defining a variable right after the start of the function. However, sometimes they are still very useful. As you have may noticed, default parameter values take 1 less line of code than the standard way which is defining the parameter right after the start of the function.
EDIT: And this is super important! This will not work in IE. See documentation. So with IE you have to use the "define variable at top of function" method. Default parameters won't work in IE.
Yes, This will work in Javascript. You can also do that:
function func(a=10,b=20)
{
alert (a+' and '+b);
}
func(); // Result: 10 and 20
func(12); // Result: 12 and 20
func(22,25); // Result: 22 and 25

What is the benefit of angular.isdefined?

What is the benefit of angular.isdefined over and above foo === undefined?
I can't immediately think of a benefit.
Accessing a truly undefined variable in any way in Javascript, except typeof throws an error. You can only use Angular.isDefined with properties. E.g, this would work fine:
angular.isDefined(window.obj);
Because obj is an undefined propery of window.
Examples of the expected behavior:
var foo;
var bar = 42;
typeof foo !== 'undefined'; // false
typeof bar !== 'undefined'; // true
typeof baz !== 'undefined'; // false
angular.isDefined(foo); // false
angular.isDefined(bar); // true
angular.isDefined(baz); // ReferenceError
Here is the source:
function isDefined(value) {return typeof value !== 'undefined';}
Obviously the first reason is a lower verbosity, but it also future proofs angular, especially if the function is used internally.
Like Kamrul said angular does:
function isDefined(value) { return typeof value !== 'undefined'; }
Which means "the type of this var is undefined"... in you example you compare the content of the variable is equals to undefined and angular is checking the type of the variable.
In js the types are dynamic so until you don't assign a value the variable has no type... so isDefined will tell you both, if a variable declaration exist and if this variable has any content.
But, be careful because the variable could be null, in which case the type of the variable would be object.
You could try this code:
var a;
var b = 'asd';
var c = null;
console.log('a: ' + typeof a);
console.log('b: ' + typeof b);
console.log('c: ' + typeof c);
console.log('d: ' + typeof d);
And you will see the next in console:
a: undefined
b: string
c: object
d: undefined
So,
a) the var exist but has no value so is undefined
b) the var exist and has value.. this value is a string so this is its type
c) the var exist but is null, the type can't be interfered so its type is object
d) the var has not been declared so... it's undefined
The main point is the diference between "a" and "d"... so try the next:
console.log('a is undefined? ' + a === undefined);
console.log('d is undefined? ' + d === undefined);
You will see the next in console:
false
Uncaught ReferenceError: d is not defined
Which... is a big problem because:
a) tells you that is not undefined when that's not true
d) raise an exception so... you code will fail
Conclusion
Use is defined when you want to check if a variable exists and has been initialized with a value, but be careful with null values because null is an object (so is a defined var).
If you want to validate that a variable exists and has any valid value (so is not null) you can simple do something like:
if (myvar) {
console.log('myvar is defined and is not null');
} else {
console.log('myvar is undefined or null');
}
Another good trick is to init to some value if the var is not defined with ||
myvar = myvar || 'some init value';
The above code takes the value of myvar if is defined and not null and if not init it with some value.
As #TonyBrasunas put on his comment if myvar is evaluated to false, 'some init value' will be assigned. Take this into consideration before using this trick.
This is good in functions, for example:
function split(input, charToSplit) {
charToSplit = charToSplit || ' ';
return input.split(charToSplit);
}
Then by default you can split with whitespaces:
var input = 'asd asd';
var splited = split(input);
// --> splited = ['asd', 'asd']
Or... with another char:
var input = 'asd|asd';
var splited = split(input, '|');
// --> splited= ['asd', 'asd']
I can only guess but I think my guess is a pretty good one.
These two expressions are functionally equivalent:
typeof foo !== 'undefined'
angular.isDefined(foo)
Benefits of the latter include:
1) It's arguably less of a mental strain to ask whether something is defined than to ask if something is not undefined.
2) angular.isDefined(foo) is arguably a lot less "noisy" than typeof foo !== 'undefined', and therefore it's quicker to grasp what's happening.
Note: These aren't my arguments for the superiority of angular.isDefined. What I'm trying to convey is my guess as to why the Angular team wanted to create angular.isDefined and why they thought it was better than the plain JavaScript alternative.

handling on no argument in javascript functions

I have little experience in javascript but in other programming languages the following is possible, to set a default value for a missing parameter in a function.
For instance lets say i have a function
function foo(a , b)
return a + b
{
I would like to be able to call the above function with 1 parameter or with 2 parameters
one parameter case:
foo(2) //a =2 and b would be automatically set to a default no argument value,
two parameter case:
foo(1,2) // a = 1 , b = 2 => 3
Is this possible in javascript that is IE 8 compatible or using Jquery 1.7.2?
JavaScript functions allow you to call them with less parameters than specified.
What you're trying to accomplish is possible doing something like the following:
function foo(a , b){
if(typeof b === "undefined"){
b=3;
}
return a + b;
}
foo(5);//return 3;
I strongly suggest that you check for undefined and not rely on the || operator. I've spent hours debugging code that made that assumption and failed when passing 0 or another falsy value. The JavaScript type system can get really tricky, for example "0" is falsy.
ECMAScript Harmony (the next version) allows default parameters like in those other languages using the following syntax
function foo(a , b=3){
return a + b;
}
This does not work in IE8 like the first version though.
No, but you can simulate this effect manually with a tertiary operator or an if statement (just make sure you check for undefined!):
function foo(a, b) {
b = (typeof b === "undefined") ? 2 : b;
return a + b;
}
Yes, it's possible. If a parameter isn't passed, you get a special value "undefined". The following works for me:
function foo(a, b) {
a = a || defaultForA;
b = b || defaultForB;
}
Due to the way Javascript treats conversion to boolean, the following will all be considered undefined in the above code snippet:
undefined
null
0
"" (empty string)
false
So if those values are important to you, you'll need to explicitly test for undefined rather than the blanket "if not false" test being used above.
An undefined parameter evaluates as false, so you can do something like this in the beggining of your function foo:
a = a || 0;
b = b || 0;
That way if a or b exist, they will be evaluated with their own values and with 0 otherwise.
You can just test if you received a parameter:
function foo(a, b) {
if(typeof b === "undefined") {b = 2;}
}
By testing for "undefined" you can also accept parameters that evaluate to false (like null or "" or 0 or false)

What is the difference between null and undefined in JavaScript?

I want to know what the difference is between null and undefined in JavaScript.
undefined means a variable has been declared but has not yet been assigned a value :
var testVar;
console.log(testVar); //shows undefined
console.log(typeof testVar); //shows undefined
null is an assignment value. It can be assigned to a variable as a representation of no value :
var testVar = null;
console.log(testVar); //shows null
console.log(typeof testVar); //shows object
From the preceding examples, it is clear that undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.
Proof :
console.log(null === undefined) // false (not the same type)
console.log(null == undefined) // true (but the "same value")
console.log(null === null) // true (both type and value are the same)
and
null = 'value' // Uncaught SyntaxError: invalid assignment left-hand side
undefined = 'value' // 'value'
The difference can be explained with toilet tissue holder:
A non-zero value is like a holder with roll of toilet tissue and there's tissue still on the tube.
A zero value is like a holder with an empty toilet tissue tube.
A null value is like a holder that doesn't even have a tissue tube.
An undefined value is similar to the holder itself being missing.
I picked this from here
The undefined value is a primitive value used when a variable has not
been assigned a value.
The null value is a primitive value that represents the null, empty,
or non-existent reference.
When you declare a variable through var and do not give it a value, it will have the value undefined. By itself, if you try to WScript.Echo() or alert() this value, you won't see anything. However, if you append a blank string to it then suddenly it'll appear:
var s;
WScript.Echo(s);
WScript.Echo("" + s);
You can declare a variable, set it to null, and the behavior is identical except that you'll see "null" printed out versus "undefined". This is a small difference indeed.
You can even compare a variable that is undefined to null or vice versa, and the condition will be true:
undefined == null
null == undefined
They are, however, considered to be two different types. While undefined is a type all to itself, null is considered to be a special object value. You can see this by using typeof() which returns a string representing the general type of a variable:
var a;
WScript.Echo(typeof(a));
var b = null;
WScript.Echo(typeof(b));
Running the above script will result in the following output:
undefined
object
Regardless of their being different types, they will still act the same if you try to access a member of either one, e.g. that is to say they will throw an exception. With WSH you will see the dreaded "'varname' is null or not an object" and that's if you're lucky (but that's a topic for another article).
You can explicitely set a variable to be undefined, but I highly advise against it. I recommend only setting variables to null and leave undefined the value for things you forgot to set. At the same time, I really encourage you to always set every variable. JavaScript has a scope chain different than that of C-style languages, easily confusing even veteran programmers, and setting variables to null is the best way to prevent bugs based on it.
Another instance where you will see undefined pop up is when using the delete operator. Those of us from a C-world might incorrectly interpret this as destroying an object, but it is not so. What this operation does is remove a subscript from an Array or a member from an Object. For Arrays it does not effect the length, but rather that subscript is now considered undefined.
var a = [ 'a', 'b', 'c' ];
delete a[1];
for (var i = 0; i < a.length; i++)
WScript.Echo((i+".) "+a[i]);
The result of the above script is:
0.) a
1.) undefined
2.) c
You will also get undefined returned when reading a subscript or member that never existed.
The difference between null and undefined is: JavaScript will never set anything to null, that's usually what we do. While we can set variables to undefined, we prefer null because it's not something that is ever done for us. When you're debugging this means that anything set to null is of your own doing and not JavaScript. Beyond that, these two special values are nearly equivalent.
Please read the following carefully. It should remove all your doubts regarding the difference between null and undefined in JavaScript. Also, you can use the utility function at the end of this answer to get more specific types of variables.
In JavaScript we can have the following types of variables:
Undeclared Variables
Declared but Unassigned Variables
Variables assigned with literal undefined
Variables assigned with literal null
Variables assigned with anything other than undefined or null
The following explains each of these cases one by one:
Undeclared Variables
Can only be checked with the typeof operator which returns string 'undefined'
Cannot be checked with the loose equality operator ( == undefined ), let alone the strict equality operator ( === undefined ),
as well as if-statements and ternary operators ( ? : ) — these throw Reference Errors
Declared but Unassigned Variables
typeof returns string 'undefined'
== check with null returns true
== check with undefined returns true
=== check with null returns false
=== check with undefined returns true
Is falsy to if-statements and ternary operators ( ? : )
Variables assigned with literal undefined
These variables are treated exactly the same as Declared But Unassigned Variables.
Variables assigned with literal null
typeof returns string 'object'
== check with null returns true
== check with undefined returns true
=== check with null returns true
=== check with undefined returns false
Is falsy to if-statements and ternary operators ( ? : )
Variables assigned with anything other than undefined or null
typeof returns one of the following strings: 'bigint', 'boolean', 'function', 'number', 'object', 'string', 'symbol'
Following provides the algorithm for correct type checking of a variable:
Get the typeof our variable and return it if it isn't 'object'
Check for null, as typeof null returns 'object' as well
Evaluate Object.prototype.toString.call(o) with a switch statement to return a more precise value. Object's toString method returns strings that look like '[object ConstructorName]' for native/host objects. For all other objects (user-defined objects), it always returns '[object Object]'
If that last part is the case (the stringified version of the variable being '[object Object]') and the parameter returnConstructorBoolean is true, it will try to get the name of the constructor by toString-ing it and extracting the name from there. If the constructor can't be reached, 'object' is returned as usual. If the string doesn't contain its name, 'anonymous' is returned
(supports all types up to ECMAScript 2020)
function TypeOf(o, returnConstructorBoolean) {
const type = typeof o
if (type !== 'object') return type
if (o === null) return 'null'
const toString = Object.prototype.toString.call(o)
switch (toString) {
// Value types: 6
case '[object BigInt]': return 'bigint'
case '[object Boolean]': return 'boolean'
case '[object Date]': return 'date'
case '[object Number]': return 'number'
case '[object String]': return 'string'
case '[object Symbol]': return 'symbol'
// Error types: 7
case '[object Error]': return 'error'
case '[object EvalError]': return 'evalerror'
case '[object RangeError]': return 'rangeerror'
case '[object ReferenceError]': return 'referenceerror'
case '[object SyntaxError]': return 'syntaxerror'
case '[object TypeError]': return 'typeerror'
case '[object URIError]': return 'urierror'
// Indexed Collection and Helper types: 13
case '[object Array]': return 'array'
case '[object Int8Array]': return 'int8array'
case '[object Uint8Array]': return 'uint8array'
case '[object Uint8ClampedArray]': return 'uint8clampedarray'
case '[object Int16Array]': return 'int16array'
case '[object Uint16Array]': return 'uint16array'
case '[object Int32Array]': return 'int32array'
case '[object Uint32Array]': return 'uint32array'
case '[object Float32Array]': return 'float32array'
case '[object Float64Array]': return 'float64array'
case '[object ArrayBuffer]': return 'arraybuffer'
case '[object SharedArrayBuffer]': return 'sharedarraybuffer'
case '[object DataView]': return 'dataview'
// Keyed Collection types: 2
case '[object Map]': return 'map'
case '[object WeakMap]': return 'weakmap'
// Set types: 2
case '[object Set]': return 'set'
case '[object WeakSet]': return 'weakset'
// Operation types: 3
case '[object RegExp]': return 'regexp'
case '[object Proxy]': return 'proxy'
case '[object Promise]': return 'promise'
// Plain objects
case '[object Object]':
if (!returnConstructorBoolean)
return type
const _prototype = Object.getPrototypeOf(o)
if (!_prototype)
return type
const _constructor = _prototype.constructor
if (!_constructor)
return type
const matches = Function.prototype.toString.call(_constructor).match(/^function\s*([^\s(]+)/)
return matches ? matches[1] : 'anonymous'
default: return toString.split(' ')[1].slice(0, -1)
}
}
null is a special keyword that indicates an absence of value.
think about it as a value, like:
"foo" is string,
true is boolean ,
1234 is number,
null is undefined.
undefined property indicates that a variable has not been assigned a value including null too .
Like
var foo;
defined empty variable is null of datatype undefined
Both of them are representing a value of a variable with no value
AND
null doesn't represent a string that has no value - empty string-
Like
var a = '';
console.log(typeof a); // string
console.log(a == null); //false
console.log(a == undefined); // false
Now if
var a;
console.log(a == null); //true
console.log(a == undefined); //true
BUT
var a;
console.log(a === null); //false
console.log(a === undefined); // true
SO each one has it own way to use
undefined use it to compare the variable data type
null use it to empty a value of a variable
var a = 'javascript';
a = null ; // will change the type of variable "a" from string to object
null: absence of value for a variable; undefined: absence of variable itself;
..where variable is a symbolic name associated with a value.
JS could be kind enough to implicitly init newly declared variables with null, but it does not.
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.
via JavaScript:The Definitive Guide
The best way to understand the difference is to first clear your mind of the inner workings of JavaScript and just understand the differences in meaning between:
let supervisor = "None"
// I have a supervisor named "None"
let supervisor = null
// I do NOT have a supervisor. It is a FACT that I do not.
let supervisor = undefined
// I may or may not have a supervisor. I either don't know
// if I do or not, or I am choosing not to tell you. It is
// irrelevant or none of your business.
There is a difference in meaning between these three cases, and JavaScript distinguishes the latter two cases with two different values, null and undefined. You are free to use those values explicitly to convey those meanings.
So what are some of the JavaScript-specific issues that arise due to this philosophical basis?
A declared variable without an initializer gets the value undefined because you never said anything about the what the intended value was.
let supervisor;
assert(supervisor === undefined);
A property of an object that has never been set evaluates to undefined because no one ever said anything about that property.
const dog = { name: 'Sparky', age: 2 };
assert(dog.breed === undefined);
null and undefined are "similar" to each other because Brendan Eich said so. But they are emphatically not equal to each other.
assert(null == undefined);
assert(null !== undefined);
null and undefined thankfully have different types. null belongs to the type Null and undefined to the type Undefined. This is in the spec, but you would never know this because of the typeof weirdness which I will not repeat here.
A function reaching the end of its body without an explicit return statement returns undefined since you don't know anything about what it returned.
By the way, there are other forms of "nothingness" in JavaScript (it's good to have studied Philosophy....)
NaN
Using a variable that has never been declared and receiving a ReferenceError
Using a let or const defined local variable in its temporal dead zone and receiving a ReferenceError
Empty cells in sparse arrays. Yes these are not even undefined although they compare === to undefined.
$ node
> const a = [1, undefined, 2]
> const b = [1, , 2]
> a
[ 1, undefined, 2 ]
> b
[ 1, <1 empty item>, 2 ]
A lot of "technical" answers have been given, all of them mostly correct from the limited point of view of JS as a mere programming language.
However, I would like to add the following thoughts, especially when you're writing TypeScript code as part of a bigger project / (enterprise) application:
When talking with a Backend of some kind you'll most probably receive JSON
While some backends correctly avoid the use of "null" in their JSON (removing those properties), others do not
Now, while "null" may mean that the value is missing deliberately, more often it does not convey this meaning. Most databases use "null" just because they don't have an "undefined" type. But the meaning really just is "undefined".
Because of that, you can never know if a "null" value really means deliberate absence. Therefore "null" cannot really mean the deliberate choice of "missing value". It is undecidable in general.
As a consequence, semantically, "null" and "undefined" are exactly the same thing in practice.
Therefore, in an effort to harmonize things I'm strictly against using "null" and want to encourage you to stop using "null" in your code. It's far easier than you might think. Don't get me wrong. I'm not talking about not handling "null" values, only to avoid explicitly using them in your code. Put differently: your code should still be able to work with accidentally passed "null" values coming from outside your application, e.g. via a 3rd party lib like Angular, or a 3rd party backend.
Here are the guidelines that make it possible:
avoid direct undefined type guards (e.g. if (value === undefined) { ... }.
Instead, use indirect type guards (aka truthiness checks) e.g. if (value) { ... }
Whenever 0 or empty strings are meaningful, use either
an explicit helper method like Lodash's isNil
or include the meaningful value in the comparison (e.g. if (!value && value !== 0) { ... })
Consider using a lint rule that disallows the usage of null
null is a special value meaning "no value". null is a special object because typeof null returns 'object'.
On the other hand, undefined means that the variable has not been declared, or has not been given a value.
I'll explain undefined, null and Uncaught ReferenceError:
1 - Uncaught ReferenceError : variable has not been declared in your script, there is no reference to this varaible
2 - undefined: Variable declared but does not initialised
3 - null : Variable declared and is an empty value
null and undefined are two distinct object types which have the following in common:
both can only hold a single value, null and undefined respectively;
both have no properties or methods and an attempt to read any properties of either will result in a run-time error (for all other objects, you get value undefined if you try to read a non-existent property);
values null and undefined are considered equal to each other and to nothing else by == and != operators.
The similarities however end here. For once, there is a fundamental difference in the way how keywords null and undefined are implemented. This is not obvious, but consider the following example:
var undefined = "foo";
WScript.Echo(undefined); // This will print: foo
undefined, NaN and Infinity are just names of preinitialized "superglobal" variables - they are initialized at run-time and can be overridden by normal global or local variable with the same names.
Now, let's try the same thing with null:
var null = "foo"; // This will cause a compile-time error
WScript.Echo(null);
Oops! null, true and false are reserved keywords - compiler won't let you use them as variable or property names
Another difference is that undefined is a primitive type, while null is an object type (indicating the absense of an object reference). Consider the following:
WScript.Echo(typeof false); // Will print: boolean
WScript.Echo(typeof 0); // Will print: number
WScript.Echo(typeof ""); // Will print: string
WScript.Echo(typeof {}); // Will print: object
WScript.Echo(typeof undefined); // Will print: undefined
WScript.Echo(typeof null); // (!!!) Will print: object
Also, there is an important difference in the way null and undefined are treated in numeric context:
var a; // declared but uninitialized variables hold the value undefined
WScript.Echo(a === undefined); // Prints: -1
var b = null; // the value null must be explicitly assigned
WScript.Echo(b === null); // Prints: -1
WScript.Echo(a == b); // Prints: -1 (as expected)
WScript.Echo(a >= b); // Prints: 0 (WTF!?)
WScript.Echo(a >= a); // Prints: 0 (!!!???)
WScript.Echo(isNaN(a)); // Prints: -1 (a evaluates to NaN!)
WScript.Echo(1*a); // Prints: -1.#IND (in Echo output this means NaN)
WScript.Echo(b >= b); // Prints: -1 (as expected)
WScript.Echo(isNaN(b)); // Prints: 0 (b evaluates to a valid number)
WScript.Echo(1*b); // Prints: 0 (b evaluates to 0)
WScript.Echo(a >= 0 && a <= 0); // Prints: 0 (as expected)
WScript.Echo(a == 0); // Prints: 0 (as expected)
WScript.Echo(b >= 0 && b <= 0); // Prints: -1 (as expected)
WScript.Echo(b == 0); // Prints: 0 (!!!)
null becomes 0 when used in arithmetic expressions or numeric comparisons - similarly to false, it is basically just a special kind of "zero". undefined, on the other hand, is a true "nothing" and becomes NaN ("not a number") when you try to use it in numeric context.
Note that null and undefined receive a special treatment from == and != operators, but you can test true numeric equality of a and b with the expression (a >= b && a <= b).
Undefined means a variable has been declared but has no value:
var var1;
alert(var1); //undefined
alert(typeof var1); //undefined
Null is an assignment:
var var2= null;
alert(var2); //null
alert(typeof var2); //object
tl;dr
Use null for set a variable you know it is an Object.
Use undefined for set a variable whose type is mixed.
This is my usage of both 5 primitives and Object type, and that explain the difference between « use case » of undefined or null.
String
If you know a variable is only a string while all lifecycle, by convention, you could initialize it, to "":
("") ? true : false; // false
typeof ""; // "string";
("Hello World") ? true : false; // true
typeof "Hello World"; // "string"
Number
If you know a variable is only a number while all lifecycle, by convention, you could initialize it, to 0 (or NaN if 0 is an important value in your usage):
(0) ? true : false; // false
typeof 0; // "number";
(16) ? true : false; // true
typeof 16; // "number"
or
(NaN) ? true : false; // false
typeof NaN; // "number";
(16) ? true : false; // true
typeof 16; // "number"
Boolean
If you know a variable is only a boolean while all lifecycle, by convention, you could initialize it, to false:
(false) ? true : false; // false
typeof false; // "boolean";
(true) ? true : false; // true
typeof true; // "boolean"
Object
If you know a variable is only an Object while all lifecycle, by convention, you could initialize it, to null:
(null) ? true : false; // false
typeof null; // "object";
({}) ? true : false; // true
typeof {}; // "object"
Note: the smart usage off null is to be the falsy version of an Object because an Object is always true, and because typeof null return object. That means typeof myVarObject return consistent value for both Object and null type.
All
If you know a variable has a mixed type (any type while all lifecycle), by convention, you could initialize it, to undefined.
In addition to a different meaning there are other differences:
Object destructuring works differently for these two values:
const { a = "default" } = { a: undefined }; // a is "default"
const { b = "default" } = { b: null }; // b is null
JSON.stringify() keeps null but omits undefined
const json = JSON.stringify({ undefinedValue: undefined, nullValue: null });
console.log(json); // prints {"nullValue":null}
typeof operator
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" instead of "null"
In JavasScript there are 5 primitive data types: String, Number, Boolean, null and undefined.
I will try to explain with some simple examples.
Let's say we have a simple function
function test(a) {
if(a == null) {
alert("a is null");
} else {
alert("The value of a is " + a);
}
}
Also, in above function if(a == null) is the same as if(!a).
Now when we call this function without passing the parameter a
test(); // will alert "a is null";
test(4); // will alert "The value of a is " + 4;
also
var a;
alert(typeof a);
This will give undefined; we have declared a variable but we have not asigned any value to this variable;
but if we write
var a = null;
alert(typeof a); // will give alert as object
so null is an object. In a way we have assigned a value null to 'a'
When you declare a variable in javascript, it is assigned the value undefined. This means the variable is untouched and can be assigned any value in future. It also implies that you don't know the value that this variable is going to hold at the time of declaration.
Now you can explicitly assign a variable null. It means that the variable does not have any value. For example - Some people don't have a middle name. So in such a case its better to assign the value null to the middlename variable of a person object.
Now suppose that someone is accessing the middlename variable of your person object and it has the value undefined. He wouldn't know if the developer forgot to initialize this variable or if it didn't have any value. If it has the value null, then the user can easily infer that middlename doesn't have any value and it is not an untouched variable.
OK, we may get confused when we hear about null and undefined, but let's start it simple, they both are falsy and similar in many ways, but weird part of JavaScript, make them a couple of significant differences, for example, typeof null is 'object' while typeof undefined is 'undefined'.
typeof null; //"object"
typeof undefined; //"undefined";
But if you check them with == as below, you see they are both falsy:
null==undefined; //true
Also you can assign null to an object property or to a primitive, while undefined can simply be achieved by not assigning to anything.
I create a quick image to show the differences for you at a glance.
For the undefined type, there is one and only one value: undefined.
For the null type, there is one and only one value: null.
So for both of them, the label is both its type and its value.
The difference between them. For example:
null is an empty value
undefined is a missing value
Or:
undefined hasn't had a value yet
null had a value and doesn't anymore
Actually, null is a special keyword, not an identifier, and thus you cannot treat it as a variable to assign to.
However, undefined is an identifier. In both non-strict mode and strict mode, however, you can create a local variable of the name undefined. But this is one terrible idea!
function foo() {
undefined = 2; // bad idea!
}
foo();
function foo() {
"use strict";
undefined = 2; // TypeError!
}
foo();
I want to add a knowledge point which pertains to a subtle difference between null and undefined. This is good to know when you are trying to learn Vanilla JavaScript(JS) from ground up:
null is a reserved keyword in JS while undefined is a property on
the global object of the run-time environment you're in.
While writing code, this difference is not identifiable as both null and undefined are always used in right hand side (RHS) of a JavaScript statement. But when you use them in left hand side (LHS) of an expression then you can observe this difference easily. So JS interpreter interprets the below code as error:
var null = 'foo'
It gives below error:
Uncaught SyntaxError: Unexpected token null
At the same time, below code runs successfully although I won't recommend doing so in real life:
var undefined = 'bar'
This works because undefined is a property on the global object (window object in case of JavaScript running in a browser)
null and undefined are both are used to represent the absence of some value.
var a = null;
a is initialized and defined.
typeof(a)
//object
null is an object in JavaScript
Object.prototype.toString.call(a) // [object Object]
var b;
b is undefined and uninitialized
undefined object properties are also undefined. For example "x" is not defined on object c and if you try to access c.x, it will return undefined.
Generally we assign null to variables not undefined.
Per Ryan Morr's thorough article on this subject...
"Generally, if you need to assign a non-value to a variable or property, pass it to a function, or return it from a function, null is almost always the best option. To put it simply, JavaScript uses undefined and programmers should use null."
See Exploring the Eternal Abyss of Null and Undefined
In javascript all variables are stored as key value pairs. Each variable is stored as variable_name : variable_value/reference.
undefined means a variable has been given a space in memory, but no value is assigned to it. As a best practice, you should not use this type as an assignment.
In that case how to denote when you want a variable to be without value at a later point in the code? You can use the type
null ,which is also a type that is used to define the same thing, absence of a value, but it is not the same as undefined, as in this case you actually have the value in memory. That value is null
Both are similar but usage and meaning are different.
The difference in meaning between undefined and null is an accident of JavaScript’s design, and it doesn’t matter most of the time. In cases where you actually have to concern yourself with these values, I recommend treating them as mostly interchangeable.
From the Eloquent Javascript book
As typeof returns undefined, undefined is a type where as null is an initializer indicates the variable points to no object(virtually everything in Javascript is an object).
null - It is an assignment value, which is used with variable to represent no value (it's an object).
undefined - It is a variable which does not have any value assigned to it, so JavaScript will assign an undefined to it (it's a data type).
undeclared - If a variable is not created at all, it is known as undeclared.
Check this out. The output is worth thousand words.
var b1 = document.getElementById("b1");
checkif("1, no argument" );
checkif("2, undefined explicitly", undefined);
checkif("3, null explicitly", null);
checkif("4, the 0", 0);
checkif("5, empty string", '');
checkif("6, string", "string");
checkif("7, number", 123456);
function checkif (a1, a2) {
print("\ncheckif(), " + a1 + ":");
if (a2 == undefined) {
print("==undefined: YES");
} else {
print("==undefined: NO");
}
if (a2 === undefined) {
print("===undefined: YES");
} else {
print("===undefined: NO");
}
if (a2 == null) {
print("==null: YES");
} else {
print("==null: NO");
}
if (a2 === null) {
print("===null: YES");
} else {
print("===null: NO");
}
if (a2 == '') {
print("=='': YES");
} else {
print("=='': NO");
}
if (a2 === '') {
print("==='': YES");
} else {
print("==='': NO");
}
if (isNaN(a2)) {
print("isNaN(): YES");
} else {
print("isNaN(): NO");
}
if (a2) {
print("if-?: YES");
} else {
print("if-?: NO");
}
print("typeof(): " + typeof(a2));
}
function print(v) {
b1.innerHTML += v + "\n";
}
<!DOCTYPE html>
<html>
<body>
<pre id="b1"></pre>
</body>
</html>
See also:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators
Cheers!
The difference between undefined and null is minimal, but there is a difference. A variable whose value is undefined has never been initialized. A variable whose value is null was explicitly given a value of null, which means that the variable was explicitly set to have no value. If you compare undefined and null by using the null==undefined expression, they will be equal.
Basically, Undefined is a global variable that javascript create at the run time whether null means that no value has assigned to the variable (actually null is itself an object).
Let's take an example:
var x; //we declared a variable x, but no value has been assigned to it.
document.write(x) //let's print the variable x
Undefined that's what you will get as output.
Now,
x=5;
y=null;
z=x+y;
and you will get 5 as output. That's the main difference between the Undefined and null
Both special values imply an empty state.
The main difference is that undefined represents the value of a variable that wasn’t yet initialized, while null represents an intentional absence of an object.
The variable number is defined, however, is not assigned with an initial value:
let number;
number; // => undefined
number variable is undefined, which clearly indicates an uninitialized variable
The same uninitialized concept happens when a non-existing object property is accessed:
const obj = { firstName: 'Dmitri' };
obj.lastName; // => undefined
Because lastName property does not exist in obj, JavaScript correctly evaluates obj.lastName to undefined.
In other cases, you know that a variable expects to hold an object or a function to return an object. But for some reason, you can’t instantiate the object. In such a case null is a meaningful indicator of a missing object.
For example, clone() is a function that clones a plain JavaScript object. The function is expected to return an object:
function clone(obj) {
if (typeof obj === 'object' && obj !== null) {
return Object.assign({}, obj);
}
return null;
}
clone({name: 'John'}); // => {name: 'John'}
clone(15); // => null
clone(null); // => null
However, clone() might be invoked with a non-object argument: 15 or null (or generally a primitive value, null or undefined). In such case, the function cannot create a clone, so it returns null - the indicator of a missing object.
typeof operator makes the distinction between the two values:
typeof undefined; // => 'undefined'
typeof null; // => 'object'
The strict quality operator === correctly differentiates undefined from null:
let nothing = undefined;
let missingObject = null;
nothing === missingObject; // => false

JavaScript || or operator with an undefined variable

I have been doing some reading lately one article I read was from Opera.
http://dev.opera.com/articles/view/javascript-best-practices/
In that article they write this:
Another common situation in JavaScript
is providing a preset value for a
variable if it is not defined, like
so:
if(v){
var x = v;
} else {
var x = 10;
}
The shortcut notation for this is the
double pipe character:
var x = v || 10;
For some reason, I can't get this to work for me. Is it really possible to check to see if v is defined, if not x = 10?
--Thanks.
Bryan
That Opera article gives a poor description of what is happening.
While it is true that x will get the value of 10 if v is undefined. It is also true that x will be 10 if v has any "falsey" value.
The "falsey" values in javascript are:
0
null
undefined
NaN
"" (empty string)
false
So you can see that there are many cases in which x will be set to 10 besides just undefined.
Here's some documentation detailing the logical operators. (This one is the "logical OR".) It gives several examples of its usage for such an assignment.
Quick example: http://jsfiddle.net/V76W6/
var v = 0;
var x = v || 10;
alert( x ); // alerts 10
Assign v any of the falsey values that I indicated above, and you'll get the same result.
var x = v || 10;
That operator (the "logical" or "short-circuit" OR operator) would normally check the value of v, and if it is a "falsy" value (i.e. it would fail as a condition used in an if statement), 10 becomes the value of x, otherwise v does (and if 10 were a function, it would never be executed).
undefined, null, and 0 are all examples of falsy values that a variable can hold (yes, even the first one), and the operator (or if statement) acts accordingly. In contrast, all objects and arrays (not including null) are "truthy" values, which allows for such things as this (used in the Google Analytics tracker code):
var _gaq = _gaq || []; // Makes a new array _gaq if it is not already there
However, if the referenced variable is not even declared anywhere within the scope chain, then a JavaScript exception will occur.
One way to avoid this is by declaring all your global variables from the start:
var iAmAGlobalVariable; // Holds the value undefined by default
If this is not possible, you should use the typeof operator. It does not attempt to evaluate its operand, and thus an exception will not occur:
var x;
if(typeof v != 'undefined' && v) {
x = v;
} else {
x = 10;
}
Or even better, if you know that the variable would be a global variable, you can treat it as a property of the global (window) object:
var x = window.v || 10;
If v evaluates to false (for example, 0, null, false) then it won't work. You can manually check for undefined:
var x = v !== undefined ? v : 10;
I would use triple equals with ternary in a function for this.
function myTest(x){
return x === undefined ? true: false;
}
Only returns true if x is undefined
See
(http://www.impressivewebs.com/why-use-triple-equals-javascipt/)
and
(http://jsfiddle.net/V76W6/)
I would just use a try-catch
var x = 0;
try
{
x = v;
}
catch(err)
{
x = 10;
}
Here is how to get it working:
var v; //declare v as undefined
// v = 5; //if uncommented x will be 5
var x = v || 10;
alert(x); //output: 10
http://jsfiddle.net/uLLtu/1/

Categories