Truthy and falsy value and data types with interview questions and their answers
Hari Mohan Prajapat
SD 3 at UST | Frontend Engineer (React, Next.js, TypeScript, JavaScript) | Python (Django, Flask, Pandas, NumPy, Jupyter) | AWS Computing | Author | Building Happy Software engineer's Community | Fitness Freak|25k
In JavaScript, "truthy" and "falsy" are terms used to describe values based on how they are evaluated in a boolean context.
### Falsy Values
These are values that evaluate to false when used in a condition. Here are the falsy values in JavaScript:
- false
- 0 (the number zero)
- "" (empty string)
- null
- undefined
- NaN (Not-a-Number)
Example:
```javascript
if (0) {
console.log("This won't run because 0 is falsy.");
} else {
console.log("0 is falsy."); // This will execute.
}
```
### Truthy Values
All values other than the falsy ones are considered "truthy." This includes non-empty strings, non-zero numbers, objects, arrays, etc.
Example:
```javascript
if ("hello") {
console.log("This will run because 'hello' is truthy."); // This will execute.
}
```
---
### JavaScript Data Types
JavaScript has two categories of data types: Primitive and Non-Primitive (Reference).
#### Primitive Data Types
1. Number: Represents numeric values.
- Example: let age = 25;
2. String: Represents sequences of characters.
- Example: let name = "Alice";
3. Boolean: Represents true or false.
- Example: let isHappy = true;
4. Undefined: A variable declared but not assigned a value.
- Example: let x; // x is undefined
5. Null: Represents an intentional absence of value.
- Example: let y = null;
6. Symbol: Represents unique identifiers (introduced in ES6).
- Example: let sym = Symbol("id");
7. BigInt: For numbers larger than Number.MAX_SAFE_INTEGER (introduced in ES2020).
- Example: let bigNumber = 123n;
#### Non-Primitive (Reference) Data Types
1. Object: A collection of key-value pairs.
- Example:
let person = {
name: "Alice",
age: 25
};
2. Array: A list-like object.
- Example:
let fruits = ["apple", "banana", "cherry"];
3. Function: A block of code designed to perform a task.
- Example:
function greet() {
console.log("Hello!");
}
Certainly! Here are some more examples of truthy values in JavaScript:
1. Non-empty Strings: Any string that is not empty, even with a single space.
if (" ") {
console.log("A single space is truthy.");
}
if ("hello") {
console.log("'hello' is truthy.");
}
2. Non-zero Numbers: Positive, negative, or even decimals.
if (42) {
console.log("42 is truthy.");
}
if (-3.14) {
console.log("-3.14 is truthy.");
}
3. Objects: Even empty objects are considered truthy.
if ({}) {
console.log("An empty object is truthy.");
}
4. Arrays: Just like objects, even empty arrays are truthy.
if ([]) {
console.log("An empty array is truthy.");
}
```
5. Infinity and -Infinity: These special numeric values are truthy.
if (Infinity) {
console.log("Infinity is truthy.");
}
if (-Infinity) {
console.log("-Infinity is truthy.");
}
6. Functions: Any function (even an empty one) is truthy.
function example() {}
if (example) {
console.log("A function is truthy.");
}
7. Dates: A Date object is always truthy.
if (new Date()) {
console.log("A Date object is truthy.");
}
some potential interview questions related to truthy and falsy values and data types in JavaScript, along with tips on answering them effectively
Here are some potential interview questions related to **truthy and falsy values** and **data types** in JavaScript, along with tips on answering them effectively:
---
### **Truthy and Falsy Values**
1. **What are truthy and falsy values in JavaScript? Can you give examples?**
- Tip: Clearly define the terms and provide examples like 0, undefined (falsy), and "hello", [] (truthy).
2. **Why does 0 == false evaluate to true, but 0 === false evaluates to false?**
- Tip: Explain the difference between == (type coercion) and === (strict equality).
3. **Can you provide examples of edge cases where falsy values might cause bugs?**
- Tip: Mention scenarios like checking an empty array (`[]`) or object (`{}`) in conditions.
4. **How can you explicitly check if a value is truthy or falsy in JavaScript?**
- Tip: Mention using Boolean(value) or the double-bang (`!!`) operator.
5. **How does JavaScript treat empty strings and null values in boolean conditions?**
- Tip: Explain that both are treated as falsy.
---
### **JavaScript Data Types**
1. **What are the primitive and non-primitive data types in JavaScript?**
- Tip: List all types like Number, String, Object, etc., and explain their differences.
2. **What is the difference between null and undefined?**
- Tip: Highlight that null is an assigned absence of value, while undefined means a variable hasn't been assigned a value.
3. **What are the unique features of the Symbol and BigInt data types?**
- Tip: Explain Symbol for creating unique identifiers and BigInt for handling large numbers.
4. **Is JavaScript dynamically typed or statically typed? Explain with an example.**
- Tip: Mention that JavaScript is dynamically typed, meaning you don’t declare variable types explicitly:
let x = "hello"; // x is a string
x = 5; // x is now a number
5. **Can you explain the concept of type coercion in JavaScript?**
- Tip: Discuss how JavaScript automatically converts one data type to another during comparisons or calculations.
6. **How do objects differ from primitive data types in JavaScript?**
- Tip: Explain that primitives are immutable, while objects are mutable and passed by reference.
7. **How can you check the type of a variable in JavaScript?**
- Tip: Mention typeof and its usage:
```javascript
console.log(typeof 42); // "number"
console.log(typeof "hello"); // "string"
---
### **Combination Questions**
1. **What happens when you try to compare a truthy value to a falsy value?**
- Tip: Provide examples:
console.log(1 == true); // true
console.log(1 === true); // false
```
2. **What is the output of the following code? Explain why:**
console.log(Boolean({})); // ?
console.log(Boolean([])); // ?
console.log(Boolean("0")); // ?
console.log([] == false); // ?
- Tip: Walk through the evaluation of each expression.
3. **Can you create a simple function to filter out falsy values from an array?**
- Tip: Demonstrate using the filter() method:
let arr = [0, 1, false, 2, "", 3];
let truthyValues = arr.filter(Boolean);
console.log(truthyValues); // [1, 2, 3]