JavaScript Functions Tutorial

JavaScript Functions Tutorial


Introduction: What are JavaScript functions?

A JavaScript function is a block of code which performs a specific task. They are used to break down and organize the code into manageable chunks. Functions can be used to create custom objects, filters, and many other things.

JavaScript functions are defined using the function keyword followed by a name for the function and a pair of parentheses containing zero or more comma-separated parameters (or arguments). The function parameter list will be in between those parenthesis ( ). The parameters are optional and we might call them variables inside the a functions. The body of the function is enclosed in curly braces {}, which may include one or more statements inside them.

What is an example of a function in JavaScript?

function Name (parameter1, parameter2) {

statements;

return value;

}

Lets break it down to:

  • The function keyword
  • The name after the keyword
  • Optional parameters
  • Statements that carries the tasks
  • Return keyword to get some output

Now let’s create a real example, let us start with a function that can add two numbers:

function add(num1, num2) {

  let result = num1 + num2

  console.log(result)

return result

}

This function can add two values, but first we need to call the function with the two values that we want them added (Argument1, Argument 2):

add(2, 3)

// output: the return statement should return : 5

Another good thing from JavaScript is that it let you keep the output of a function into a variable, so instead of the add(2,3) we can write:

const addOutput = add(2,3)

// output: the return statement should return the addOutput's variable with : 5

With that I stored the value of the function into a variable and I don’t have every single time to call the function with same arguments passed on to get the same output. Instead only use the addOutput variable that will store the add function’s returning value.

Things to keep in mind:

  • The variables names are case sensitive. addoutput is different than addOutput, we use the camel case in javaScript. Start with lower char than with each other word we go upper for the first char only.
  • Using descriptive names, avoid x, y or z names for the parameters and functions names.
  • Writing the function called declaring the function
  • Calling the function called invoking or calling the function
JavaScript Functions Tutorial
JavaScript Functions Tutorial

Declarations

Declare a function that called an expression

Just as the way we used the declare a variable to store the values returned from a function above, we can use the same technique to declare a function, and it is called the function expression

This is how:

const add = function(num1, num2) {

  let result = num1 + num2

  console.log(result)

  return result

}


add(2,3)

// output: 5

Function that called IIFE (Immediately invoked function expression)

An IIFE is a type of a function that we need to write when we want the function to run, called or invoked immediately.

(function (num1, num2) {

let result = num1 + num2

console.log(result)

})(2,3)

// output: 5
// Notice we didn't have to call the function by a name, also notice the function has no name!

Things to keep in mind with function expression:

  • Expressions are anonymous, so we’ll see later in this post why it’s important that we should be familiar with the different kinds of functions.
  • IIFE is an expression type of functions as well

Parameters in javascript:

We only call a parameter an argument when it carries a value. By default, JavaScript’s has an array-like object Arguments to you access all the parameters passed to a function without having to name or use them one by one.

function add() {

let argsTotal = 0

for (let i = 0; i < arguments.length; i++) {

// Here we see that javascript give us an access to the object like array called arguments

argsTotal += arguments[i]

}

return argsTotal

}

const output = add(2,3,1)

console.log(output) // 6

With the recent version of JavaScript, we got another present called the rest operator. This is basically give us what arguments (array-like object) does, but in a better way. And by better way, I mean that now I have an array that I can use all array’s methods with, like sort(), filter(), map(), or reduce().

function add (...args) {

let argsTotal = args.reduce(function(sum, value) {

return (sum + value)

})

return argsTotal

}

const output = add(2,3,1)

console.log(output)
// output: 6

Things to keep in mind about parameters:

  • This array like object does not have an access to some array methods like map, filter or sort
  • More recent version of javascript, let you use the rest operator with as the last parameters within the function: function add(num1, num2, …args) {} – or just for simplicity: function add(…args) {}
  • This rest parameters can accept an infinite numbers of arguments, and its always should be at the end of the parameters list
  • While the Arguments object isn’t a real array, the rest parameters is and you could use all the array’s methods with it
  • When I pass an object as an argument? when I need to pass a value by reference and I don’t care about the order of the arguments
JavaScript Functions Tutorial
JavaScript Functions Tutorial

Scope

In order to understand the scope, we need to take a look at a variable. You need to know where it is declared?, by what it is declared?. By where I mean on which block {} or which line. By what i mean by what keyword (var, let or const keywords) or if it’s normal declaration or expression. Let’s just say never use “var” keyword 🙂

Although I asked not to use it, but you will definitely run into a code that uses it. So, you should be familiar with it to avoid any troubles.

var nerdLevel = "nerd"

function doStudy() {

nerdLevel = "not nerd"

console.log(nerdLevel)

}

doStudy()
//output: not nerd

In the previous example nerdLevel variable defined in the global scope, notice that we didn’t declare it inside the function, yet we can use it and change it’s value.

In the following example we use the nerdLevel variable in function scope using “var”:


function doStudyNerd() {

var nerdLevel = "Not Nerd"

console.log(nerdLevel)

}

doStudyNerd()

//output Not Nerd

Let’s take a look now on the only block scope keywords variable declarations: let and const. In the following example we can change let to const and we will get the same result. However, we only need to use const if we know that its value will not change. Hence the name const from constant. Or we can use it for the passed references object like arrays and functions.

let nerdLevel= "nerd"

function doStudy() {

let nerdLevel = "not nerd"

console.log(nerdLevel)

}

doStudy() // output: not nerd

console.log(nerdLevel) // output: nerd

Those two variables with the same name should not be allowed, but if you notice the same name yes, but it shows in different occasions. Hence, the scope is different and it’s not the same. The first time it appears, it was within the global scope, so when you call it in the global scope, it shows the value of “nerd”.

The other occasion was when you created it inside the function, which is why when you invoked the function, it only showed its value because it lives within that function.

Things to keep in mind about scope:

  • If you didn’t use a declaration keyword like let, var or const javascript will assume that you want to use var

Hoisting

Hoisting is the process of moving a variable declaration to the top of its containing scope, in order to make it available as soon as possible.

If you have a function declared on line number 300 but you actually invoked it or call this very same function in line number 100.

Logically this is impossible to execute, but luckily with javascript the compiler actually can hoisted before the invoking or calling so it dost not results an error.

Remember that I told you above that it’s important that we know which type of function we should pick before the declarations? normal or expressions. Because the hoisting happens when you declare the function in the normal way, not the expression way when you anonymously store it inside a variable.

Things to keep in mind about hoisting:

  • Keyword const is the same as let keyword, but const used if we want to use a constant value or use a declaration expression.
  • Function’s normal declarations are like var· They will be hoisted, whereas function expressions won’t.

Methods

Methods are one of the procedures and actions that can be performed on an object in JavaScript. In the following examples, we will be looking at how to create and invoke a method within an object.

The keyword this

Whenever we use the keyword this in JavaScript code, we mean an object. That’s why it’s always a good idea to see the context in which you’re using the keyword this, as the answer always depends on that.

const nerdsInfo = {

social: {

blog: "nerdleveltech.com",

twitter: "twitter.com/NerdLevelTech",

reddit: "www.reddit.com/user/NerdLevelTech"

},

printSocial: function(data) {

console.log(`${data.blog} ${data.twitter} ${data.reddit}`)

}

}

nerdsInfo.printSocial(nerdsInfo.social)

// output: nerdleveltech.com twitter.com/NerdLevelTech www.reddit.com/user/NerdLevelTech

But with using keyword this we can do that instead:

const nerdsInfo = {

social: {

blog: "nerdleveltech.com",

twitter: "twitter.com/NerdLevelTech",

reddit: "www.reddit.com/user/NerdLevelTech"

},

printSocial: function(data) {

console.log(`${this.social.blog} ${this.social.twitter} ${this.social.reddit}`)

}

}

nerdsInfo.printSocial()

// output: nerdleveltech.com twitter.com/NerdLevelTech www.reddit.com/user/NerdLevelTech

And if we wan’t to enhance the code a little bit and make it more practical example, we can write the following:

const nerdsInfo = {

social: {

blog: "nerdleveltech.com",

twitter: "twitter.com/NerdLevelTech",

reddit: "www.reddit.com/user/NerdLevelTech"

},

printSocial: function() {

for (const key in this.social){

console.log(`${key} ${this.social[key]}`)

}

}

}

nerdsInfo.printSocial()

// output:

// blog nerdleveltech.com

// twitter twitter.com/NerdLevelTech

// reddit www.reddit.com/user/NerdLevelTech

Things to keep in mind about keyword this:

  • If we use the keyword this within a function scope, we mean the global object at that time
  • If we use the keyword this within object scope, we mean that object at that time
Return Statement
Return Statement

The return statement

The keyword return represents the results of a function after we return the results, the execution of this function is done. In other words it ends the function’s execution

function add (num1, num2) {

return console.log('Add Results: '),

num1 + num2

}

console.log(add(2,3))

// output: Add Results: 5

What if we take a new line after the return? what would you think the results of the code would be?

function add (num1, num2) {

return

console.log('Add Results: '),

num1 + num2

}

console.log(add(2,3))

// output: undefined

Can you make an educated guess? and why?

The reason for undefined result is the compiler automatically put at the end of each line the semicolon “;“

So when the compiler assume that this is the end of the line, it will be only return; and that of course return undefined.

Now you need to include the parenthesis like the following:

function add (num1, num2) {

return(

console.log('Add Results: '),

num1 + num2

)

}

console.log(add(2,3))
// output: Add Results: 5

Things to keep in mind about return statement:

  • Multiple returns can be in the same function with a conditional statements, once any of the return be true, the function will return at that point and the function will end
  • If there is no return the function when invoked, the function will return undefined

No comment

Leave a Reply

Your email address will not be published. Required fields are marked *