0

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..

danny alkhald
  • 131
  • 1
  • 1
  • 4

5 Answers5

7

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

Community
  • 1
  • 1
BuddhiP
  • 6,231
  • 5
  • 36
  • 56
3
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

Ry-
  • 218,210
  • 55
  • 464
  • 476
TGH
  • 38,769
  • 12
  • 102
  • 135
  • Btw you dont need to set it to null just `var dan;` would suffice. – PSL Jun 25 '13 at 01:57
  • I tried the tow versions before I ask. Both of them don't work. – danny alkhald Jun 25 '13 at 02:03
  • Ok now I see. the problem was that I didn't use "var" keyword. – danny alkhald Jun 25 '13 at 02:05
  • 1
    @dannyalkhald you should really provide more context here. Be careful when you add "var" as it redefines the dan for current scope, and hides any existing dan, point is: just adding a keyword may not be the proper solution, try to learn how variables/scope behaves in JavaScript – BuddhiP Jun 25 '13 at 02:41
  • I know that var define the scope of the variable but I don't know why it's significant in this context. – danny alkhald Jun 25 '13 at 02:50
  • The absence of _var_ means that a variable will be treated as global. – jahroy Jun 25 '13 at 03:31
1

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

FabianCook
  • 20,269
  • 16
  • 67
  • 115
  • Javascript exacerabates this confusion by allowing you to explicitly assign `undefined` to a variable, and it's different from not defining the variable in the first place. – Barmar Jun 25 '13 at 02:00
  • Does this answer the question? – Ry- Jun 25 '13 at 02:02
  • I was more so explaining the situation where you could use it. The problem with the code is that `dan` is not defined at all which is the answer, but thats to easy.. – FabianCook Jun 25 '13 at 02:09
  • If I use an object as the function argument like this function: function da (d){this.a = d.a || 5;} will it work? – danny alkhald Jun 25 '13 at 02:18
  • if d is an object then yes given d.a is falsy 5 would be taken. Eg if you call da like so `da({})` then `this.a` will equal `5` however is you call `da();` then you will get a javascript error `can not call property 'a' of undefined` or something similar – FabianCook Jun 25 '13 at 02:25
  • @dannyalkhald In your example I would check if d was passed and has an a property: `this.a=(d===undefined)?5:(d.a===undefined)?5:d.a;` – HMR Jun 25 '13 at 02:33
  • 1
    @SmartLemon Great! That's exactly the situation that I want to use the "||" operator for. – danny alkhald Jun 25 '13 at 02:38
  • @ HMR I will check for the d object, but is it necessary to check if it has the a property? – danny alkhald Jun 25 '13 at 02:40
  • @ HMR This says It's not necessary to check for the property http://stackoverflow.com/questions/17288317/undefined-vs-defined-window-property-in-javascript – danny alkhald Jun 25 '13 at 03:20
1

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
HMR
  • 37,593
  • 24
  • 91
  • 160
  • 1
    Its not safe to compare a variable directly to 'undefined' as in some cases, undefined itself can be assigned to something else, in which case these checks will fail. Better way is to check with typeof operator: typeof(dan) === 'undefined' – BuddhiP Jun 25 '13 at 02:37
  • @BuddhiP You are correct but who in their right mind would re define undefined or window? A way around it is to do like jQuery: (function(window,undefined){your code })(window); If you're making a library to be consumed by anyone (even those who re define window and or udefined) than you make a valid point. – HMR Jun 25 '13 at 02:57
  • typeof(dan) will not throw an error when dan wasn't declared (undefined variable). So the example code won't behave the same. – HMR Jun 25 '13 at 02:59
  • it will not throw errors when `dan` is undefined. http://jsfiddle.net/BuddhiP/Gv52L/1/, And yes no one in 'right mind' will do it, but right mind is a relative term :). Some programmers write same as (undefined == varname) (practice from other languages where writing if (null == var) to prevent accidental assignments), but in those cases they may cause accidental assignments in JS (undefined = varname) bcs JS doesn't prevent assigning to 'undefined'.. that's one way this could break. Anyways, my point is its better to be safe. :) – BuddhiP Jun 25 '13 at 03:09
0

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.

Ani
  • 4,473
  • 4
  • 26
  • 31