Categories
Object-Oriented JavaScript

Object-Oriented JavaScript — Parameters and Built-in 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 various kinds of functions and parameters.

Default Parameters

We can set default parameters in a function.

To do that, we just assign a value to a parameter.

We can write:

function render(fogLevel = 0, sparkLevel = 100) {
  console.log(`Fog Level: ${fogLevel} and spark level:
${sparkLevel}`)
}

We have a render function with the fogLevel and sparkLevel parameters.

And we set their default to 0 and 100 respectively.

Then if we have:

render()

Then we get:

'Fog Level: 0 and spark level: 100'

Default parameters have their own scope.

The scope is sandwich between the outer functina and the inner function scope.

So if we have:

let scope = "outer";

function scoper(val = scope) {
  let scope = "inner";
  console.log(val);
}
scoper();

Then val would be 'outer' since it takes scope from outside of the function.

Rest Parameters

Rest parameters let us get an arbitrary number of arguments from a function.

For instance, we can write:

function getTodos(...todos) {
  console.log(Array.isArray(todos));
  console.log(todos)
}

Then we get the first console log is true .

And the 2nd is [“eat”, “drink”, “sleep”] .

todos is an array because we have a rest operator before it.

This makes it gets the arguments and put them all in the todos array.

And we get all of them with the 2nd console log.

Spread Operators

The spread operator lets us spread array entries as arguments of a function.

We can also use it to spread values in an array.

For instance, we can write:

const min = Math.min(...[1, 2, 3]);

This replaces the old way, which is:

const min = Math.min.apply(undefined, [1, 2, 3]);

The spread operator is easier to understand and it’s shorter.

1, 2 and 3 are the arguments of Math.min .

We can also use the spread operator to merge array items into another array.

For instance, we can write:

const midweek = ['Wed', 'Thu'];
const weekend = ['Sat', 'Sun'];
const week = ['Mon', 'Tue', ...midweek, 'Fri', ...weekend]

Then week is:

["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]

Predefined Functions

There’s a number of predefined functions in JavaScript.

They’re:

  • parseInt()
  • parseFloat()
  • isNaN()
  • isFinite()
  • encodeURI()
  • decodeURI()
  • encodeURIComponent()
  • decodeURIComponent()
  • eval()

parseInt parses a non-number value to an integer.

For instance, we can use parseInt by writing:

parseInt('123')

parseFloat parses a non-number value to a floating-point number.

And we get 123 .

For instance, we can use parseFloatby writing:

parseFloat('123.45')

And we get 123.45 .

isNaN checks if a value is NaN .

So if we have:

isNaN(NaN)

We get true .

isFinite checks if a value is a finite number.

So we can write:

isFinite(Infinity)

and we get false .

We can encode a string to a URI with encodeURI .

For instance, if we have:

const url = 'http://www.example.com/foo?bar=this and that';
console.log(encodeURI(url));

and we get:

'http://www.example.com/foo?bar=this%20and%20that'

And we can decode a URI string with decodeURI .

encoudeURIComponent and decodeURIComponent can do the same thing for part of a URI.

If we write:

const url = 'http://www.example.com/foo?bar=this and that';
console.log(encodeURIComponent(url));

and we get:

'http%3A%2F%2Fwww.example.com%2Ffoo%3Fbar%3Dthis%20and%20that'

eval lets us run code from a string. This is one we shouldn’t use because anyone can pass in a malicious string to it.

And code in strings can’t be optimized.

Conclusion

Default parameters let us set default values for parameters if they aren’t set with arguments.

JavaScript comes with some predefined functions we can use.

The rest and spread operator are handy for handling arguments.

Categories
Object-Oriented JavaScript

Object-Oriented JavaScript — Objects and Constructors

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 objects and constructors.

Accessing an Object’s Properties

We can access an object’s properties by using the square bracket notation or the dot notation.

To use the square bracket notation, we can write:

dog['name']

This works for all property names, whether they’re valid identifiers or not.

We can also use them to access properties by passing in a property name dynamically with a string or symbol.

The dot notation can be used by writing:

dog.name

This is shorter but only works with valid identifiers.

An object can contain another object.

For instance, we can write:

const book = {
  name: 'javascript basics',
  published: 2020,
  author: {
    firstName: 'jane',
    lastName: 'smith'
  }
};

The author property has the firstName and lastName properties.

We can get nested properties by writing:

book['author']['firstName']

or

book.author.firstName

We can mix the square brackets and dot notation.

So we can write:

book['author'].firstName

Calling an Object’s Methods

We can call a method the same way we call any other function.

For instance, if we have the following object:

const dog = {
  name: 'james',
  gender: 'male',
  speak() {
    console.log('woof');
  }
};

Then we can call the speak method by writing:

dog.speak()

Altering Properties/Methods

We can change properties by assigning a value.

For instance, we can write:

dog.name = 'jane';
dog.gender = 'female';
dog.speak = function() {
  console.log('she barked');
}

We can delete a property from an object with the delete operator:

delete dog.name

Then when we try to get dog.name , we get undefined .

Using this Value

An object has its own this value.

We can use it in our object’s methods.

For instance, we can write:

const dog = {
  name: 'james',
  sayName() {
    return this.name;
  }
};

We return this.name , which should be 'james' .

Because this is the dog object within the sayName method.

Constructor Functions

We can create constructor functions to let us create objects with a fixed structure.

For instance, we can write:

function Person(name, occupation) {
  this.name = name;
  this.occupation = occupation;
  this.whoAreYou = function() {
    return `${this.name} ${this.occupation}`
  };
}

We have the instance properties name , occupation and the this.whoAreYou instance method.

They’re all returned when we create a new object with the constructor.

Then we can use the new operator to create a new Person instance:

const jane = new Person('jane', 'writer');

The value of this os set to the returned Person instance.

We should capitalize the first letter of the constructor so that we can tell them apart from other functions.

We shouldn’t call constructor functions without the new operator.

So we don’t write:

const jane = Person('jane', 'writer');

The value of this won’t be set to the returned Person instance this way.

The Global Object

The global object in the browser is the window object.

We can add properties to it with var at the top level:

var a = 1;

Then window.a would be 1.

Calling a constructor without new will return undefined .

So if we have:

const jane = Person('jane', 'writer');

then jane is undefined .

The built-in global functions are properties of the global object.

So parseInt is the same as window.parseInt .

Conclusion

We can access object properties in 2 ways.

Also, we can create constructor functions to create objects with a set structure.

Categories
Object-Oriented JavaScript

Object-Oriented JavaScript — Object Properties

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 object properties.

Object Properties and Attributes

Object properties have their own attributes.

They include the enumerable and configurable attributes.

And they’re both booleans.

Enumerable means if we can enumerate the properties.

And configurable means the property can’t be deleted or change any attributes if it’s false .

We can use the Object.getOwnPropertyDescriptor method by writing:

let obj = {
  name: 'james'
}
console.log(Object.getOwnPropertyDescriptor(obj, 'name'));

And we get:

{value: "james", writable: true, enumerable: true, configurable: true}

from the console log.

Object Methods

ES6 comes with various object methods.

Copy Properties using Object.assign

We can use the Object.assign method to copy properties.

For instance, we can write:

let a = {}
Object.assign(a, {
  age: 25
})

Then a is:

{age: 25}

We copy the age property to the a object, so that’s what we get.

Object.assign can take multiple source objects.

For instance, we can write:

let a = {}
Object.assign(a, {
  a: 2
}, {
  c: 4
}, {
  b: 5
})

Then a is:

{a: 2, c: 4, b: 5}

All the properties from each object will be copied.

If there’re any conflicts:

let a = {
  a: 1,
  b: 2
}
Object.assign(a, {
  a: 2
}, {
  c: 4
}, {
  b: 5
})

console.log(a)

then the later ones will make precedences.

So a is the same.

Compare Values with Object.is

We can compare values with Object.is .

It’s mostly the same as === , except that NaN is equal to itself.

And +0 is not the same as -0 .

For instance, if we have:

console.log(NaN === NaN)
console.log(-0 === +0)

Then we get:

false
true

And if we have:

console.log(Object.is(NaN, NaN))
console.log(Object.is(-0, +0))

We get:

true
false

Destructuring

Destructuring lets us decompose object properties into variables.

For instance, instead of writing:

const config = {
  server: 'localhost',
  port: '8080'
}
const server = config.server;
const port = config.port;

We can write:

const config = {
  server: 'localhost',
  port: '8080'
}
const {
  server,
  port
} = config

It’s much shorter than the first example.

Destructuring also works on arrays.

For instance, we can write:

const arr = ['a', 'b'];
const [a, b] = arr;

Then a is 'a' and b is 'b' .

It’s also handy for swapping variable values.

For instance, we can write:

let a = 1,
  b = 2;
[b, a] = [a, b];

Then b is 1 and a is 2.

Built-in Objects

JavaScript comes with various constructors.

They include ones like Object , Array , Boolean , Function , Number , and String .

These can create various kinds of objects.

Utility objects includes Math , Date , and RegExp .

Error objects can be created with the Error constructor.

Object

The Object constructor can be used to create objects.

So these are equivalent:

const o = {};
const o = new Object();

The 2nd one is just longer.

They both inherit from the Object.prototype which has various built-in properties.

For instance, there’s the toString method to convert an object to a string.

And there’s the valueOf method to return a representation of an object.

For simple objects, valueOf just returns the object. So:

console.log(o.valueOf() === o)

And we get true .

Conclusion

Objects have various properties and methods.

They inherit various methods that let us convert to different forms.

Categories
Object-Oriented JavaScript

Object-Oriented JavaScript — Loops 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 various kinds of loops and functions.

Loops

There are various kinds of loops we can use with JavaScript.

For…in Loops

The for…in loop lets us loop through an object’s keys.

For example, we can write:

let obj = {
  a: 1,
  b: 2,
  c: 3
}
for (const key in obj) {
  console.log(key, obj[key])
}

And we get the key with the key and we can access the value with obj[key] .

For…of Loops

The for…of loop lets us iterate through iterable objects, including arrays.

For instance, we can write:

let arr = [1, 2, 3]
for (const a of arr) {
  console.log(a);
}

We have the arr array which we loop through with the for-of loop.

a has the array entry.

Comments

Comments are part of the code that’s ignore by JavaSdcript engines.

We can use them to explain how our code works.

Single line comments starts with // and ends at the end of the line.

Multiline comments starts with /* and ends with */ .

Anything in between them are ignored.

So we can write:

// single line

and:

/* multi-line comment on a single line */

or:

/*
  multi-line comment on a single line
*/

Functions

Functions is a reusable piece of code.

We can use them to do something in our code.

There are various kinds of functions, they include:

  • anonymous functions
  • callbacks
  • immediate (self-invoking) functions
  • inner functions (functions defined inside other functions)
  • functions that return functions
  • functions that redefine themselves
  • closures
  • arrow functions

They let us group together code, give it a name, and reuse it later.

We can define a function by writing:

function sum(a, b) {
  let c = a + b;
  return c;
}

And we return the sum of a and b in the function.

a and b are parameters and we return a value.

We have the function keyword to define a function.

return lets us return a value.

If there’s no return statement, then it returns undefined .

We can also create arrow functions by writing

const sum = (a, b) => {
  let c = a + b;
  return c;
}

or we can write:

const sum = (a, b) => a + b

They don’t bind to this and they’re shorter.

Calling a Function

We can call a function by writing:

const result = sum(1, 2);

The values in the parentheses are the arguments.

They’re set as the value of the parameters.

Parameters

Parameters are the items in the parentheses of the function.

So if we have:

function sum(a, b) {
  let c = a + b;
  return c;
}

then a and b are parentheses.

We pass in arguments to set them.

They’re set by their position.

If we forgot to pass them in then they’ll be undefined .

JavaScript isn’t picky when checking arguments.

The type can be anything, and we can skip any of them.

It’ll just do things that we don’t expect and fails silently if we don’t pass in what’s expected.

Conclusion

Functions are reusable pieces of code we can invoke.

for…in loops let us loop through objects and for…of loops let us loop through iterable objects.

Categories
Object-Oriented JavaScript

Object-Oriented JavaScript — Functions and Objects

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

Iterators

Iterators can be created with generator functions in JavaScript.

For instance, we can write:

function* genFn() {
  yield 1;
  yield 2;
  yield 3;
}

We have a generator function as indicated by the function* keyword.

Then we can call it to return an iterator:

const gen = genFn();
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());

We called genFn to get an iterator.

Then we called next on the returned iterator.

And the next method will return the object with the value and done properties.

value has the value from yield .

And done is a boolean to indicate whether all the values are returned.

IIFE vs Blocks

We don’t need IIFEs for containing variables in blocks anymore.

We can use let and const to declare block-scoped variables.

So if we have:

(function() {
  var foo = 0;
}());
console.log(foo);

Then the console log will throw the ‘Uncaught ReferenceError: foo is not defined’ error.

We can do the same thing with let or const variables in blocks”

{
  let foo = 1;
  const bar = 2;
}

Arrow Functions

Arrow functions are great for creating callbacks.

For example, we often have to write code like:

$("#submit-btn").click(function(event) {
  validateForm();
  submit();
});

Arrow functions are a bit shorter and we won’t have to worry about the value of this in the function.

Instead, we can write:

$("#submit-btn").click((event) => {
  validateForm();
  submit();
});

We can write arrow functions in various ways. They’re:

  • No parameters: () => {...}
  • One parameter: a => {...}
  • More than one parameters: (a,b) => {...}

Arrow functions can have both statement block bodies or expressions.

We can have a statement block with:

n => {
  return n ** 2;
}

And we can have an expression with:

n => n ** 2;

Objects

Objects are the most central part of object-oriented programming.

It’s made of various properties and methods.

And properties may contain primitive values or other objects.

We can create an object by writing:

const person = {
  name: 'james',
  gender: 'male'
};

An object is surrounded by curly braces.

And name and gender are the properties.

The keys can be in quotation marks.

For instance, we can write:

const person = {
  'name': 'james',
  gender: 'male'
};

We need to quote property names if the property name is one of the reserved words in JavaScript.

We also need to quote them if they have spaces.

And if they start with a number, then we also need to quote them.

Defining an object with {} is called the object literal notation.

Elements, Properties, Methods, and Members

An array can have elements.

But an object has properties, methods, and members.

The object:

const person = {
  name: 'james',
  gender: 'male'
};

only has properties.

Properties are key-value pairs.

The value can be anything.

Methods are just properties with function values.

So if we have:

const dog = {
  name: 'james',
  gender: 'male',
  speak() {
    console.log('woof');
  }
};

Then speak is a method.

Hashes and Associative Arrays

Object properties can be added and remove dynamically, so we can use them as hashes or associative arrays.

Hashes and associative arrays are just key-value pairs.

Conclusion

We can create iterators with generators, and we can define objects with properties and methods.