Что выведет следующий код typeof 1n
Перейти к содержимому

Что выведет следующий код typeof 1n

  • автор:

Восемь типов данных, typeof

Материал на этой странице устарел, поэтому скрыт из оглавления сайта.

Более новая информация по этой теме находится на странице https://learn.javascript.ru/types.

В JavaScript существует несколько основных типов данных.

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

Число «number»

Единый тип число используется как для целых, так и для дробных чисел.

Существуют специальные числовые значения Infinity (бесконечность) и NaN (ошибка вычислений).

Например, бесконечность Infinity получается при делении на ноль:

Ошибка вычислений NaN будет результатом некорректной математической операции, например:

Эти значения формально принадлежат типу «число», хотя, конечно, числами в их обычном понимании не являются.

Особенности работы с числами в JavaScript разобраны в главе Числа.

Число «bigint»

В JavaScript тип «number» не может содержать числа больше, чем 2 53 (или меньше, чем -2 53 для отрицательных). Это техническое ограничение вызвано их внутренним представлением. 2 53 – это достаточно большое число, состоящее из 16 цифр, поэтому чаще всего проблем не возникает. Но иногда нам нужны действительно гигантские числа, например в криптографии или при использовании метки времени («timestamp») с микросекундами.

Тип BigInt был добавлен в JavaScript, чтобы дать возможность работать с целыми числами произвольной длины.

Чтобы создать значение типа BigInt , необходимо добавить n в конец числового литерала:

Более подробно тип данных BigInt мы рассмотрим в отдельной главе BigInt.

Строка «string»

В JavaScript одинарные и двойные кавычки равноправны. Можно использовать или те или другие.

В некоторых языках программирования есть специальный тип данных для одного символа. Например, в языке С это char . В JavaScript есть только тип «строка» string . Что, надо сказать, вполне удобно.

Более подробно со строками мы познакомимся в главе Строки.

Булевый (логический) тип «boolean»

У него всего два значения: true (истина) и false (ложь).

Как правило, такой тип используется для хранения значения типа да/нет, например:

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

Специальное значение «null»

Значение null не относится ни к одному из типов выше, а образует свой отдельный тип, состоящий из единственного значения null :

В JavaScript null не является «ссылкой на несуществующий объект» или «нулевым указателем», как в некоторых других языках. Это просто специальное значение, которое имеет смысл «ничего» или «значение неизвестно».

В частности, код выше говорит о том, что возраст age неизвестен.

Специальное значение «undefined»

Значение undefined , как и null , образует свой собственный тип, состоящий из одного этого значения. Оно имеет смысл «значение не присвоено».

Если переменная объявлена, но в неё ничего не записано, то её значение как раз и есть undefined :

The typeof javaScript operator and other data type related things

The javaScript typeof operator will return a string that is the type of the operand that is given to it from the right of the typeof keyword when used in an expression. It is the first go to operator then to go about preforming type checking of values in javaScript.

However when it comes to data type checking in javaScript there are also some additional things to look out for when it comes to really knowing what one is dealing with when it comes to values. For example when it comes to objects the typeof operator will always return object, but will not give insight into the type of object. So the typeof operator is not a replacement for other keywords such as the instance of operator that will help to know what kind of object a value is when it is in fact an object.

The typeof operator might not always give the desired results in many cases. Maybe the most note worthy issue to be aware of is that it will return the value ‘object’ when used with a null value. This is actually the value that it should return, but some developers might considered this a bit confusion, and in any case it is something that one has to adjust for no matter what anyway.

1 — javaScript typeof lowdown

The typeof operator has right to left associativity so to use it I just need to type the typeof operator followed by what it is that I want to find the type of. the result of the expression of the typeof operator with the value I want the type of to the right of typeof will then evaluate to a string, and the string more often then not will be the type of the value. For the most part the typeof operator is fairly straight forward to use but it has a few quirks, so lets get into it by starting off with a basic example of javaScript typeof.

Here the javaScript typeof operator works as expected, I give it a number and it returns the string ‘number’. So far the type of operator works the way it should without issue. However there are certain values like NaN that stands for Not a Number yet its type if number. Things also get a little weird when I pass it the null value for example so lets continue looking at some more examples here.

2 — No need to call typeof as it is an operator and not a function

In some examples I see new javaScript developers placing parentheses around what it is that they want to find the type of. This is not necessary as the typeof operator is an operator and not a function. However in some cases you might still want to use parentheses as a way to group an expression as you might get undesired results.

So if you do need to group then use parentheses otherwise they are not needed.

3 — The deal with javaScript typeof and null

So there is something strange with the typeof operator and the value of null. When the value of null is what is used with the typeof operator the result is object.

From what I have gathered so far with the typeof null equals object deal in javaScript it it would seem that this is a mistake that dates all the way to the beginning of javaScript. However maybe object is an appropriate value to return considering that the value is often used as a placeholder for what should be an object. There is some talk as to the subject of if it will be fixed or not but so far it seems like that is not happening. Also it would not be a good idea to change it at this point as that would result in a whole world of code breaking, so it would seem that this is just once little thing that javaScript developers just need to adjust for when using typeof.

4 — The Instanceof operator is what can be used for finding out what kind of object I am dealing with

In most cases the typeof operator works just fine if I want to find out if something is a number, string, or an object. However if I want to find out what kind of object I am dealing with then in most cases typeof does not help much unless it the object is a function. When it comes to javaScript there are plain old objects that are cerated with the Object constructor, or the object literal syntax, but there is also a whole worlds of different kinds of objects created with a constructor function.

There are a number of built in constructor functions like Date, and Function, but it is also possible to create ones own Constructor functions also. So it is a good idea to know how to go about finding out what kind of object one is dealing with when type checking, there are a few ways to do this, but maybe the instanceof operator is the first and foremost option that will come up.

The instanceof operator accepts two operands one to the left that is what should be an object, and the other is a constructor function. If the variable or value that is being evaluated is an instance of the constructor then the expression will evaluate to true, else false.

5 — Constructor name

When dealing with an object another way to get the actual constructor name of the object rather than just always getting object is to look at the constructor property. All objects should have a constructor object that will contain the constructor function that was used to create the object. For example if it is a Date object then the constructor should be the Date constructor. There is then a name property of this object that is then the name of that constructor function that was used.

6 — Conclusion

So it would seem that the javaScript typeof operator can be used as a way to find out the type of something in javaScript, but it might not aways work as expected. In addition when it comes to objects it is vague and can even return a value of object for null, so it still needs to be used with other operators to find out more in these situations.

JavaScript might be a typeless language however that just means that a variable can be any type at any given moment, it does not meed that javaScript does not have types. There are a number of data types to be aware of, also the javaScript of today is not the javaScript of yesterday as new specs of javaScript keep coming out additional types are being added. One note worthy example of this might be the Big integer data type that has been introduced in recent years.

Что выведет следующий код typeof 1n

In JavaScript, the typeof operator returns the data type of its operand in the form of a string. The operand can be any object, function, or variable.

Syntax:

Note: Operand is an expression representing the object or primitive whose type is to be returned. The possible types that exists in javascript are:

  • undefined
  • Object
  • boolean
  • number
  • string
  • symbol
  • function

Below is an example of the typeof operator.

Example: This example checks the typeof of a string, number, and undefined object and returns the value in the console.

javascript

Output:

Let’s cover all the types one by one dedicating a single code section for each code.

The Javascript “typeof” Operator

The typeof operator returns a string indicating the type of the unevaluated operand.

The syntax of typeof operator is:

Here, the operand is a variable name or a value.

You must be thinking why we need that………….

Javascript is a dynamically typed language. Ok, what does this mean.

This means that the developer doesn’t assign the type to any variable while creating them. Because a variable is not restricted in this way, its type can change during the runtime of a program.

As you can see, a variable in JavaScript can change types throughout the execution of a program. This can be hard to keep track of as a programmer, and this is where the typeof operator is useful.

Another way the typeof operator can be useful is by ensuring that a variable is defined before you try to access it in your code. This can help prevent errors in a program that may occur if you try to access a variable that is not defined.

Numbers

BigInt

Boolean

Strings

Symbols

Undefined

Objects

Functions

typeof null

Using new operator

All constructor functions, with the exception of the Function constructor, will always be typeof ‘object’

A Note on Errors

Before ES6, typeof was always guaranteed to return a string for any operand it was supplied with. Even with undeclared identifiers, typeof will return ‘undefined’. Using typeof could never generate an error.

But with the addition of block-scoped let and const using typeof on such variables (or using typeof on a class) in a block before they are declared will throw a ReferenceError. Block scoped variables are in a “temporal dead zone” from the start of the block until the initialization is processed, during which, it will throw an error if accessed.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *