JavaScript Function

Making use of the JavaScript function to its full potential

JavaScript Function

Greetings, friends. Welcome to my blog today. Are you looking forward to making use of the JavaScript function to its full potential? Then you are at the right place.

Introduction

For a while, I used JavaScript functions, but I wasn't completely utilizing them. I only had a basic understanding of function syntax and how to use it. My problem-solving capabilities were limited, and I'll have to write additional code to fix an issue caused by my failure to fully utilize JavaScript functionalities.
Let's learn it the simple way.

lets-get-started


Explanation

What a function
Looking at it from an English dictionary perspective, A function is an action or activity proper to a person, thing, or institution. Read more.
Functions are a collection of instructions that accomplish a single task. A function that adds two numbers together. A function that prints a message on the screen is also an example of a function.

JavaScript Function Syntax

  • A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().

  • Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

  • The parentheses may include parameter names separated by commas: (parameter1, parameter2,...)

  • The code to be executed by the function is placed inside curly brackets. {}

function name(parameter1, parameter2, parameter3) {
// code to be executed
}

Naming a function

Because functions are such an important part of JavaScript, it's very important to understand how to name them correctly.
-Names are case-sensitive; lowercase and uppercase are different. -Start function names with a letter; use camelCase for names. -Use descriptive names and usual verbs in the imperative form. -Common prefixes are "get," "make," "apply," etc. -Class methods follow the same rules. -JavaScript functions are written in camel case too. In addition, it's best practice to tell what the function is doing by giving the function name a verb as a prefix.

// bad
function name(){...}
// Correct
function getName(){...}
// bad
function submit()...
// Correct
function handelSubmit(){...}

Parameters

Let's look at it from the dictionary.A numerical or other measurable factor forming one of the sets that define a system or set the conditions of its operationRead more
A parameter is a named variable passed into a function. It's a placeholder for the set of data that the function requires but isn't currently available. When the function is invoked, the value of these placeholders will be given.
Parameters in a function are locale variables.

// code here can NOT use carName
function myFunction() {
  let carName = "Volvo";
  // code here CAN use carName
}
// code here can NOT use carName

Local variables

are variables that are defined within functions. They have local scope, which means that they can only be used within the functions that define them. Read more

Default Parameters

If a function is called with fewer arguments (less than declared), the missing values are set to undefined and might cause an error while running the function. This is okay in some cases, but in others, it is preferable to set a default value for the parameter.

function myFunction(x, y = 2) {
  // function code
}

Function Invocation

The code inside the function will execute when "something" invokes (calls) the function

  • When an event occurs (when a user clicks a button)
  • When it is invoked (called) from JavaScript code
  • Automatically (self invoked)

Invocation by event

the function is triggered when an event occurs.

//<div onClick='name()'> Click me</div>
function name(){
 alert(' my  name is john')
}

Invocation by calling

the function is triggered when it is called

function name(){
 alert(' my  name is john')
}
name()

Self-Invoking Functions

These are function expressions that can invoke themselves. A self-invoking expression is invoked (started) automatically, without being called. Function expressions will execute automatically if the expression is followed by (). You cannot self-invoke a function declaration.

(function () {
  let x = "Hello!!";  // I will invoke myself
})();

Return

The return statement is used to return a particular value from the function to the function caller. The function will stop executing when the return statement is called.
Note The return statement should be the last in a function because the code after the return statement will be unreachable.

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

console.log(sum(2+3)) // log=> 5

Returning multiple values

The return statement terminates the function and returns values that can be used outside the function. If the value to be returned is multiple, there are several options.

Using Array

In this example, we are returning multiple values by using the Array. Here, we are using the ES6 Array destructuring syntax to unpack the values of an array.

function getData() {  
let name = 'John',  
age = '25',  


return [name, age];  
}  
const [name, age] = getData();  
console.log(name) // log=> John
console.log(age) // log=> 25

Using Object

In this example, we are returning multiple values by using the Object. Here, we are using the ES6 Object destructuring syntax to unpack the values of the object.

function getData() {  
return {name:John, age:25};  
}  
const {name, age} = getData();  
console.log(name) // log=> John
console.log(age) // log=> 25

Conclusion

Learning how to properly use functions will save you a lot of stress in solving a code challenge. For example, validation of variable to make sure it is not empty.

Const value = 0

Function validateValue(){
if(value === 0){
console.log('error')
}else{
console.log(value)
}
}

Let look at the simplified and more readable example.

Const value = 0

Function validateValue(){
if( value === 0){
return console.log('error')
}

console.log(value)
}

We totally remove the else, it will reduce or stop the use of unnecessary ifelse statements. This is a very short example, but when it gets longer it will save a lot of stress.
Let keep our code simple and readable.


Congratulations

Congratulations
It's been a long trip, i am glad you made it to the end.

Give feedback

If you liked this article and learnt anything new, please follow me for more web-simplified subjects and give me feedback using the reaction emojis and comments, let me know what you think about the explanation. Provide suggestions, corrections, and criticism.

Let us connect

I would like to connect with any and every reader Let us connect
victorjosiah19@Twitter
josiah-victor@LinkedIn