Categories
Object-Oriented JavaScript

Object-Oriented JavaScript — Numbers

JavaScript is partly an object-oriented language.

To learn JavaScript, we got to learn the object-oriented parts of JavaScript.

In this article, we’ll look at the building blocks of objects, which are primitive values.

Primitive Data Types

JavaScript has a few primitive data types.

They’re numbers, strings, booleans, undefined , null , and bigints.

Numbers are floating-point numbers and integers.

Strings are any group of characters.

Booleans are either true or false .

undefined is a value that doesn’t exist.

null represents an empty value.

Bigints are integers that end with an n and can be outside of the safe range, which is between -2 ** 53 and 2 ** 53 .

Any value that isn’t these types are objects.

Finding Out the Value Type

We can find the value of a primitive value with the typeof operator.

typeof can return 'number' . 'string' , 'boolean' , 'undefined' , 'object' or 'function' .

Numbers are one of the types that can be detected with typeof .

Number

For instance, we can write:

let n = 1;
typeof n;

and we’ll get 'number' .

Octal and Hex Numbers

Octal and hexadecimal numbers also returns 'number' .

For instance, we can write:

let n = 0o377;
typeof n;

to write an octal number and check its type.

To check a hex number, we can write:

let n = 0x00;
typeof n;

That will also return 'number' .

Binary Numbers

We can also write binary literals with the 0b prefix,.

For instance, we can write:

let n = 0b111;

Exponents

Exponents can be written with e .

For instance, we can write:

1e1

and get 10.

If we pass it to typeof , we get 'number' :

typeof 1e1

Infinity

Infinity is another kind of number.

It’s a number too big for JavaScript to handle.

Infinity is a number, so if we write:

typeof Infinity

we get 'number' .

Dividing by 0 gives us infinity. For instance, if we write:

let a = 1 / 0

then a is Infinity .

The smallest number is -Infinity .

When we have:

Infinity - Infinity

or

- Infinity + Infinity

we get NaN since they are indeterminate in their value.

But everything else gives us Infinity or -Infinity .

For instance, we can write:

Infinity - 20

we get Infinity .

If we write:

-Infinity * 3

we get -Infinity .

There’s a global isFinite function to check is a number is finite or not.

ES6 also adds the Number.isFinite to do the same check.

The difference is that the global isFinite function casts the value before it does the check.

And Number.isFinite doesn’t do that.

NaN

NaN stands for not a number.

It’s a special value that’s also a number.

If we write:

typeof NaN

we get 'number' .

When we do some arithmetic with non-number values, then we get NaN .

For example, if we have:

let a = 10 * "a"

We get NaN .

We can check if a value is NaN with the Number.isNaN method.

There’s also the global isNaN method.

The difference is that the global one does casting and the non-global one doesn’t.

So:

Number.isNaN('test')

returns false but

Number.isNaN(NaN)

returns true .

Number.isInteger is a method that checks if a value is a finite integer.

For instance, if we have:

Number.isInteger(123)

then that returns true .

But if we have:

Number.isInteger('foo')

that returns false .

It doesn’t do casting before it does the comparison.

Conclusion

There are various kinds of primitive values in JavaScript.

One of them is a number.

There’re various representations of numbers.

Categories
Object-Oriented JavaScript

Object-Oriented JavaScript — Conditionals and Loops

JavaScript is partly an object-oriented language.

To learn JavaScript, we got to learn the object-oriented parts of JavaScript.

In this article, we’ll look at conditionals and loops.

Ternary Operator

The ternary operator is a shorter version of the if-else syntax.

For instance, instead of writing:

let a = 3;
let result = '';
if (a === 1) {
  result = "a is 3";
} else {
  result = "a is not 3";
}

We can write:

let a = 1;
let result = (a === 3) ? "a is 3" : "a is not 3";

The ternary expression can be added with the ? and : symbols.

a === 3 is the conditional expression.

And the strings are what we return.

Switch

If we have lots of if conditions and else...if parts, then we can use the switch statements to write them,

For instance, we can write:

let a = '1',
  result = '';
switch (a) {
  case 1:
    result = 'Number';
    break;
  case '1':
    result = 'String';
    break;
  default:
    result = ''
    break;
}

We have a switch statement with case clauses inside.

The case clause value is compared against a and the correct clause would be run based on the match.

We need the break keyword so that we can stop at the end of the clause.

The default clause is run when none of the other cases match.

Loops

Loops let us run code repeatedly.

JavaScript has the following loops:

  • while loops
  • do-while loops
  • for loops
  • for-in loops
  • for-of loops

While Loops

The while loop takes a condition and runs some code.

For instance, we can write:

let i = 0;
while (i < 10) {
  i++;
}

The code runs the while loop which increments i by 1 until it reaches 10.

The parentheses surrounds the condition to run the loop.

As long as the condition is true , it’ll be run.

Do-while Loops

The do...while loop is a slight variation of the while loop.

It’s different from the while loop in that the first iteration is always run.

We can use it by writing:

let i = 0;
do {
  i++;
} while (i < 10);

i is always incremented once.

Then the whether more iterations are run are determined by the condition inside the parentheses.

For Loops

The for loop is the most widely used kind of loop.

It has the initialization clause which initializes the variable which we want to iterate.

The increment clause updates the variable.

The ending condition is also added so it can end.

For instance, we can write:

for (let i = 0; i < 100; i++) {
  console.log(i)
}

We keep incrementing i until it reaches 100.

We can vary this by moving the body to the loop heading:

for (let i = 0; i < 100; i++, console.log(i)) {

}

But it doesn’t make much sense to do that.

Loops can be nested within each other.

For instance, we can write:

for (let i = 0; i < 100; i++) {
  for (let j = 0; j < 100; j++) {
    console.log(i, j)
  }
}

We have one loop nested in another loop.

Conclusion

The ternary operator lets us write if...else statements in a shorter way.

And we can create loops in various ways.

Categories
Object-Oriented JavaScript

Object-Oriented JavaScript — Comparisons and New Primitive Types

JavaScript is partly an object-oriented language.

To learn JavaScript, we got to learn the object-oriented parts of JavaScript.

In this article, we’ll look at boolean, comparisons, and new primitive types which are the building blocks of objects.

Lazy Evaluation

Booleans expressions are lazily evaluated.

This means that it evaluates the expression until the result is clear.

So if we have:

true || "foo";

then the JavaScript engine stops at true and returns that because it’s clearly true no matter what the 2nd operand is.

However, if we have:

true && "foo";

then both are evaluated and the 2nd operand is returned.

We can use this behavior to let us initialize variables to a default value.

For instance, we can write:

let num = num || 10;

If num is falsy, then num will be assigned 10.

Comparison

Comparison operators also return boolean values.

There are the == and === operators for equality comparisons.

And != and !== for inequality comparisons.

> returns true if the left operand is greater than the right operand.

And >= returns true if the left operand is greater than or equal to the right operand.

< returns true if the right operand is greater than the left operand.

And <= returns true if the right operand is greater than or equal to the left operand.

We should use === and !== for equality and inequality comparisons since they don’t cast the operands before comparing them.

Undefined and null

undefined means a value doesn’t exist.

If we have an uninitialized variable, then the it’s undefined .

So if we have:

let x

then x is undefined .

typeof x would returns 'undefined' .

null isn’t assigned by JavaScript behind the scenes, it’s assigned by our code.

So if we have:

let y = null

then y is null .

typeof y would be 'object' since it’s null .

They can be converted to a boolean or a string.

For instance, we can write:

!!undefined;

or

!!null;

they both return false since they’re both falsy.

We can write:

"value: " + null;
"value: " + undefined;

And we get:

"value: null"

and

"value: undefined"

Symbols

Symbols are a new primitive type.

These are used as unique identifiers.

We create a symbol by using the Symbol function.

For instance, we can write:

const atom = Symbol();

We don’t use the new keyword since Symbol isn’t a constructor.

We can pass in a string into it:

const bar = Symbol('bar')

No 2 symbols are the same.

So if we have:

console.log(Symbol('bar') === Symbol('bar'))

or:

console.log(Symbol() === Symbol())

they’re both false .

Bigint

Bigint is another primitive type.

They are integers with an n suffix.

We can write like:

10n

We can do arithmetic with 2 bigints.

So we can write:

10n * 2n

and get 20n .

They can be outside of the safe range of JavaScript integers, which is -2 ** 53 and 2 ** 53 , so we can use them to represent any integer.

Conclusion

Booleans are lazily evaluated.

undefined represents non-existing value.

null represents no value.

Symbols are used as unique identifi8ers.

Bigints are large integers that can be anything.

Categories
Object-Oriented JavaScript

Object-Oriented JavaScript — Arrays and Conditionals

JavaScript is partly an object-oriented language.

To learn JavaScript, we got to learn the object-oriented parts of JavaScript.

In this article, we’ll look at arrays and conditionals.

Arrays

An array is a sequence of values.

It’s an object type.

It can have anything in them, including primitive values and objects.

We can define an empty array with:

let a = [];

And we can put values in them by writing:

let a = [1, 2, 3];

Array index is the position of the item. Arrays start with 0 as its index.

So the first item has index 0.

We can access any element using square brackets:

a[0];

then we get 1.

Adding/Updating Array Elements

We can add a value to an array by assigning a value to it.

For instance, we can write:

a[2] = 'foo';

Then we get:

[1, 2, 'foo'];

We can write:

a[3] = 'bar';

Then we get:

[1, 2, 'foo', 'bar'];

We can have gaps in an array.

Gaps are filled with undefined .

Assignment can also be used to update an element.

Arrays of Arrays

We can have an array of arrays.

For instance, we can write:

let a = [[1, 2, 3], [4, 5, 6]];

Then we can access entry by writing:

a[0][0];

We return the first entry of th first array in a ,. so we get 1.

We can also use the square brackets to get a character from a string, so we can write:

let s = 'foo';

And we get:

s[0];

which is 'f' .

Conditions and Loops

Conditional statements include the if and switch statements.

They let us run code depending on the condition given.

Loops include the while , do...while , for , for...in , and for...of loops.

Code Blocks

A code block is a part of a piece of code that’s separated from the outside.

For instance, we can write:

{
  let a = 1;
  let b = 3;
}

to create a block.

let lets us create variables that are only available within the block.

Blocks can be nested, so we can write:

{
  let a = 1;
  let b = 3; {
    let c = a + b; {
      let d = a - b;
    }
  }
}

We have blocks that are nested in other blocks.

if condition

We can use the if block to run something given a condition.

To do that, we can write:

if (a > 3) {
  result = 'a is greater than 3';
}

then the body is only run when a is bigger than 3.

We can have any logical expression between the parentheses.

else Clause

The else clause can be added to an if condition if we need to run something if the if condition is false .

For example, we can write:

if (a > 3) {
  result = 'a is greater than 3';
} else {
  result = 'a is not greater than 3';
}

They can be nested like any other blocks.

The if condition is handy for checking if a variable exists.

For instance, we can write:

if (typeof foo !== "undefined") {
  result = "yes";
}

Then we check if foo is initialized by checking if it’s undefined .

Conclusion

Arrays are a sequence of values.

The if statement lets us run code conditionally.

Categories
Object-Oriented JavaScript

Object-Oriented JavaScript — Polymorphism and Primitive Values

JavaScript is partly an object-oriented language.

To learn JavaScript, we got to learn the object-oriented parts of JavaScript.

In this article, we’ll go through the object-oriented parts of JavaScript.

We also look at the basic building block of objects, which are primitive values.

Polymorphism

Polymorphism means that if we substitute one subclass with another, that the program should still work the same way if the code uses the parent’s properties or methods.

If they both inherit from the same parent class, then they should have the same methods, so they should work the same way.

If the Person class has the talk method and we created 2 subclasses that inherit from them.

Then we can use any of those subclass’ talk method.

Primitive Data Types

The basic building blocks of object-oriented JavaScript are primitive data types.

In JavaScript, primitive data types are strings, number, booleans, null , undefined and bigint.

They’re all recorded as values and have no methods of their own unless they’re wrapped in wrapper objects.

Variables

Variables are used to store data.

They’re placeholders for concrete values.

It’s more convenient to use variables than the values to wor with the actual data.

This is because they can be used multiple times.

Values can only be used once.

Using variables requires 2 steps.

We’ve to declare it, and then we’ve to assign it a value.

To declare a variable, we can write:

let a;

A variable can be a combination of letters, numbers, and underscore characters.

But we can’t start with a number.

Then to initialize it, we assign a value to it.

For instance, we can write:

let a = 1;

We can do both in one step.

Variables declared with const requires a value to be assigned when it’s declared.

So we write something like:

const a = 1;

We can declare multiple variables in one statement, like:

let a = 1,  
  b = 2,  
  c = 3;

We can also use $ in variables.

Variable names can start with $ and it can also be in other positions.

$ is often used as function or property names.

Variables are Case Sensitive

JavaScript variables are case sensitive.

So if they’re different cases, then they’re considered different.

Operators

Operators can take one or values or variables, do an operation, and return a value.

JavaScript has various operators like arithmetic operators, bitwise operators, etc.

+ adds 2 numbers or concatenate strings.

- does subtraction.

* does multiplication.

/ does division.

% returns the remainder of one number divided by another.

++ increments the number by 1.

-- decrements the number by 1.

For instance, we can add 2 numbers by writing:

const sum = 1 + 2;

There are also some compound operators.

They make our code more compact.

They do the arithmetic and the assignment at the same time.

+= adds a number to an existing number.

-= subtracts a number from an existing number.

*= multiplies a number with an existing number.

/= divides a number from an existing number.

%= returns the remainder if we divide the left number by the right number.

For instance, we add a number to a variable by writing:

let x = 1;  
x += 2;

We created a variable x and set it to 1.

Then we add 2 to x with += .

So at the end x is 3.

Conclusion

Polymorphism is where we can substitute a subclass with another and we can still use the parent’s methods.

Variables hold values and we can do various operations with them.