My journey to learn JavaScript - Part 2 - Functions and Objects

in #programming8 years ago

Following up on my last post where I briefly described my understanding of JavaScript Statements and Variables, I like to share in this post what I have learned so far about Functions and Objects.

Functions

Functions are one of the fundamental building blocks in JavaScript and most other program languages. A Function can exist of one or multiple Statement’s which perform a task like adding/removing values to an array (More on that later!) or a calculation.

Function example:

function payput(postReward) {
var authorReward = postReward / 1.25;
return authorReward;
}

So what does this mean in detail? Let’s break it down.

function - is the JS keyword to declare a function followed by a name (payout) and optional a parameter (postReward).

Inside the { } of the function we have a statement, in this case a variable called authorReward that performs a calculation. (post Reward - 25%).

Last we have the return statement that ends the function and returns the calculated value (authorReward).

In order to call the function, we just need to type the function name followed by an argument (value inside the brackets) into the console. Something like this.

payouts(50);

As a result we get a value back of 40. (50 - 25%).

To summarise, functions become very handy if you need to do the same operation multiple times since you can call the operating task by just using the function name instead of writing the full operation out every time.

Objects

An object is like a “container” that can hold multiple values and/or functions. If you like to describe a person in JS than the object could look like this.

var person = {
name: 'Tarek',
born: 1979,
married: true
}

Let’s break it down again for more details.

Like with declaring a single variable the var statement is used when declaring an object (person) followed by curly brackets. Within the curly brackets multiple properties can be assigned.

  • Under name property we store a String (Tarek)
  • Under born property we store a number (1979)
  • And under married property we store a boolean value (true)

More on boolean operations later!

If we than like to access any of the properties we assigned to the object (person), let’s say the name, we can type the following statement into the console.

person.name

The result in the next line will be Tarek

That was one example to read a property out of an object. If we like to change any of the properties inside an object we can do so as well by over-writing an object property. That can be done like this.

person.name = (‘Sami’);

If you read the name value again now using person.name you will get the name Sami instead.

I hope this overview of Functions and Objects was useful to you. The next post on my JS learning progress will come soon.

Coin Marketplace

STEEM 0.17
TRX 0.13
JST 0.027
BTC 59356.21
ETH 2723.43
USDT 1.00
SBD 2.53