7 - Why is there an "or" ( || ) in the addition?


#1

Just wondering what this (highlighted in bold) is supposed to be in the original code:

add: function(itemCost){
this.total += (itemCost || 0);
this.lastTransactionAmount = itemCost;
},

If I'm not mistaken, this would mean that itemCost or 0 should be added to this.total ... but that does not seem to make much sense. After all, this is a simple mathematical addition, not an if statement. Neither do we want to work with booleans here, just with numbers. So what is this supposed to be and why is it there?


#2

@gabriel1379,

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
[quote]
o6 = false || "Cat" // f || t returns "Cat"
[end-quote]

You could do a test

var test = function(itemCost) {
    console.log( itemCost );
    var cost = itemCost || 0;
    console.log( cost );
};
test(); //Not using an argument will lead to =itemCost= being =undefined=

the undefined Value
will be Interpreted as a so-calloed falsy
https://developer.mozilla.org/en-US/docs/Glossary/Falsy


#3

@gabriel1379,

the FUNCTION talk

var myFunc = function( param1, param2) {
       //Begin of  anonymous FUNCTION-BODY
       //VARIABLE -myFunc- has an -anonymous function- assigned
       //this -anonymous function- has 2 PARAMETERS param1 and param2
       //param1 and param2 PARAMETERS are used 
       //as -local- VARIABLES throughout the FUNCTION-BODY

      console.log( param1 + " and " + param2 ) ;

      //End of anonymous FUNCTION-BODY
};

If you want to call/execute the anonymous function
you will have to add a pair of parentheses to the variable myFunc
like
myFunc();
As the anonymous function was defined
as having 2 parameters
you have to provide 2 arguments
in our case 2 string VALUES "Alena" and "Lauren"
like
myFunc("Alena","Lauren");

some quotes from the outer-world:

**argument is the value/variable/reference being passed in,
parameter is the receiving variable used within the function/block**

OR

**"parameters" are called "formal parameters",
while "arguments" are called "actual parameters".**


#4

That explains it, thank you.


#5

@gabriel1379,

google search
== the Book ==
jquery [your question] site:developer.mozilla.org
CSS [your question] site:developer.mozilla.org
javascript [your question] site:developer.mozilla.org
[your question] site:jquery.com
[your question] site:getbootstrap.com

== discussions / opinions ==
jquery [your question] site:stackoverflow.com
CSS [your question] site:stackoverflow.com
javascript [your question] site:stackoverflow.com

== guidance ==
www.crockford.com
[your question] site:crockford.com
- - http://javascript.crockford.com/code.html
- - http://javascript.crockford.com/survey.html

http://stackoverflow.com/questions/1795438/load-and-execution-sequence-of-a-web-page
http://www.w3schools.com/jquery/trysel.asp