This is my first article , so apologies in advance! But today I wanted to share my analogy to understand return statement in Javascript.
Suppose you went to a shop to buy a bag of chips which costs $9 and you handed him a $10 currency note , you would get $1 in return right?? So let us translate this scenario to code!!
Codepen here π https://codepen.io/sougataghar47/pen/NWXQWoj
var potatoeChipsPrice = 9;
var moneyYouGave = 10;
function buyChips(itemCost, money) {
//if you gave extra money to the shopkeeper
if (money > itemCost) {
var change = money - itemCost; //to calculate how much extra money you gave to shopkeeper
return change; //think of it as your shopkeeper returning the extra money as change like you would expect in real life
}
//returns undefined if you don't match the above condition as undefined is the default return value if you do not specify what to return
}
var returnedMoney = buyChips(potatoeChipsPrice, moneyYouGave); //you went to the counter and gave 10 dollars and now you should get 1 dollar back
console.log("Returned Money in dollar(s) = " + returnedMoney); //if you check the console, you would see 1 dolar returned
And this is why return statements are useful because there could be cases where it would make sense to return a value like you wouldn't want a shopkeeper that returns nothing if you gave him extra money , right?
You can return any value such as array,object,number,string,boolean,etc.A function will always return undefined if you don't specify what to return. Don't be worried about it if you don't choose to specify.
Hope I made some sense with my analogy because I think its easier to understand code when you can relate to real life scenarios! Please let me know if you like my analogy as I may write more articles about how I think about coding and if people can relate :)!
Top comments (0)