Skip to content

Instantly share code, notes, and snippets.

@robwilson1
Last active August 21, 2018 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robwilson1/3ff673af6b4b3e479eee77e088d78fb0 to your computer and use it in GitHub Desktop.
Save robwilson1/3ff673af6b4b3e479eee77e088d78fb0 to your computer and use it in GitHub Desktop.
True False

Truthy and Falsey

Intro

In JavaScript things can either be true or false. Often we want to perform some code based on weather a condition is true or false.

	// Pretend code
	if TRUE do THIS
	otherwise do THAT

Let's look at common truthy values:

  • The Boolean true - true
  • A non empty String - 'hi', 'a'
  • A non zero Number - -4, 50, 10045, 1
  • Any Array - [0, 1, 2], ['a'], []
  • Any Object - {}, { name: 'bobby' }

Let's look at common falsey values:

  • The Boolean false - false
  • The number 0 - 0
  • An empty String - ''
  • NaN
  • null
  • undefined

Testing to see if something is true or false

Often in your code you need to test multiple things and act on them based on the following:

  • At least one of the things is true/false
  • If ALL of the things are true/false

To do this, we use AND and OR logic gates:

AND logic gate

A B RESULT
0 0 FALSE
1 0 FALSE
0 1 FALSE
1 1 TRUE

OR logic gate

A B RESULT
0 0 FALSE
1 0 TRUE
0 1 TRUE
1 1 TRUE

It is possible to use as many parameters as you want to test, but it starts to get very difficult to follow after 3.

Reversing True and False

A special symbol in JavaScript and most other programming languages is the NOT symbol. This is the exclamation mark !

NOT logic gate

A RESULT
0 TRUE
1 FALSE

Convert anything to a boolean

You can take anything and convert it to a simple true false boolean value by using the special JavaScript symbol !! (two exclamation marks).

Running this on the number 42: !!42 will become the Boolean true Running this on the number 0: !!0 will become the Boolean false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment