Html boolean to string

JavaScript Boolean toString()

The toString() method is used internally by JavaScript when an object needs to be displayed as a text (like in HTML), or when an object needs to be used as a string.

Normally, you will not use it in your own code.

Syntax

Parameters

Return Value

Browser Support

toString() is an ECMAScript1 (ES1) feature.

ES1 (JavaScript 1997) is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Boolean.prototype.toString()

The toString() method returns a string representing the specified boolean value.

Try it

Syntax

Return value

A string representing the specified boolean value.

Description

The Boolean object overrides the toString method of Object ; it does not inherit Object.prototype.toString() . For Boolean values, the toString method returns a string representation of the boolean value, which is either «true» or «false» .

The toString() method requires its this value to be a Boolean primitive or wrapper object. It throws a TypeError for other this values without attempting to coerce them to boolean values.

Because Boolean doesn’t have a [@@toPrimitive]() method, JavaScript calls the toString() method automatically when a Boolean object is used in a context expecting a string, such as in a template literal. However, boolean primitive values do not consult the toString() method to be coerced to strings — rather, they are directly converted using the same algorithm as the initial toString() implementation.

Boolean.prototype.toString = () => "Overridden"; console.log(`$true>`); // "true" console.log(`$new Boolean(true)>`); // "Overridden" 

Examples

Using toString()

const flag = new Boolean(true); console.log(flag.toString()); // "true" console.log(false.toString()); // "false" 

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 Feb 21, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

doctor Brain

Сегодня мы напишем функцию booleanToString , которая будет иметь единственный аргумент — булево значение b и возвращать строку: true, если входящий аргумент — истина (true) или false, если входящий аргумент — ложь (false). Таким образом, наша функция будет преобразовывать булево значение в строчное.

Данная задача очень проста и не вызывает каких-либо проблем в реализации. Тем не менее, мы можем рассмотреть решения, использующие различные подходы и позволяющие сократить код до одной строки.

Итак, первое и наиболее очевидное решение — это использование условного оператора if :

function booleanToString(b)< if(b)< return "true"; >else < return "false"; >> 

Таким образом, если на входе мы получаем истину (true), функция вернет строку “true”, если — ложь (false), функция вернет строку “false”.

Однако, есть и другие приемы, позволяющие получить такой же результат.

Например, мы можем использовать конкатенацию с пустой строкой. Это позволит конвертировать булево значение в строчное:

function booleanToString(b)

Кроме того, мы можем вовсе отказаться от использования условного оператори или конкатенации и прибегнуть к помощи встроенного метода .toString() , которые так же вернет нам нужный результат:

function booleanToString(b)

Итак, данная задача показывает, как можно использовать различные подходы для достижения определенного результата. Так же, это неплохой пример проведения рефакторинга кода с переходом от первого достаточно громоздкого и очевидного решения к более короткой и интересной реализации.

Новые публикации

Photo by CHUTTERSNAP on Unsplash

JavaScript: сохраняем страницу в pdf

HTML: Полезные примеры

CSS: Ускоряем загрузку страницы

JavaScript: 5 странностей

JavaScript: конструктор сортировщиков

Категории

О нас

Frontend & Backend. Статьи, обзоры, заметки, код, уроки.

© 2021 dr.Brain .
мир глазами веб-разработчика

Источник

How to convert Boolean to String in JavaScript?

In this tutorial, we will learn to convert the Boolean to string in JavaScript. The problem is straightforward: sometimes programmers need to use the boolean true and false values as a string. So, there is a requirement to convert the Boolean to string.

Here, we have various methods to convert the Boolean to a string variable.

  • Using the toString() Method
  • Using + and $ (template literal) Operator
  • Using the ternary Operator

Using the toString() method

The toString() method is the JavaScript string library method, which is useful for converting the variables to the string data type. We can also use it for the Boolean value, and it returns a respected string value according to the Boolean value.

Syntax

Following is the syntax to convert Boolean to string using the toString() method −

let bool = false; let result = bool.toString();

Example

In the below example, we have used the toStirng() method to convert the Boolean to string. We have converted the false value to the string and checked the type of the returned value using the typeof operators. Users can observe the results in the output.

html> head> /head> body> h2> Converting the Boolean to string in JavaScript. /h2> h4> Converting the false to string using i> toString() /i> method: /h4> div id = "string1"> /div> h4> typeof the above string is /h4> div id = "stringType"> /div> /body> script> var string1 = document.getElementById("string1"); var stringType = document.getElementById("stringType"); let bool = false; let result = bool.toString(); string1.innerHTML = result; stringType.innerHTML = typeof result; /script> /html>

Using + and $ (template literal) Operators

In this approach, we will use the + operator to convert the Boolean to a String. When we try to concatenate the string value with the variable of another data type, it converts the variable to the string and returns the merged string. To achieve our goal, we will concatenate the empty string with the Boolean value.

Also, users can use the template literal ( $ <> ) to concatenate the empty string with the Boolean value.

Syntax

Following is the syntax to convert Boolean to string using + and $ operators −

let bool = true; let result = bool + ""; // using + operator let result = `$`; // using template literal

Example

In the below example, we have used the + operator and template literal to convert the Boolean to string. We have simply created the formatted string of a single Boolean variable to convert the boolean into a string.

html> head> /head> body> h2> Converting the Boolean to string in JavaScript. /h2> h4> Converting the Boolean true to string using i> + /i> operator. /h4> div id = "string1"> /div> h4> Converting the Boolean false to string using i> $ > /i> operator. /h4> div id = "string2"> /div> h4> type of both returned values respectively./h4> div id = "stringType"> /div> /body> script> var string1 = document.getElementById("string1"); var string2 = document.getElementById("string2"); var stringType = document.getElementById("stringType"); let bool = true; let result = bool + ""; string1.innerHTML = result; stringType.innerHTML = typeof result + "
"
; bool = false; result = `$bool>`; string2.innerHTML = result; stringType.innerHTML += typeof result; /script> /html>

In the above output, users can observe that the data type of both variables is the string which means we have converted Boolean to string successfully.

Using the ternary Operator

The ternary operator is the shorter version of the if-else statement. It contains three parts. The first part contains the condition. If the condition becomes true, it returns the value from the second part. Otherwise, it returns the value from the third section. We will use the Boolean variable as a condition statement and return either “true” or “false” according to the value of a Boolean variable.

Syntax

Users can follow the below syntax to use the ternary operator for Boolean values.

let bool = true; let result = bool ? "true" : "false";

Example

In the below example, we have used the ternary operator to convert Boolean to string. The ternary operator returns the string “true” if the value of the Boolean variable is true and returns “false” if the value of the Boolean variable is false.

html> head> /head> body> h2> Converting the Boolean to string in JavaScript. /h2> h4> Converting the Boolean true to string using i> ternary ( ? : ) /i> operator. /h4> div id = "string1"> /div> /body> script> var string1 = document.getElementById("string1"); let bool = true; let result = bool ? "true" : "false"; string1.innerHTML = result; /script> /html>

We have used the tostring() method, Arithmetic + operator, and ternary operator to convert the Boolean to string. The toString() method is much slower than the second and third approaches. To make your code faster, the user should use the second approach.

Источник

Читайте также:  Php csv разделитель строк
Оцените статью