Sunday 9 June 2019

javascript - What is this communicating: my_var = my_var || 69





I saw this in a Javascript example



my_var = my_var || 69



I assume it means to check if my_var exists, if not set my_var to 69. Is this the case? Is there any documentation on this, it is very hard to represent as a google/SO search, could somebody point me in the direction of docs or duplicate QA?



(The example didn't use 69, that's just me being crass)


Answer



Easy enough to try in the JS console.



var my_var
my_var = my_var || 69
//69


var my_var = 5
my_var = my_var || 69
//5


You are setting the variable only if it is currently carrying a falsy value.



Falsy values in JS are:





  1. false

  2. null

  3. undefined

  4. The empty string ''

  5. The number 0

  6. The number NaN


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...