Back to Course

Introduction to JavaScript

0% Complete
0/0 Steps
  1. JavaScript: Basics
    9Topics
    |
    10 Quizzes
  2. JavaScript: Variables
    9Topics
    |
    10 Quizzes
  3. JavaScript: Conditional Statements
    10Topics
    |
    11 Quizzes
  4. JavaScript: Functions
    10Topics
    |
    11 Quizzes
  5. JavaScript: Scope
    6Topics
    |
    7 Quizzes
  6. JavaScript: Arrays
    11Topics
    |
    12 Quizzes
  7. JavaScript: Loops
    8Topics
    |
    9 Quizzes
  8. JavaScript: High Order Functions
    3Topics
    |
    4 Quizzes
  9. JavaScript: Iterators
    6Topics
    |
    6 Quizzes
Lesson 3, Topic 7
In Progress

JavaScript: Truthy and Falsy Assignment

Yasin Cakal 2 Nov 2021
Lesson Progress
0% Complete

Both true and false evaluations, bring up a world of short-hand possibilities!

Assume you have a website and want to create a customized invitation card using a user’s username. The username variable might be false if the user does not have an account. The code below checks if the username is defined and, if it isn’t, assigns a default string:

let userName = '';
let defaulter;
if (userName) {
  defaulter = userName;
 } else {
  defaulter = 'New User';
 }
console.log(defaulter); 

// Prints: New User

You can use a shorthand for the code above if you combine your understanding of logical operators. When you use the || operator in a boolean condition, JavaScript assigns the truthy value to a variable:

let username = '';
let defaulter = username || 'New User';
console.log(defaulter); 

// Prints: New User

Because || check the left-hand condition first, the variable defaulter will be given the value of username if it is true, and New User if it is false. This concept is referred to as “short-circuit evaluation”.

Responses

Leave a Reply

%d bloggers like this: