Missing Guide to JavaScript Numbers

Pro Members Only

This lesson is available if you have an active subscription.

Alternatively, some member might be able to gift it to you.

If you already have a subscription, you can sign in.

Professional Modern JavaScript Lessons

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36

Missing Guide to JavaScript Numbers

Subscription Required

You must have an active subscription to access this content.
If you already have a subscription, you can sign in.

Basics

const leet = 1337;
const yummy = 3.14;
const loss = -1000;

console.log(1337 === 1337.00); // true

{
let million = 1_000_000;
console.log(million === 1000000); // true
}

{
let million = 1e6;
console.log(million === 1000000); // true
}

console.log(1e-6 === 0.000001); // true

console.log(typeof leet); // 'number'

console.log(.1 + .2); // 0.30000000000000004 - https://0.30000000000000004.com/

Mathematical Operators

// addition
console.log(1 + 1); // 2

// subtraction
console.log(5 - 1); // 4

// multiplication
console.log(5 * 2); // 10

// division
console.log(10 / 4); // 2.5

// remainder
console.log(3 % 2); // 1
console.log(6 % 3); // 0

// exponent
console.log(2 ** 3); // 8

Shorthand Assignment

{
let addition = 123;
addition = addition + 1;
console.log(addition); // 124
}

let addition = 123;
addition += 1;
console.log(addition); // 124

let subtraction = 123;
subtraction -= 55;
console.log(subtraction); // 68

let multiplication = 123;
multiplication *= 2;
console.log(multiplication); // 246

let division = 123;
division /= 2;
console.log(division); // 61.5

let remainder = 5;
remainder %= 2;
console.log(remainder); // 1

let exponent = 16;
exponent **= .5;
console.log(exponent); // 4

Unary Operators

Addition and Subtraction

{
let example = 0;
example++;
console.log(example); // 1
++example;
console.log(example); // 2
}

{
let example = 0;
example--;
console.log(example); // -1
--example;
console.log(example); // -2
}

Pre vs Post

{
let example = 0;
let result = example++;
console.log(result); // 0
console.log(example); // 1
}
{
let example = 0;
let result = ++example;
console.log(result); // 1
console.log(example); // 1
}

{
let example = 0;
let result = example--;
console.log(result); // 0
console.log(example); // -1
}
{
let example = 0;
let result = --example;
console.log(result); // -1
console.log(example); // -1
}

Comparison Operators

// less than
console.log(1 < 3); // true

// greater than
console.log(1 > 3); // false

// less than or equal
console.log(3 <= 3); // true

// greater than or equal
console.log(4 >= 5); // false

// greater than or equal
console.log(4 >= 5); // false

// strict equality
console.log(1 === 1); // true

// strict inequality
console.log(5 !== 3); // true

Integral Limits

console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
console.log(Number.MIN_SAFE_INTEGER); // -9007199254740991

console.log(Number.MAX_SAFE_INTEGER + 1); // 9007199254740992 - Correct (but ambiguous)
console.log(Number.MAX_SAFE_INTEGER + 2); // 9007199254740992 - Rounded!

// Safe value
console.log(Number.isSafeInteger(Number.MAX_SAFE_INTEGER)); // true

// Unsafe values (it might have been rounded to it due to overflow)
console.log(Number.isSafeInteger(Number.MAX_SAFE_INTEGER + 1)); // false
console.log(Number.isSafeInteger(9007199254740999)); // false

Infinity

console.log(10 ** 1000); // Infinity
console.log(-1 * 10 ** 1000); // -Infinity

console.log(1 / 0); // Infinity
console.log(-1 / 0); // -Infinity

console.log(Infinity === Infinity); // true
console.log(-Infinity === -Infinity); // true

console.log(Infinity > 1); // true
console.log(-Infinity < -1); // true

console.log(Number.POSITIVE_INFINITY === Infinity); // true
console.log(Number.NEGATIVE_INFINITY === -Infinity); // true

String Interop

const meaningOfLife = 42;
console.log(meaningOfLife.toString()); // '42'

const message = 'The meaning of life is: ' + 42;
console.log(message); // 'The meaning of life is: 42'

const change = 123.353;
console.log(change.toString()); // '123.353'
console.log(change.toFixed(2)); // '123.35' - rounded down
console.log(change.toFixed(1)); // '123.4' - rounded up

console.log(meaningOfLife.toFixed(2)); // '42.00'

String Parsing

const meaningOfLife = '42';

console.log(parseInt(meaningOfLife)); // 42

const change = '23.55';

console.log(parseInt(change)); // 23
console.log(parseFloat(change)); // 23.55
console.log(+change); // 23.55

NaN

const powerPuff = 'Sugar, spice and everything nice';

const valueOfPower = parseInt(powerPuff);
console.log(valueOfPower); // NaN

console.log(0 / 0); // NaN

const first = parseFloat('Alpha'); // NaN
const second = parseFloat('Beta'); // NaN

console.log(first !== second); // true

console.log(NaN !== NaN); // true
console.log(NaN === NaN); // false

console.log(first === NaN); // false

console.log(isNaN(NaN)); // true
console.log(isNaN(first)); // true

Number Bases

const perfect = 2 ** 5;

console.log(perfect == 32); // true
console.log(perfect === 0b100000); // true
console.log(perfect === 0o40); // true
console.log(perfect === 0x20); // true

// case insensitive
console.log(0b0 === 0B0); // true
console.log(0o0 === 0O0); // true
console.log(0x0 === 0X0); // true

console.log(perfect.toString()); // '32'
console.log(perfect.toString(2)); // '100000'
console.log(perfect.toString(8)); // '40'
console.log(perfect.toString(16)); // '20'

console.log(parseInt('32')); // 32
console.log(parseInt('100000', 2)); // 32
console.log(parseInt('40', 8)); // 32
console.log(parseInt('20', 16)); // 32

Math Built-in Module

console.log(Math.floor(1.99)); // 1
console.log(Math.ceil(1.01)); // 2

console.log(Math.round(1.99)); // 2
console.log(Math.round(1.01)); // 1
console.log(Math.round(1.5)); // 2

Math.random(); // a random floating point in the range (>=0 && <1)

const coinToss = Math.floor(Math.random() * 2); // 0 or 1
const diceRoll = Math.floor(Math.random() * 6); // 0, 1, 2, 3, 4, or 5

console.log(Math.max(1, 2, 3)); // 3
console.log(Math.min(1, 2, 3)); // 1

function calculateCircumference(radius) {
return 2 * Math.PI * radius;
}
console.log(calculateCircumference(1)); // 6.283185307179586
javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

00:00

One of the harder, often misunderstood primitives within JavaScript is a number data type. So in this tutorial, not only will we look at the basics of number, but also its limitations, some special numbers, fancy modern syntax and lots, lots more. So by the end you will have complete mastery of this critical data type. So let's go. The number TE type within JavaScript is a 64 bit signed floating value. This means that it can be used to represent intes as well as decimals, as well as inactive numbers. Now make no mistake, they are the same TE type. So 1, 3, 3 7 will be exactly equal to 1 3 3 7 0.0000 if

00:36

you wanted to do that comparison, modern JavaScript numbers can also include an underscore, and this is purely for readability purposes. This does not impact the value that is contained by that number. Additionally, you can declare numbers with the scientific e notation. After the E, you are basically specifying how many times you want the decimal to move towards the right here. Of course, we are saying that starting with the value of A one, we want the decimal to move six times towards the right, giving us one, followed by six zeros, which is a million. We can actually provide a negative value after E as well,

01:10

and that will move the decimal point towards the left. So here we are saying that starting with one, move it six times towards the left, giving us 0.5 zeros and one similar to other primitive types. The type of operator also works with numbers and when you apply to a number value, it returns the string number. Now the number that type within JavaScript is a true boundary floating point value, which means that they suffer from the boundary floating point error that you might be familiar with in other programming languages. If by any chance this is the first time that you're experiencing this, you can actually visit this website to learn more about this fact, but in short,

01:46

it exists in most programming languages including Java c and c plus plus. As you would expect, JavaScript numbers support all the common mathematical operators. You can use the plus operator to add to numbers. For example, one plus one is two. You can use the minus operator to subtract one value from another. For example, five minus one is four. You can use star for multiplication. For example, five star two is 10. You can use the forward slash for division. For example, 10 divided by four gives us 2.5. You can use the person sign for remainder, also called modular.

02:20

So three divided by two gives us a remainder of one and six is a perfect factor of three, so that gives us a remainder of zero. JavaScript also has the exponent operator, which you might be familiar with as power and it is represented by double stars. For example, two to the power three gives us eight. Now with these mathematical operators there is also a concept of shorthand assignment. As an example, consider a simple variable, which we have initialized 2, 1, 2, 3. We can do a mathematical operation, for example, plus one and then assign the value back to the original variable. Now of course this does work because 1, 2, 3 plus one is 1, 2, 4. However,

02:58

there Is a shorter hand syntax for this particular statement. We can do the same thing with plus equal one, and what this does is actually takes the variable adds one to it and assigns it back to the variable. As far as the runtime behavior is concerned, these two statements are perfectly equivalent. And of course this shorthand version exists for all the other mathematical operators that we've seen as well. For example, 1, 2, 3 minus 55 gives us 68 1 2 3. Star two gives us 2, 4, 6, 1, 2, 3 divided by two gives us 61.55 divided by two gives us a remainder of one 16

03:35

to the power of 0.5. That is the square root of 16 gives us the value. Four, just like other scenes inspired programming languages, JavaScript also has the double plus and the double minus operators along with a prefix and postfix support. So you can take a variable and add plus plus after the variable or plus plus before the variable. And both of these will increment the variable. For example, we start with zero, we go to one and then we go to two. And the same is true for minus minus as well. We can do example minus minus to get minus one or minus minus example to get minus two.

04:08

The difference between the postfix version and the prefix version becomes obvious when we try to do the same within an assignment expression. Here we have the same code written twice, but the first time we are using the postfix plus plus. And in the second example we are using the prefix plus plus to understand the difference, focus on the terms post and pre. With post plus plus the runtime returns the current value immediately and post that we update the value of the variable. So the value that goes into the result is the original value, which is zero, and then example gets updated to the value of one. Similarly,

04:44

with pre plus plus the value gets pre-up updated. So example is immediately going to become one and that is what is returned into the result. And the same thing applies to the minus, minus postfix and prefix operators. With postfix, the result is going to be the value before the update and with prefix the result is going to be the value with the minus minus pre-applied. Now share income is a surprise that these operators only work on variables that can be muted. For example, alpha is a lead variable and therefore alpha plus plus is perfectly fine. However, if you just have three standing by itself,

05:16

it's not actually a variable. So three plus plus is going to result in an error. And similarly, if we have cons beta, then beta is a cons and therefore it cannot be reassigned and beta plus plus will not be allowed. And of course if you have touched it configured as we did in a previous lesson, then it'll catch these silly mistakes for you at compiled time. To make core execution decisions based on a value, we need to be able to compare numbers and of course JavaScript comparison operators have got your back. You can compare to numbers with a less than operator and of course one is less than three. So that's true.

05:49

You can use the greater than operator one is a not greater than three and therefore that is false. There is also less than or equal to, for example, three is less than or equal to three because it is equal to three and that will be true. There is greater than or equal and four is not greater than or equal to five, which is actually less than five. So therefore it'll be false. And there is also strict equality. For example, one is equal to one and of course that's going to be true and strict inequality, which is not equal equal. So five is not equal to three and therefore that is true because DAOs cap

06:24

numbers have a fixed bit size of 64. There are limitations on the size of inte that it can safely represent. There is a global number module that has dismember called max safe integer, which represents the max safe positive value. And similarly there is a min safe integer which represents the minimum safe value. Now safe in this context refers to the fact that the value cannot be result of a rounding error. The unsafe values are plus one away from max safe and minus one away from mins safe.

06:54

And what that basically means is that there is no guarantee that the result that we get at this point is not the result of a rounding error. So max safe plus one while correct is ambiguous because plus two will give us the same value. So max safe and mins safe, you are perfectly fine Outside of that range, numbers can be represented but they might be a chance that they might have been rounded. Now to check if there is a chance that a rounding might have occurred on the value, you can use this function called number is safe integer and of course max safe integer is safe,

07:27

but anything else outside of that range is not going to be safe. For example, plus one is not going to be safe. And similarly, any other number that we write that is going to be outside that range is not going to be safe. If you go out of pounds of what values can be represented in the 64 bits, you will end with infinity, which is still a well-defined numeric value within JavaScript. As an example, if you decide that you have had enough and raise 10 to the power 1000, you will get infinity. And if you multiply it with minus one, you will get minus infinity. Dividing a positive number by zero will give you infinity and dividing a

08:02

negative number by zero will give you negative infinity. Now as I mentioned, these are well-defined literals, so you can actually type it in yourself as well and it is equal to itself. So infinity is equal to infinity minus infinity is equal to minus infinity and they've work with comparison operators as well. So infinity is greater than any other positive number that you can think of and a minus infinity is smaller than any other negative number that you can think of. Now these values also exist as members of the number module. So number has positive infinity, which is of course equal to infinity and negative infinity,

08:35

which is of course equal to minus infinity. Since the origin of JavaScript lies in user interface programming working with strings is often required and so the interop between numbers and strings is quite well built within JavaScript. Let's first look at converting a number into a string. Now numbers have a method called two string, which Can be used to convert the number into a string, and this actually gets in worked automatically when we add a number to a string and we've seen examples of that in our string lesson. When we are working with floating point values, we might want to format it a bit further because the default to string might

09:09

give us a really long string that we might not like For a bit of formatting control, there is a function built into strings called two fixed, which takes a number of decimal points that we want to display. So if we invoke two fixed on change and pass in a value of two, we get back a string that contains two decimal digits. Additionally, two fixed will also round a value. So as an example, if we invoke two fixed one, it rounds it up to four. Now Tofi will always try to add the required number of digits, so if we don't have any, for example, 42 clearly doesn't. It'll add zeros instead.

09:43

Now let's talk about the opposite where we take a string and we try to pass it into a number. Chow script has a global function available for us called pass int, which takes a string and tries to pass it into its integer equivalent. If the string in question has a decimal portion, that portion is completely ignored by par int. So 23.55, we only get back the number 23. Now if we do want to pass the value as a float, then JavaScript has another built-in function called pass float, which takes that string and passes it into a float. So 23.55 string gives us the numeric 23.55. Now,

10:18

just like we use the double bank to convert other values into Drew Bullions, JavaScript has a ary plus operator that can be used to convert a string into their number equivalent. When I have a string that I trust is going to pass correctly, then this urinary plus is normally what I would use. But what about the case when we have a string that is not going to pass correctly, for example, sugar spice and everything nice, although excellent is not a valid number for these cases, JavaScript has a special numeric value called nan, which stands for not a number beyond passing things that clearly cannot be a

10:55

number. The Nan literal also shows up in other scenarios. For example, when we try to divide zero by zero, there is a very peculiar but completely reasonable behavior observative within NANS that is best explained with a simple example. Here we have two variables, first and second, which are the result of passing two different strings. Now, both of these are going to be Nan, but clearly I'll find we are not equal to each other. Therefore it makes reasonable sense that first should not be equal to second. And indeed this is the case within JavaScript. However, this does mean that a nan is not equal to a nan.

11:33

This poses a slight problem because if a nan is not equal to nan, then a nan equal to NAN will be false. This will actually prevent us from checking if a particular value has resulted in an N, but fortunately, JavaScript has a very nice global function called is N, that will tell you if a particular numeric value is an N Or not. And as a side note, these silly mistakes of comparing directly with an NAN instead of using the Isan function are caught as a compile time error per type script in addition to literals in the decimal number system.

12:05

The number TE type also allows us to express our ideas in other digital basis, but make no mistake, they are still backed by the same boundary. 64 bit value. Consider the simple inte J 32, which is of course two to the power five. Representing this value in binary should be one followed by five zeros, and we can actually write that literal within towers script with zero B followed by the boundary value. Note that this is still the same number underneath, which is 32, which is of course Y perfect is equivalent to this boundary literal. In addition to boundary,

12:39

we can do octal with zero O and this is four zero and octal and hexa decimal with zero x and this is two zero in hexa decimal. Now all of these temptations are case insensitive as well, so it doesn't matter if b O or X are lowercase or uppercase. In addition to expressing ourselves in these numeric lits, we can actually take a numeric value and express it out as a string in any of these number systems. Now, by default, two string will render it out in decimal, but two string actually optionally also takes in a base for the number system. For example,

13:12

binary is base two and we get that one followed by five zeros and similarly octal is eight. We get 40 and hex is 16 and we get 20. And now that we know how to express these numbers as strings in different bases, we can actually pass them from the different bases as well. Now by default pass int, we'll pass it as a decimal. However, we can pass in a second optional argument to pass int for the base, for example, two for binary, eight for octal, and 16 for hex a decimal. All of these strings in the different bases, we'll pass to the numeric value of 32.

13:46

JavaScript comes with a built-in global math module that provides a lot of utility functions and some constraints that make it easier to work with numbers. For example, there is a math dot floor which will get rid of the floating portion. There is math dot seal, which if there is a floating portion, it'll bump up the integer value. So here 1.01 becomes two, and then there is math start round, which will round it to the nearest integer most smartly. For example, 1.99 becomes two, 1.01 becomes one, and 1.5 gets rounded up to two. And there is also math, maths, random,

14:21

which is perhaps my favorite function, and it returns a floating point starting from zero, but ending right before one. And by combining this with multiplication and math flow, we can actually scale it to whatever value that we want. For example, if you multiply it by two, it is going to be in the range zero to 1.9 9, 9, 9 9. And therefore if you flow it, it is either going to be zero or it is going to be one. And similarly, if you want six distinct intes, multiply it by six and use math flow To get zero to five. Math also has functions Maths max and math do min max returns the

14:57

maximum value within a set of numbers and min returns the smallest value within a set of numbers. And these functions come in quite handy. And speaking of handy math also has some Constance, for example, math. Do pi, which comes in handy when you are working with circles. For example. Here's the circle front of a unit circle. As you can see, there is a lot of power built into JavaScript numbers and for most user interface programming purposes, you will be well looked after. As always, thank you for joining me and I will see you in the next one.

Professional Modern JavaScript

Professional Modern JavaScript

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36