JavaScript Basics Tutorial

An overview of Javascript fundementals

Functions

A function is a stored set of statements that perform some tasks or does some computation and then return the result to the user. Once stored the function can then be called whenever it is needed instead of rewriting all those statements. It can also be set to take input values.

The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can call that function.

JavaScript has many built-in functions that we can call to perform certain tasks. We can also create our own user-defined functions in JavaScript using the keyword function. This is the basic syntax to create a function in JavaScript:


function functionName(inputParameter1, inputParameter2, ...) { 
    //function statements
}

Example


//this function doubles the input value                
function doubleNumber(number) {
    return number * 2;
}

//here we call the function
console.log(doubleNumber(10));  //outputs 20

            

Javascript has many built-in function for performing various tasks

Here are some common built-in functions:

  • charAt() - returns a character in a string at the given index
  • indexOf() - returns the index of a the first occurrence of a character in a string
  • charCodeAt() - returns the ascii number of the character at the given index in a string
  • fromCharCode() - returns the character of the given ascii number
  • replace() - replaces a matched substring with a new substring
  • split() - splits a string into an array of substrings
  • toUpperCase() - returns the given string all in upper case
  • toLowerCase() - returns the given string in all lower case
  • join() - opposite of split(). Joins all array elements into a string
  • pow() - returns a base to the exponent power
  • min() - returns the smallest valued element
  • max() - returns the largest value element
  • round() - returns a number rounded to the nearest integer

Exercise

Create a function called 'add' that adds 2 numbers and returns the result.


 add(num1, num2) {
    let result = num1   ;
    return ();
}

  try Again!
            
 prev  Maps
events  next