• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Truthy and Falsy in JS: What Every Developer Should Know

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
Stop Guessing: Understand JavaScript Equality the Right Way


When you start working with JavaScript, one of the first things you notice is how flexible it feels. You can assign different types of values to the same variable and JavaScript won’t complain. This flexibility is great—but it can also lead to unexpected bugs, especially when you're comparing values or checking if something is "true" or "false."

Let’s break down some of these concepts in a beginner-friendly way so you can write safer and more predictable JavaScript code.

? JavaScript Variables Are Loosely Typed


In JavaScript, you don’t need to declare the type of a variable. For example:


let x = 5; // x is a number
x = "hello"; // now x is a string
x = true; // now x is a boolean

This is called loose typing—a variable can hold any type of data, and JavaScript doesn’t stop you from changing it. While this is super convenient, it can be dangerous when you start comparing values.

Loose vs Strict Equality: What’s the Difference?

Loose Equality (==)


This operator tries to be helpful by converting values to the same type before comparing them.


0 == false // true ?
"" == false // true ?
"0" == 0 // true ?

These results can be very confusing, especially for beginners!

Strict Equality (===)


This operator compares both value and type. So if the types are different, the result is false.


0 === false // false ✅
"" === false // false ✅
"0" === 0 // false ✅
? Best Practice: Use === (strict equality) instead of == to avoid weird bugs.
✅ Truthy and Falsy Values


Every value in JavaScript is either truthy or falsy when used in a Boolean context (like inside an if statement).

Falsy Values


These are the ones treated as false:


false
0
-0
0n // BigInt zero
""
null
undefined
NaN

Any other value is considered truthy.

Truthy Values Examples


"0" // a non-empty string
"false" // also a non-empty string
[] // empty array
{} // empty object
function() {} // function (even if it's empty)
? Surprise Alert: [] is truthy, but [] == false is true. Wait, what?! Let's talk about that…
Why Comparisons Can Get Weird


Let’s look at a real example:


[] == false // true ?‍?
[] === false // false ✅

That first result is possible because JavaScript converts the empty array ([]) to a string (""), then compares it to false, which also converts to "". This is how we get weird results.

Another one:


"" == 0 // true ?
"" === 0 // false ✅

You can quickly see how loose equality (==) can trick you.

? How to Stay Safe with Truthy/Falsy Values


To write clean and bug-free JavaScript, follow these simple rules:

1. Use Strict Equality (===)


Always prefer === over == unless you know exactly what you're doing.


if (value === false) {
// do something
}
2. Convert to Boolean Explicitly


If you're not sure whether something is truthy or falsy, convert it to a Boolean using !!:


const isValid = !!userInput;

This way, you get a real true or false value.

3. Avoid Direct Comparisons with Falsy Values


Don’t compare values directly to true or false. Instead, rely on strict equality or Boolean conversion.

Bad:


if (value == false) {
// tricky behavior
}

Good:


if (!value) {
// easier to understand
}

Or even better:


if (value === false) {
// very specific check
}
Final Thoughts


JavaScript gives you a lot of freedom, but with that comes the need for caution. By understanding how equality and truthy/falsy values work under the hood, you can:

  • Avoid confusing bugs ?
  • Write clearer and safer code
? Tip: If you're ever stuck, use console.log(typeof value, value) to debug what's going on!
✅ Summarization


Here's a handy table to quickly identify which values are truthy and which are falsy in JavaScript:

ValueTypeTruthy or FalsyNotes
falseBooleanFalsyThe literal false
0NumberFalsyZero is considered falsy
-0NumberFalsyNegative zero is also falsy
0nBigIntFalsyBigInt zero
""StringFalsyEmpty string
nullNullFalsyRepresents absence of value
undefinedUndefinedFalsyUnassigned or missing value
NaNNumberFalsy"Not a Number", often from invalid math
"0"StringTruthyNon-empty string, even if it looks like zero
"false"StringTruthyNon-empty string
" " (space)StringTruthyContains a space character
[]Array(Special Type of Object)TruthyEmpty array (Arrays are a special type of object, which means that the typeof operator will return "object" for arrays. However, arrays have unique properties and methods that distinguish them from regular objects)
[0]Array(Special Type of Object)TruthyContains one element (typeof operator will return "object" for arrays)
{}ObjectTruthyEmpty object
{ a: 1 }ObjectTruthyNon-empty object
function() {}FunctionTruthyFunctions are always truthy
InfinityNumberTruthyNot zero, so it's truthy
-InfinityNumberTruthySame as above
trueBooleanTruthyThe literal true
42NumberTruthyAny non-zero number is truthy
✅ Ready to Practice?


If you're just starting out with JavaScript, understanding truthy and falsy is a huge milestone!

Try reading from other different sources.

? Got questions or ideas? Leave a comment — I’d love to hear from you!

? Follow me for beginner-friendly coding tutorials every week:



Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу