Categories
Object-Oriented JavaScript

Object-Oriented JavaScript — Boolean, Number, and String

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 primitive wrappers.

Boolean

The Boolean can be used as a factory function or a constructor.

For instance, we can write:

const b = new Boolean();

and we get a boolean wrapper object returned.

We can convert it back to a primitive value with valueOf :

b.valueOf();

A better use of the Boolean function is to use it as a factory function.

For example, we can write:

Boolean("foo");

then we get true .

It’ll return true for anything truthy and false otherwise.

Boolean without new returns a primitive value.

Number

Number can also be used as a constructor or a factory function.

For instance, if we have:

const n = Number('12');

then we return the number 12.

And if we have:

const n = new Number('12');

then we return an object with value 12.

So we should use it without new to eliminate confusion.

Number also has some static properties.

Number.MAX_VALUE is 1.7976931348623157e+308 .

There’s also the Number.POSITIVE_INFINITY which is Infinity .

And Number.NEGATIVE_INFINITY which is -Infinity .

The toFixed method formats a number to a decimal number with the given number of fractional digits.

For instance, we can write:

(123.456).toFixed(1);

We have “123.5” .

The toExponential method returns the number string in exponential notation.

For instance, if we have (12345).toExponential() , then we get:

"1.2345e+4"

The toString method lets us convert numbers to number strings of various bases.

For instance, we can write:

(255).toString(2)

Then we convert the number to the binary string:

"11111111"

And we can write:

(255).toString(16)

and get:

"ff"

To convert it to a decimal, we write:

(255).toString(10)

And we get:

"255"

String

The String function is used to create a string.

We can use it as a constructor or factory function.

We don’t want to create an object with it to reduce confusion, so we should use it as a factory function.

For instance, we can write:

const obj = new String('foo');

then we create a string wrapper object.

To convert it to a primitive value, we call valueOf :

const s = obj.valueOf();

It’s better just to create a string as a string literal:

const s = 'foo';

We can also use the function to convert non-strings to strings:

const s = String(123);

We can get the number of characters in a string with the length property.

So if we have:

const s = 'foo';

Then s.length is 3.

If we pass in an object to String , then the toString method will be called.

So:

String({
  a: 1
});

returns:

"[object Object]"

And:

String([1, 2, 3]);

returns:

"1,2,3"

Conclusion

Boolean, Number, and String functions let us create primitive values.

We should use them as factory functions to convert between different primitive types.

Categories
Object-Oriented JavaScript

Object-Oriented JavaScript — Arrays and Functions

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 functions.

ES6 Array Methods

ES6 added more useful array methods.

They provided that were previously provided by 3rd party libraries like Underscore and Lodash.

Array.from

The Array.from method lets us convert iterable objects and non-iterable array-like objects into an array.

For instance, we can use it to convert a NodeList returned from document.querySelectorAll into an array.

We can write:

const divs = document.querySelectorAll('div');
console.log(Array.from(divs));

Then we get an array.

We can also convert objects that have numeric index and a length property into an array.

For example, we can write:

const obj = {
  0: 'a',
  1: 'b',
  length: 2
};
console.log(Array.from(obj));

And we get:

["a", "b"]

Creating Arrays Using Array.of

We can use the Array.of method to create a new array.

For instance, we can with:

let arr = Array.of(1, "2", {
  obj: "3"
})

Then we get:

[
  1,
  "2",
  {
    "obj": "3"
  }
]

It takes one or more arguments and returns an array with the arguments.

ES6 Array.prototype Methods

The array instance all have more methods added to them.

They include the following methods:”

  • Array.prototype.entries()
  • Array.prototype.values()
  • Array.prorotype.keys()

entries returns the key-value pair array.

values returns an array of values.

keys returns an array of keys.

So we can write:

let arr = ['a', 'b', 'c']
for (const index of arr.keys()) {
  console.log(index)
}

for (const value of arr.values()) {
  console.log(value)
}

for (const [index, value] of arr.entries()) {
  console.log(index, value)
}

We log the index with the keys method.

And we log the values withe values method.

And index and value with the entries method.

It also added the find and findIndex methods to let us find the first entry of the array that matches a given condition.

find returns the matched entry.

And findIndex returns the index of the matched entry.

For instance, we can write:

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(numbers.find(n => n > 3));
console.log(numbers.findIndex(n => n > 3));

Then we get 4 and 3 respectively from the console log.

Function

The Function constructor can be used to create a function

For instance, we can write:

const foo = new Function(
  'a, b, c, d',
  'return arguments;'
);

The first argument is the parameters and the 2nd is the function body.

It’s not a good idea to use it since we create functions with strings, which means there will be security and performance issues.

Functions objects have the constrictor and length properties.

The constructor property has the constructor that created the function, which should be the Function constructor.

And the length property has the number of parameters the function expects.

So if we have:

function foo(a, b, c) {
  return true;
}
console.log(foo.length);
console.log(foo.constructor);

We get 3 and ƒ Function() { [native code] } respectively.

Conclusion

We can create arrays with the Array.from and Array.from methods.

Also, we can traverse arrays with various methods.

The Function constructor shouldn’t be used to create functions.

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.