Javascript document all true

Why Does !document.all Return True in JavaScript

Uncovering the reason why this code returns true and what it means for your code

JavaScript is an incredibly versatile and widely-used programming language. As with any language, it has its quirks, and one of the puzzlings is the behavior of the !document.all expression.

A Brief History of JavaScript and DOM

To understand the context of !document.all , we must first take a brief look at the history of JavaScript and the Document Object Model (DOM). JavaScript was created by Brendan Eich in 1995, and it was initially developed for the Netscape Navigator browser. The language was designed to be easy to use and learn, but it was also developed quickly, leading to some quirks that persist today.

The DOM is a tree-like representation of an HTML document, allowing JavaScript to manipulate the elements and their attributes. Early browsers, such as Netscape Navigator and Internet Explorer, had their own implementations of the DOM, which led to compatibility issues. One such feature was the document.all collection, introduced by Internet Explorer.

Читайте также:  Html почему не подключается шрифт

Understanding document.all

document.all is a non-standard feature that was introduced by Microsoft in Internet Explorer 4.0 to access all elements in an HTML document. It predates the standardized document.getElementById and document.querySelector methods that are now commonly used. The document.all collection was later adopted by other browsers for compatibility reasons, but its use is discouraged in favor of standard DOM methods.

An example of using document.all is as follows:










Type Coercion in JavaScript

JavaScript is a loosely typed language, meaning variables can hold values of any data type without any prior declaration. This…

Источник

Document: all property

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The Document interface’s read-only all property returns an HTMLAllCollection rooted at the document node. In other words, it returns all of the document’s elements, accessible by order (like an array) and by ID (like a regular object).

Value

An HTMLAllCollection which contains every element in the document.

Special type conversion behavior

For historical reasons, document.all is an object that in many ways behaves like undefined . Specifically:

These special behaviors ensure that code like:

if (document.all)  // Assume that we are in IE; provide special logic > // Assume that we are in a modern browser 

Will continue to provide modern behavior even if the code is run in a browser that implements document.all for compatibility reasons.

However, in all other contexts, document.all remains an object. For example:

  • It is not strictly equal to either undefined or null .
  • When used on the left-hand side of the nullish coalescing operator ( ?? ) or the optional chaining operator ( ?. ), it will not cause the expression to short-circuit.

Specifications

Browser compatibility

BCD tables only load in the browser

Found a content problem with this page?

This page was last modified on Jun 20, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Условия в JS. Истинные и ложные значения

Условия в JS. Истинные и ложные значения

JavaScript

Разберем примеры значений которые являются ложными и истинными в JavaScript.

Например когда в JS мы делаем проверку if (0) < . >, 0 преобразуется к ложному значению и равносилен false. А когда проверка идет на пустой массив if ([]) < . >, то пустой массив будет приведен к значение true и это будет считаться истинным значением.

Далее приведены таблицы истинных и ложных значений в JavaScript.

Ложные значение в JavaScript

Значение Описание
false Ключевое слово false
0 Ноль типа Number . К нему также относятся 0.0 , 0x0 и т.д.
-0 Отрицательный ноль типа Number . К нему также относятся -0.0 , -0x0 и т.д.
0n Ноль типа BigInt (также 0x0n ). Обратите внимание, что не может быть негативного нуля типа BigInt — отрицательный 0n равняется 0n .
«» , » , ` « Значение, содержащее пустую строку .
null null — отсутствие какого-либо значения.
undefined undefined — примитивное значение.
NaN NaN — значение, не являющиеся числом.
document.all Объекты считаются ложноподобными тогда и только тогда, когда у них есть внутренний слот [[IsHTMLDDA]] . Этот слот есть только в объекте document.all , и его нельзя задать через JavaScript.

таблица ложных значений в JavaScript

Примеры ложных значений в JavaScript

if (false) // false if (null) // false if (undefined) // false if (0) // false if (-0) // false if (0n) // false if (NaN) // false if ("") // false

Истинные значения в JavaScript

Любое значение которое не является ложным false , будет приведено к истинному true .

Значение Описание
«abc» , ‘abc’ , `abc` Любая не пустая строка, тип String .
«0» Строка с символом «0» . Любая не пустая строка, тип String .
«false» Строка с текстом «false» . Любая не пустая строка, тип String .
100 , -100 , 3.14 , -3.14 Любое положительное или отрицательное число, не являющееся нулем. Тип Number .
12n Число типа BigInt , не являющееся нулем.
Infinity , -Infinity Бесконечность и минус бесконечность является истинным значением.
[] Пустой массив является истинным true
<> Пустой объект является истинным true

Таблица истинных значений в JavaScript

Примеры истинных значений в JavaScript

if (true) // true if (<>) // true if ([]) // true if (42) // true if ("0") // true if ("false") // true if (new Date()) // true if (-42) // true if (12n) // true if (3.14) // true if (-3.14) // true if (Infinity) // true if (-Infinity) // true

Источник

Boolean

The Boolean object represents a truth value: true or false .

Description

Boolean primitives and Boolean objects

Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object.

Any object, including a Boolean object whose value is false , evaluates to true when passed to a conditional statement. For example, the condition in the following if statement evaluates to true :

const x = new Boolean(false); if (x)  // this code is executed > 

This behavior does not apply to Boolean primitives. For example, the condition in the following if statement evaluates to false :

const x = false; if (x)  // this code is not executed > 

Do not use the Boolean() constructor with new to convert a non-boolean value to a boolean value — use Boolean as a function or a double NOT instead:

const good = Boolean(expression); // use this const good2 = !!expression; // or this const bad = new Boolean(expression); // don't use this! 

If you specify any object, including a Boolean object whose value is false , as the initial value of a Boolean object, the new Boolean object has a value of true .

const myFalse = new Boolean(false); // initial value of false const g = Boolean(myFalse); // initial value of true const myString = new String("Hello"); // string object const s = Boolean(myString); // initial value of true 

Warning: You should rarely find yourself using Boolean as a constructor.

Boolean coercion

Many built-in operations that expect booleans first coerce their arguments to booleans. The operation can be summarized as follows:

  • Booleans are returned as-is.
  • undefined turns into false .
  • null turns into false .
  • 0 , -0 , and NaN turn into false ; other numbers turn into true .
  • 0n turns into false ; other BigInts turn into true .
  • The empty string «» turns into false ; other strings turn into true .
  • Symbols turn into true .
  • All objects become true .

Note: A legacy behavior makes document.all return false when used as a boolean, despite it being an object. This property is legacy and non-standard and should not be used.

Note: Unlike other type conversions like string coercion or number coercion, boolean coercion does not attempt to convert objects to primitives.

In other words, there are only a handful of values that get coerced to false — these are called falsy values. All other values are called truthy values. A value’s truthiness is important when used with logical operators, conditional statements, or any boolean context.

There are two ways to achieve the same effect in JavaScript.

  • Double NOT: !!x negates x twice, which converts x to a boolean using the same algorithm as above.
  • The Boolean() function: Boolean(x) uses the same algorithm as above to convert x .

Note that truthiness is not the same as being loosely equal to true or false .

if ([])  console.log("[] is truthy"); > if ([] == false)  console.log("[] == false"); > // [] is truthy // [] == false 
[] is truthy, but it’s also loosely equal to false . It’s truthy, because all objects are truthy. However, when comparing with false , which is a primitive, [] is also converted to a primitive, which is «» via Array.prototype.toString() . Comparing strings and booleans results in both being converted to numbers, and they both become 0 , so [] == false is true . In general, falsiness and == false differ in the following cases:

  • NaN , undefined , and null are falsy but not loosely equal to false .
  • «0» (and other string literals that are not «» but get coerced to 0) is truthy but loosely equal to false .
  • Objects are always truthy, but their primitive representation may be loosely equal to false .

Truthy values are even more unlikely to be loosely equal to true . All values are either truthy or falsy, but most values are loosely equal to neither true nor false .

Constructor

Creates a new Boolean object.

Instance properties

These properties are defined on Boolean.prototype and shared by all Boolean instances.

The constructor function that created the instance object. For Boolean instances, the initial value is the Boolean constructor.

Instance methods

Returns a string of either true or false depending upon the value of the object. Overrides the Object.prototype.toString() method.

Returns the primitive value of the Boolean object. Overrides the Object.prototype.valueOf() method.

Examples

Creating Boolean objects with an initial value of false

const bNoParam = new Boolean(); const bZero = new Boolean(0); const bNull = new Boolean(null); const bEmptyString = new Boolean(""); const bfalse = new Boolean(false); 

Creating Boolean objects with an initial value of true

const btrue = new Boolean(true); const btrueString = new Boolean("true"); const bfalseString = new Boolean("false"); const bSuLin = new Boolean("Su Lin"); const bArrayProto = new Boolean([]); const bObjProto = new Boolean(>); 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jun 25, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Оцените статью