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

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

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

⚡ The Power of `!` in Frontend Development: Writing Safer, Cleaner Code

Sascha Оффлайн

Sascha

Заместитель Администратора
Команда форума
Администратор
Регистрация
9 Май 2015
Сообщения
1,483
Баллы
155

From debugging strange UI behavior to preventing silent production bugs — mastering the ! operator helps frontend developers write robust and reliable applications.
? What Does ! Actually Do?


In JavaScript:

  • !value → converts the value to a boolean and negates it.
  • !!value → converts the value to its boolean equivalent.
Examples:


!false // true
!!false // false
!!"hello" // true
!!0 // false



? Why Should Senior Developers Care?


In real-world production code:

  • APIs return unpredictable types ("", 0, null)
  • UI logic silently fails
  • Unexpected behavior emerges due to implicit falsy checks

Using ! and !! intentionally helps reduce bugs early — before they ship.

✅ 1. Boolean Coercion with !!

Problem:


const isLoggedIn = 0; // comes from backend

if (isLoggedIn) {
showDashboard(); // ❌ Won’t run!
}



Fix:


const isUserLoggedIn = !!isLoggedIn;




This ensures:


!!0 // false
!!1 // true
!!"" // false
!!"hello" // true
!!undefined // false
!![] // true



✅ 2. Conditional Rendering in React

Before:


{user && user.name && <p>Welcome, {user.name}</p>}



Cleaner:


{!!user?.name && <p>Welcome, {user.name}</p>}




Or:


{user?.name ? <p>Welcome, {user.name}</p> : null}




This prevents weird issues when user.name is "" or 0.

✅ 3. Validate Empty Inputs


function handleSubmit(email) {
if (!email) {
showToast("Email is required.");
return;
}
submit(email);
}




Catches: null, undefined, "", 0, etc.

✅ 4. Control Classnames


<button className={!!isActive ? "btn active" : "btn"}>
Click
</button>




This avoids undefined or null from breaking class logic.

✅ 5. Guarding API Responses


const user = res.data.user || {};
if (!!user?.isAdmin) {
// Works even if isAdmin is 0 or undefined
}



? Bonus: Defensive Programming


if (!config?.apiKey) {
throw new Error("Missing API key");
}

if (!props.onClick) {
console.warn("Button missing onClick handler");
}




Be proactive — catch bugs before they appear.

⚠ Common Pitfalls

PatternWhy It’s Risky
if (arr.length)Will throw if arr is null
if (!input.value)Fails when value is 0
Overusing !! Don’t coerce if types are already known
?‍? Real-World Example


function UserBadge({ user }) {
if (!user) return null;

const isVerified = !!user?.emailVerified;

return (
<div className="badge">
{user.name}
{isVerified && <span className="verified">✔</span>}
</div>
);
}



? TL;DR

Use CaseCode ExampleWhy
Coercion to Boolean!!valueConvert reliably
Flip condition!valueInvert logic
Guard clausesif (!thing)Defensive coding
Conditional rendering{!!thing && <Comp />}Clean JSX checks
✅ Conclusion


The ! and !! operators may seem trivial, but when used with intent, they prevent:

  • Crashes
  • Silent failures
  • Debugging nightmares

Next time you check a value — ask yourself:

Should I !! this just to be sure?
Happy debugging! ?



Источник:

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

 
Вверх Снизу