Categories
Object-Oriented JavaScript

Object-Oriented JavaScript — Arrays

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.

Array

Array is a built-in function that lets us create an array.

For instance, we can use it by writing:

const a = new Array();

This is the same as:

const a = [];

Either way, we can populate it by writing:

a[0] = 1;
a[1] = 2;

We can use the Array constructor to populate an array.

For instance, we can write:

const a = new Array(1, 2, 3, 4);

Then a is:

[1, 2, 3, 4]

We can create an array with some empty slots by passing in one integer.

For instance, we can write:

const a = new Array(5);

Then we get:

[empty × 5]

Arrays are just objects.

We can convert it to a string with the toString method.

For instance, we can write:

const a = new Array(1, 2, 3, 4);
console.log(a.toString());

And we get:

'1,2,3,4'

logged.

And we can get the constructor with:

console.log(a.constructor);

And we get:

ƒ Array() { [native code] }

logged.

We can use the length property to get the number of items in the array.

For instance, we can write:

const a = new Array(1, 2, 3, 4);
console.log(a.length);

Then we get 4.

We can set the length to a different number to change the array size.

If we set the length to something bigger than what it is now, then we get new entries in the array.

For instance, if we have:

const a = new Array(1, 2, 3, 4);
a.length = 5;
console.log(a);

And we get:

[1, 2, 3, 4, empty]

logged.

If we set the length to a shorter length than what it is now, then the array is truncated.

For instance, if we have:

const a = new Array(1, 2, 3, 4);
a.length = 2;
console.log(a);

And we get:

[1, 2]

Array Methods

We can set use various array methods to manipulate arrays.

We can use the push method to add an entry to the end of the array.

For instance, if we have:

const a = [1, 2, 3, 4];

Then we can call push to add a new entry:

a.push(5);

And we get:

[1, 2, 3, 4, 5]

The pop method removes the last entry of the array.

For instance, we can write:

const a = [1, 2, 3, 4];
a.pop();
console.log(a);

Then we get:

[1, 2, 3]

We can use the sort method to sort an array.

For instance, we can write:

const a = [6, 3, 1, 3, 5];
const b = a.sort();
console.log(a);

Then we get:

[1, 3, 3, 5, 6]

it returns a new array with the entries sorted.

The slice method returns a part of an array without modifying the source array.

For instance, if we have:

const a = [1, 2, 3, 4, 5];
const b = a.slice(1, 3);
console.log(b);

Then we get:

[2, 3]

logged.

The splice method lets us modify the source array.

We can use it to remove a slice, return it, and optionally fills the gap with new elements.

For instance, we can write:

const a = [1, 2, 3, 4, 5];
b = a.splice(1, 2, 100, 101, 102);
console.log(a);
console.log(b);

Then a is:

[1, 100, 101, 102, 4, 5]

and b is:

[2, 3]

We replaced values from index 1 with 2 entries.

Then we replaced that with 100, 101, and 102.

The removed entries are returned.

Conclusion

Arrays let us store data in sequence. They have various methods we can use to manipulate them.

Categories
Object-Oriented JavaScript

Object-Oriented JavaScript — Tagged Literals and Booleans

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 strings and booleans, which are the building blocks of objects.

Tagged Template Literals

Tagged template literals is another type of string literals.

They let modify the output of template literals with a function.

The function is called by prefix the template literal with the function.

For instance, we can write:

function transform(strings, ...substitutes) {
  console.log(strings);
  console.log(substitutes);
}

const firstname = "James";
const lastname = "Bond"
transform `Name is ${firstname} ${lastname}`;

transform is the template tag, which is a function that takes a specific set of parameters.

strings is an array of the parts of a string that aren’t in the curly braces.

substitutes have the values that are in the curly braces.

So strings is:

["Name is ", " ", ""]

and substitutes is”

["James", "Bond"]

Booleans

Booleans can only take on one of 2 values.

It can either be true or false .

For instance, if we have:

let b = true;

Then:

typeof b;

returns 'boolean' .

If we put true or false in quotes, then they’re strings.

So if we have:

var b = "true";
typeof b;

Then typeof b is 'string' .

Logical Operators

3 operators work with boolean values.

The ! is the logical NOT operator.

&& is the logical AND operator.

And || is the logical OR operator.

The ! negates the boolean value. So if we have:

let b = !true;

Then b is false .

If we use logical NOT twice, then we get the original value. If we have:

let b = !!true;

then b is true .

If a logical operator is used on a non-boolean value, then the value is converted to a boolean.

If we have:

let b = "foo";

Then !b; is false .

And if we have double negation:

let b = "one";
!!b;

then we get true .

Most values are converted to true with the double negation operator except the following:

  • The empty string “”
  • null
  • undefined
  • 0
  • NaN
  • false

The values above are all falsy.

The && operator returnstrue when both operands are true . Otherwise, it returns false .

The || operator returns true when either of the operands are true . Otherwise, it returns false .

We can use more than one operator in sequence.

For instance, we can write:

true && true && false && true;

and we get false .

And:

false || true || false;

and we get true .

If we mix || and && in one expression, then we should add parentheses.

For instance, we can write:

false && (false || true) && true;

we get false .

Operator Precedence

Operators have precedence.

The arithmetic follows the same rules as in math.

So if we have:

1 + 2 * 3;

we get 7 because multiplication comes first.

For logical operators, ! has the highest precedence and it’s run first.

Then comes && and || .

So:

false && false || true && true;

is the same as:

(false && false) || (true && true);

Conclusion

We should be aware of operator precedence with operators.

Also, there are several operators we should be aware of.

Categories
Object-Oriented JavaScript

Object-Oriented JavaScript — Strings

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 strings, which is one of the building blocks of objects.

Strings

A string is a sequence of characters to represent text.

Any values placed between single quotes, double quotes, or backticks are string.

If we have:

let s = "foo";
typeof s;

Then typeof s returns 'string' .

If we put nothing between the quotes, it’s still a string.

The + operator is used to concatenate 2 strings.

If we have:

let s1 = "web";
let s2 = "site";
let s = s1 + s2;

Then we s is 'website' .

And typeof s would be 'string' .

This is a source of errors in the system.

To avoid errors, we should make sure that operators are strings.

This way, we won’t be adding anything by accident.

String Conversions

A string is converted to a number behind the scene if a number string is encountered.

For instance, if we have:

let s = '1';
s = 2* s;

Then typeof s returns 'number' .

If we have:

let s = '1';
s++;

Then s++ converts s to 'number' .

We can convert a number string to a number by multiplying y 1 or use parseInt .

For instance, we can write:

let s = "100";
s = s * 1;

Now s is a string.

If the conversion fails, we get NaN .

There’re many strings with special meanings.

“ is the escape character.

We can use it to escape “, ' and " so that they can be in th string.

For instance, we can write:

const s = "12";

and s is 1 2 .

n is the line end character.

If we have:

let s = ‘n1n2n3n’;

We get:

"
1
2
3
"

r is the carriage return character.

If we have:

let s = '1r2'

We get:

“1
2”

t is the tab character. If we have:

let s = "1t2";

We get:

"1 2"

u is the character code that lets us use Unicode.

For instance, we can write:

let s = 'eu0301'

and s is

'é'

String Template Literals

ES6 introduced the template literal.

They let us embed expressions within regular strings.

ES6 has template literals and tagged literals.

Template literals are single or multiline strings with embedded expressions.

For instance, we can write:

const level = "debug";
const message = "meltdown";
console.log(`level: ${level} - message: ${message}`)

We have the level and message variables embedded into the template literals.

So we get:

'level: debug - message: meltdown'

logged.

Template literals are surrounded by backtick characters instead of quotes.

They’re concatenated into a single string.

We can have any expression int eh ${} .

For instance, we can write:

const a = 10;
const b = 10;

function sum(x, y) {
  return x + y
}

function multiply(x, y) {
  return x * y
}
console.log(`sum is ${sum(a, b)} and product is ${multiply(a, b)}.`);

We embed the result of the function calls into the template literal.

And we get:

'sum is 20 and product is 100.'

returned.

Conclusion

Strings are a sequence of characters.

We can create strings and template literals, which can have expressions embedded in them.

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.