Javascript Functions | top to bottom *

Javascript Links

Tabbbbbbbbcheat sheetCSS Functionslinks

https://www.bitdegree.org/learn/javascript-function

 

For a program to work, the computer needs some specific instructions on what, how, when, and where tasks need to be done. In JavaScript, we use functions to define these steps for the browser. In this tutorial, you'll learn about JavaScript functions, what they are, and how they are written.

We will introduce you to JavaScript function arguments which are passed to functions as values, and JS function parameters, which refer to the names included in the function. You'll learn about correct JavaScript function syntax as well.

Contents

JavaScript Function: Main Tips

  • When something calls (invokes) a function, it is executed by the program.
  • A function in JavaScript is specified with the function keyword, a name (optional), and parentheses (()).
  • JavaScript function names can have digits, letters, dollar signs ($), and underscores (_).
  • It may include names of parameters (values) separated by commas: (value1, value2, etc.).
  • The code must be in the curly brackets ({}) to be executed.
  • The names listed in the JavaScript function definition are function parameters.
  • The real values received by the invoked function are function arguments.
  • The arguments perform as local variables inside the function.

What are Functions?

To put it simply, JavaScript functions are blocks of code that perform specific tasks. Some of them are in-built in the language, but you can also create your own. If you know how, that is.

In the example below, you can see a function which multiplies z1 by z2, and then the browser returns the value. This means that the function performed a calculation, returned the answer, and ended:

Example Copy

function learnFunction(z1, z2) {
    return z1 * z2;
}

Try it LiveLearn on Udacity

 

Basic Syntax

Writing JS functions is relatively easy if you know how to do it. Follow these steps, and you'll never have to worry about JavaScript function syntax ever again:

  • Before you begin determining a function, write function on a new line.
  • Now, start by writing its name. You can create whatever name you wish.
  • Then, open the parentheses and write the parameters (arguments) of the function. When you finish, don't forget to close the parentheses.
  • Open up curly braces and begin from a new line.
  • On a new line, write down what should a function do with these arguments.
  • Close the curly braces.

The final result should look like this: function myName(myPara1, myPara2, myPara3) {code to be executed}

Function Invocation

JavaScript functions only start doing something when something invokes them. Only then the JavaScript function code will be executed. A function in JavaScript can be invoked with these events:

  • When a user invokes it (e.g., clicks a button).
  • When a browser invokes it (e.g., a page finishes loading).
  • When it is called (invoked) from JavaScript code.
  • Automatically (self-invoked).

Udacity

Pros

  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features

Main Features

  • Nanodegree programs
  • Suitable for enterprises
  • Paid certificates of completion

EXCLUSIVE: 75% OFF

Udemy

Pros

  • Easy to navigate
  • No technical issues
  • Seems to care about its users

Main Features

  • Huge variety of courses
  • 30-day refund policy
  • Free certificates of completion

AS LOW AS 12.99$

Datacamp

Pros

  • Great user experience
  • Offers quality content
  • Very transparent with their pricing

Main Features

  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable

75% DISCOUNT

Using Return Statement

The function will stop executing when it reaches a return statement. If JavaScript function was invoked from a statement, JavaScript will return to execute the code after the invoking statement.

JavaScript functions often compute a return value which is returned back to the caller:

Example Copy

function learnFunction(x, z) {
    return x * z;
}

Try it LiveLearn on Udacity

 

Why Use Functions?

The code which is defined can be reused many times: it is not a one-time thing. You can get different results by using different arguments with the same JavaScript functions.

For example, in the editor, you can see a function which transforms Fahrenheit degrees to Celsius. The function has already finished its work, but if you decide to change the value of Fahrenheit, you can reuse it:

Example Copy

function celsius(fah) {
    return (fah - 32) * (5 / 9);
}
document.getElementById("test").innerHTML = celsius(86);

Try it LiveLearn on Udacity

 

Now take a good look at the example below. You see the same code as previously, but the value of Celsius is not defined within the parentheses. Because of that, the function cannot work properly – no Fahrenheit value that the JavaScript function could transform to Celsius value is determined. For that reason, the browser displays the function definition instead of the value:

Example Copy

function celsius(fahr) {
    return (fahr - 32) * (5 / 9);
}
document.getElementById("demo").innerHTML = celsius(86);

Try it LiveLearn on Udacity

 

Note: JavaScript functions must have the value included to work properly.

Functions as Variables

JavaScript functions can be used in the same way as variables. This is extremely useful when values can change or some data should be stored inside:

Example Copy

document.getElementById("test").innerHTML =
"The weather temperature is " + celsius(86) + " Celsius";

function celsius(fahr) {
    return (5 / 9) * (fahr - 32);
}

Try it LiveLearn on Udacity

 

JavaScript Function: Summary

  • It is important to follow the proper syntax when creating JavaScript functions.
  • There are different ways you can invoke a JavaScript function. For more, refer to JavaScript Call a Function tutorial.
  • JavaScript functions can be reused.

 

 


 

 

 

It's nearly impossible not to encounter array when coding in JavaScript. In this tutorial, you will learn all about various JavaScript array methods.

You will understand how to convert string to array JavaScript code will use, or in other words, perform a data type conversion. We will also explain different ways to split arrays into smaller ones, remove items from different positions in the array, sort them, merge them, and much much more.

Contents

JavaScript Array Methods: Main Tips

  • The biggest advantage of arrays in JavaScript is the variety of their methods.
  • Array methods provide convenient ways to use arrays.
  • There are multiple methods to manipulate arrays and their data.

Most Common Methods

A complete list of JavaScript array functions can be found here. However, we will now talk about the ones that are used most commonly. Simple code examples will also be provided to help you get a better idea in each case.

toString() Method

The toString() method returns all the elements of an array as a string list:

Example Copy

var cars = ["Audi", "Mazda", "BMW", "Toyota"];
document.getElementById("text").innerHTML = cars.toString();
// output:  Audi, Mazda, BMW, Toyota

Try it LiveLearn on Udacity

 

join() Method

The join() method puts all the elements of the array into a string list. The difference from toString() method is that you can specify a separator (in our case, a dash – (" - ")):

Example Copy

var cars = ["Audi", "Mazda", "BMW", "Toyota"]; 
document.getElementById("text").innerHTML = cars.join(" - ");

// output: Audi - Mazda - BMW - Toyota

Try it LiveLearn on Udacity

 

pop() Method

JavaScript pop() method is used when you need to remove the last element of an array. It returns the removed item's value:

Example Copy

var cars = ["Audi", "Mazda", "BMW", "Toyota"]; 
cars.pop();

// New array:  Audi, Mazda, BMW

Try it LiveLearn on Udacity

 

push() Method

The push() method adds a new specified element to the end of an array. It returns a numeric value that is the length of the new array:

Example Copy

var cars = ["Audi", "Mazda", "BMW", "Toyota"];
car.push("new");

// New array: Audi, Mazda, BMW, Toyota, new

Try it LiveLearn on Udacity

 

shift() Method

This method, just like JavaScript pop() method, removes an element from an array.

The difference between these two is that shift() removes the first element. It is called shift because after removing the first element, it shifts all the other elements to a lower index:

Example Copy

var cars = ["Audi", "Mazda", "BMW", "Toyota"];  
cars.shift();             

// new array: Mazda, BMW, Toyota

Try it LiveLearn on Udacity

 

unshift() Method

The unshift() method adds a new element to the beginning of an array, and unshifts older elements. Then, it returns the new array length:

Example Copy

var cars = ["Audi", "Mazda", "BMW", "Toyota"]; 
cars.unshift("new");

// New array: new, Audi, Mazda, BMW, Toyota

Try it LiveLearn on Udacity

 

splice() Method

The splice() method can add and remove elements from an array.

The first parameter specifies the index where a new element should be inserted. The second specifies how many elements should JavaScript remove from array. The rest of the parameters set the values that will be added (this method can add multiple elements):

Example Copy

var cars = ["Audi", "Mazda", "BMW", "Toyota"];
cars.splice(2, 0, "new", "newer"); 

// new array: Audi, Mazda, new, newer, BMW, Toyota

Try it LiveLearn on Udacity

 

sort() Method

This method sorts an array alphabetically. You can learn more about all of the possibilities the sort() method presents in the JavaScript sorting arrays tutorial:

Example Copy

var cars = ["Audi", "Mazda", "BMW", "Toyota"];
cars.sort();             

// array: Audi, BMW, Mazda, Toyota

Try it LiveLearn on Udacity

 

reverse() Method

This method reverses the order of the elements in an array. It can be used when sorting an array – this way, it will be sorted in descending order:

Example Copy

var cars = ["Audi", "Mazda", "BMW", "Toyota"];   
cars.sort();             
cars.reverse();           

// array: Toyota, Mazda, BMW, Audi

Try it LiveLearn on Udacity

 

concat() Method

JavaScript concat() method joins two arrays and makes a new one. It can take any number of arguments:

Example Copy

var cars = ["Audi", "Mazda", "BMW", "Toyota"]; 
var people = ["Joe", "Leona"];  
var joined = cars.concat(people);      

// joined array: Audi, Mazda, BMW, Toyota, Joe, Leona

Try it LiveLearn on Udacity

 

slice() Method

This method cuts out a part of an array and makes a new one. It can take one or two arguments: the first one specifies an index where to start slicing, and the second one sets the end index of the slice. If the second argument is not specified, it will slice to the end of the array:

Example Copy

var cars = ["Audi", "Mazda", "BMW", "Toyota", "Suzuki"]; 
var myCars = cars.slice(1, 3);  

// myCars: Mazda, BMW

Try it LiveLearn on Udacity

 

valueof() Method

This method converts the value of the array to a primitive one. The primitive value of an array is a string by default, so by default this method does exactly the same thing as toString() method:

Example Copy

var cars = ["Audi", "Mazda", "BMW", "Toyota"]; 
document.getElementById("text").innerHTML = cars.valueOf();  

// output: Audi, Mazda, BMW, Toyota

Try it LiveLearn on Udacity

 

Udacity

Pros

  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features

Main Features

  • Nanodegree programs
  • Suitable for enterprises
  • Paid certificates of completion

EXCLUSIVE: 75% OFF

Udemy

Pros

  • Easy to navigate
  • No technical issues
  • Seems to care about its users

Main Features

  • Huge variety of courses
  • 30-day refund policy
  • Free certificates of completion

AS LOW AS 12.99$

Datacamp

Pros

  • Great user experience
  • Offers quality content
  • Very transparent with their pricing

Main Features

  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable

75% DISCOUNT

Changing Elements

All array elements are accessed by their index number. You can change any array element by setting a new value to them:

Example Copy

var cars = ["Audi", "Mazda", "BMW", "Toyota"]; 
cars[0] = "Opel";        

 //cars:  Opel, Mazda, BMW, Toyota

Try it LiveLearn on Udacity

 

You can easily append new item to the end of an array by using its length property:

Example Copy

var cars = ["Audi", "Mazda", "BMW", "Toyota"]; 
cars[cars.length] = "Opel";           

// cars:Audi, Mazda, BMW, Toyota, Opel

Try it LiveLearn on Udacity

 

Note: arrays start at 0. So, if you need to access the first element of an array, you must use 0 as an index.

Numeric Sort

The sort() function works only on strings by default.

Sorting words this way is convenient: "Apple" comes before "Cactus". However, it does not work correctly when sorting numbers: according to the method, "36" is bigger than "101", because the first character "3" is bigger than "1". This can be fixed by specifying a compare function as a sort() method's argument.

Example Copy

var numbers = [41, 102, 1, 8, 25, 10];  
numbers.sort((a, b) => { return a - b }); 

// numbers: 1, 8, 10, 25, 41, 102

Try it LiveLearn on Udacity

 

JavaScript Array Methods: Summary

  • Arrays have a lot of methods you can use to manipulate them and their content.
  • toString() and valueOf() are not methods unique to arrays. All JavaScript objects have these methods.
  • To make JavaScript remove from array properly, use JavaScript pop() or shift() methods.
  • To perform array concatenation, use JavaScript concat() method.

 

 

 

Each of the JavaScript data types has their own functionality, properties, and methods you need to be aware of. Differentiating each one is fundamental when starting out with JavaScript.

JavaScript strings store textual data. In this tutorial, you will learn all about JavaScript string methods and properties. You will understand how to manipulate textual data using them, how to make JavaScript concatenate strings, cut, append or prepend text, as well as get certain characters from a string.

Contents

JavaScript String Methods: Main Tips

  • String methods assist in using and modifying strings.
  • There is a large variety of string methods in JavaScript.
  • You must change the string to an array before accessing it as an array using array methods.

Searches in a String

There are often cases when you need to perform a specific search in your JavaScript string. Whether you need to look for an index or a string, there are functions that allow you to do just that. Let's take a look at their descriptions and examples.

indexOf() is used to bring back an index of the first instance of a set character or text in the text string:

Example Copy

var loc = "Lets find where 'place' occurs!";
var plc = loc.indexOf("place");

Try it LiveLearn on Udacity

 

Now, lastIndexOf() is used to bring back an index of the last instance of a set character or text in the text string:

Example Copy

var plc = "Please locate where 'place' occurs!";
var loc = plc.lastIndexOf("place");

Try it LiveLearn on Udacity

 

The two methods bring back -1 when no text is found. We already know that JavaScript starts calculating from 0. Therefore, the methods may take in an additional parameter as the starting index to start the inquiry.

To find the starting index of a defined value, search() is used:

Example Copy

var txt = "Let us find where 'place' starts!";
var loc = txt.search("place");

Try it LiveLearn on Udacity

 

Note: search() and indexOf() may appear the same, but indexOf() does not accept regular expressions, while search() takes only one start position argument.

Extracting String Parts

The methods listed below are used for extracting a piece of a string:

  • slice(start, end)
  • substring(start, end)
  • substr(start, length)

JavaScript slice() is used to extract a piece of string and return it as a new string. There are two parameters: a start position index and an end one. In the code below, you can see a part of a string being sliced from 7th to 13th position:

Example Copy

var txt = "BMW, Audi, Mercedes";
var ans = txt.slice(7, 13);

Try it LiveLearn on Udacity

 

When there is a negative value defined, the calculation is started from the end string location. In the code below, you can see a part of a string being sliced from -12th to -6th position:

Example Copy

var txt = "BMW, Audi, Mercedes";
var ans = txt.slice(-12, -6);

Try it LiveLearn on Udacity

 

This method slices the other part of a string if the second parameter is excluded:

Example Copy

var ans = txt.slice(7);

Try it LiveLearn on Udacity

 

It can be counted starting from the end:

Example Copy

var ans = txt.slice(-12);

Try it LiveLearn on Udacity

 

Note: IE 8 does not support negative values.

The JavaScript substring() method is different in one major way: it will not receive negative value indexes:

Example Copy

var txt = "BMW, Audi, Mercedes";
var ans = txt.substring(7, 13);

Try it LiveLearn on Udacity

 

Now, the substr() method has its own difference as well. The length is defined in the second value parameter, thus, it can't be negative.=:

Example Copy

var txt = "BMW, Audi, Mercedes";
var ans = txt.substr(7, 6);

Try it LiveLearn on Udacity

 

Speaking of the length of a JavaScript data string, you can use the length property to bring it back. See the example below:

Example Copy

var lng = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var x = lng.length;

Try it LiveLearn on Udacity

 

Extracting Characters

There are also two methods that you can use when you need to take any characters of a string safely:

  • charAt(position)
  • charCodeAt(position)

We use charAt JavaScript method to return a character at a specified index in text. We type the function name as charAt():

Example Copy

var txt = "HELLO WORLD";
txt.charAt(0); // returns H

Try it LiveLearn on Udacity

 

charCodeAt() is used to return a unicode of a character at a defined index location in a string:

Example Copy

var txt = "HELLO WORLD";
txt.charCodeAt(0); // returns 72

Try it LiveLearn on Udacity

 

Replacing String Content

Using replace() changes the defined value to another value:

Example Copy

txt = "I like to learn with bitdegree!";
var x = txt.replace("bitdegree", "bitdegree.org");

Try it LiveLearn on Udacity

 

By default, the replace() function replaces only the first match:

Example Copy

txt = "I like to learn with bitdegree. I like to learn with bitdegree.";
var x = txt.replace("bitdegree", "bitdegree.org");

Try it LiveLearn on Udacity

 

The /g is used to switch out all matched up strings:

Example Copy

txt = "I like to learn. I like to learn with bitdegree.";
var x = txt.replace(/bitdegree/g, "bitdegree.org");

Try it LiveLearn on Udacity

 

The replace() is case-sensitive so using capital letters will not make it work:

Example Copy

txt = "Lets visit bitdegree!";
var x = txt.replace("BITDEGREE", "bitdegree.org");

Try it LiveLearn on Udacity

 

/i is used to solve this problem:

Example Copy

txt = "Let's visit bitdegree!";
var x = txt.replace(/bitdegree/i, "bitdegree.org");

Try it LiveLearn on Udacity

 

Udacity

Pros

  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features

Main Features

  • Nanodegree programs
  • Suitable for enterprises
  • Paid certificates of completion

EXCLUSIVE: 75% OFF

Udemy

Pros

  • Easy to navigate
  • No technical issues
  • Seems to care about its users

Main Features

  • Huge variety of courses
  • 30-day refund policy
  • Free certificates of completion

AS LOW AS 12.99$

Datacamp

Pros

  • Great user experience
  • Offers quality content
  • Very transparent with their pricing

Main Features

  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable

75% DISCOUNT

Converting Cases

In some cases, you might need to quickly convert the whole content of the string to a single case. For example, you might wish to accent something by putting it in all caps. There are functions in JavaScript designed to perform just that!

toUpperCase() method converts the text into uppercase:

Example Copy

var txt1 = "Hi World!";       // String
var txt2 = txt1.toUpperCase();  // txt2 is txt1 converted to upper

Try it LiveLearn on Udacity

 

toLowerCase() method converts the text into lowercase:

Example Copy

var txt1 = "Hi World!";       // String
var txt2 = txt1.toLowerCase();  // txt2 is txt1 converted to lower

Try it LiveLearn on Udacity

 

Joining Strings

Sometimes we need to join separate strings into one. This method is called JavaScript string concatenation, and it can be executed by using the conCat JavaScript function:

Example Copy

var txt1 = "Hi";
var txt2 = "World";
var txt3 = txt1.concat(" ", txt2);

Try it LiveLearn on Udacity

 

Besides being a JavaScript string concatenation method, concat() is sometimes used as a plus operator. Both lines match in functionality:

Example Copy

var txt = "hi" + " " + "World!";
var txt = "hi".concat(" ", "World!");

Try it LiveLearn on Udacity

 

Both of these methods will be returning a unique string. The primary string is not changed. That being said, strings can only be swapped out.

Converting a String to an Array

Sometimes to achieve the results we need we have to change the data type. JavaScript split() function is used to transform string to array JavaScript will use. When excluding the separator, the array will then store the full string in [0]:

Example Copy

var str = "x,y,z,g,t"; // String
str.split(","); // Split on commas
str.split(" "); // Split on spaces
str.split("|"); // Split on pipe

Try it LiveLearn on Udacity

 

If we use an empty string as a separator (""), the array is going to consist of single letter characters:

Example Copy

var str = "Hello"; // String
str.split(""); // Split in characters

Try it LiveLearn on Udacity

 

JavaScript String Methods: Summary

  • There are various string methods you can use to manipulate strings.
  • You can use string methods to JavaScript concatenate strings, split them, get indexes of characters and perform many other tasks.
  • You can also turn string to array JavaScript will recognize.

 

 

 

 

The JavaScript date functions manipulate time or retrieve information about it. This tutorial discusses the two categories of methods related to dates. Also, we explain how the JavaScript date object is created with the new Date() function. These date objects use a Unix Time Stamp.

You can always revisit our JavaScript date object and JavaScript date formats tutorials if needed. They're dedicated to JavaScript date object methods.

Contents

JavaScript Date: Main Tips

  • Date methods make JavaScript get time or date, or set them.
  • Date values can be expressed in years, months, days, hours, minutes, seconds or milliseconds.
  • There are two categories of date methods: get methods and set methods.
  • get methods return a part of a date.
  • set methods specify in what form the parts of the date will be returned.
  • By default, in computer languages, time is measured from January 1, 1970. That's called the Unix time.

get Methods

Date get methods return a part of the date you need. Take a look at the table to get a better idea:

MethodDescription
getDate()Get the current day as a number (from 1 to 31)
getFullYear()Get the current year as a four digit number
getMonth()Get the current month (0-11, 0 is January)
getDay()Get the current weekday as a number (0-6, 0 is Sunday)
getHours()Get the current hour (0-23)
getMilliseconds()Get the current milliseconds (0-999)
getSeconds()Get the current seconds (0-59)
getMinutes()Get the curent minutes (0-59)
getTime()Get the time in milliseconds (since January 1st, 1970)

getTime() Method

The method lets JavaScript get current time. It outputs the amount of milliseconds that have passed since January 1st, 1970:

Example Copy

var dt = new Date();
document.getElementById("dateOut").innerHTML = dt.getTime();

Try it LiveLearn on Udacity

 

getFullYear() Method

The method lets JavaScript get current date year in a four digit number:

Example Copy

var dt = new Date();
document.getElementById("dateOut").innerHTML = dt.getFullYear();

Try it LiveLearn on Udacity

 

getDay() Method

getDay() returns the weekday as a number:

Example Copy

var dt = new Date();
document.getElementById("dateOut").innerHTML = dt.getDay();

Try it LiveLearn on Udacity

 

Note: This method returns a number from 0 to 6 that indicates the current week day, 0 representing Sunday.

set Methods

You are familiar with the ways to get date JavaScript, but sometimes you need to set it. Let's review set methods that help us set a part of the date:

MethodDescription
setDate()Set the current day as a number (from 1 to 31)
setFullYear()Set the current year (you can also set the day and month)
setHours()Set the current hour (from 0 to 23)
setMilliseconds()Set the current milliseconds (from 0 to 999)
setMinutes()Set the curent minutes (from 0 to 59)
setMonth()Set the current month (from 0 to 11, 0 is January)
setSeconds()Set the current seconds (from 0 to 59)
setTime()Set the time in milliseconds

setFullYear() Method

The method sets the date to be a specified date. The example below sets the date to January 1st, 2018.

Example Copy

var dt = new Date();
dt.setFullYear(2018, 0, 1);
document.getElementById("dateOutput").innerHTML = dt;

Try it LiveLearn on Udacity

 

Note: just as weekdays, months are counted starting from 0. January is 0, December is 11.

setDate() Method

The method sets which day of the month it is (1-31).

Example Copy

var dt = new Date();
dt.setDate(14);
document.getElementById("dateOut").innerHTML = dt;

Try it LiveLearn on Udacity

 

Udacity

Pros

  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features

Main Features

  • Nanodegree programs
  • Suitable for enterprises
  • Paid certificates of completion

EXCLUSIVE: 75% OFF

Udemy

Pros

  • Easy to navigate
  • No technical issues
  • Seems to care about its users

Main Features

  • Huge variety of courses
  • 30-day refund policy
  • Free certificates of completion

AS LOW AS 12.99$

Datacamp

Pros

  • Great user experience
  • Offers quality content
  • Very transparent with their pricing

Main Features

  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable

75% DISCOUNT

Parsing Dates

There are different ways to make JavaScript get time or date. For example, Date.parse() method lets you parse a properly written date from a string and convert it to milliseconds:

Example Copy

var milSec = Date.parse("November 14, 1995");
document.getElementById("dateOut").innerHTML = milSec;

Try it LiveLearn on Udacity

 

You can perform a reverse action as well. Convert the milliseconds back and voila – you get the date JavaScript:

Example Copy

var milSec = Date.parse("November 14, 1995");
var dt = new Date(milSec);
document.getElementById("dateOut").innerHTML = dt;

Try it LiveLearn on Udacity

 

JavaScript Compare Dates

You can easily make JavaScript compare dates. The example below compares the date of today with November 14th, 1995:

Example Copy

var today, goodDay, textOut;
today = new Date();
goodDay = new Date();
goodDay.setFullYear(1995, 10, 14);

if (goodDay > today) {
    textOut= "Today is before November 14, 1995.";
} else {
    textOut= "Today is after November 14, 1995.";
}
document.getElementById("dateOut").innerHTML = textOut;

Try it LiveLearn on Udacity

 

UTC Date Methods

There is a time standard used in the whole world to regulate time and clocks. It's called the Coordinated Universal Time, abbreviated to UTC. Keep in mind daylight savings do not affect it in any way.

Naturally, UTC is also important in programming. In JavaScript, you can use special date methods to work with UTC:

MethodDescription
getUTCDate()Identical to getDate(), but returns the UTC date
getUTCDay()Identical to getDay(), but returns the UTC day
getUTCFullYear()Identical to getFullYear(), but returns the UTC year
getUTCHours()Identical to getHours(), but returns the UTC hour
getUTCMilliseconds()Identical to getMilliseconds(), but returns the UTC milliseconds
getUTCMinutes()Identical to getMinutes(), but returns the UTC minutes
getUTCMonth()Identical to getMonth(), but returns the UTC month
getUTCSeconds()Identical to getSeconds(), but returns the UTC seconds

JavaScript Date: Summary

  • You can use JavaScript date object methods to either set or get date values in years, months, days, hours, minutes, seconds or miliseconds.
  • get methods return a part of a date.
  • set methods specify the format of the date to be returned.
  • You can make JavaScript get date according to Coordinated Universal Time (UTC).

Previous TopicNext Topic

 

 

 

 

JavaScript timing events, or the JavaScript timer feature, defines a function and sets a specific time for its execution. You can also allow a continuous display of functions. Timing events are especially useful when you want to display popups.

This tutorial covers the JavaScript timing events, their types, and usage. You will also learn about the functions used to cancel them. Keep in mind that even though in the examples you'll mostly see JavaScript alert, you can use JavaScript timer events with other features as well.

Contents

JavaScript Timer: Main Tips

  • JavaScript allow executing code in specified time intervals. This functionality is called timing events.
  • You can cancel this functionality using clearTimeout() and clearInterval() functions.

Most Common Timer Functions

The variety of functions JavaScript offers is amazing. Using them, you can perform various tasks, thus providing your website with any functionality.

When we wish to execute timing events, we can also choose from a few methods that have different useful functions each. We will now discuss the most commonly used ones and review examples to illustrate each one.

setTimeOut()

This is probably the most common timing event method: it calls a function after a time you have specified passes.

Look at the example below. If you click a button, a JavaScript alert message will pop up after 2 seconds (2000 milliseconds):

Example Copy

<button onclick="setTimeout(showAlert, 2000)">Click me!</button>

Try it LiveLearn on Udacity

 

Udacity

Pros

  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features

Main Features

  • Nanodegree programs
  • Suitable for enterprises
  • Paid certificates of completion

EXCLUSIVE: 75% OFF

Udemy

Pros

  • Easy to navigate
  • No technical issues
  • Seems to care about its users

Main Features

  • Huge variety of courses
  • 30-day refund policy
  • Free certificates of completion

AS LOW AS 12.99$

Datacamp

Pros

  • Great user experience
  • Offers quality content
  • Very transparent with their pricing

Main Features

  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable

75% DISCOUNT

clearTimeOut()

This JavaScript timer function cancels the JavaScript setTimeout() function before it is executed.

In the example below, the setTimeout() function again calls a JavaScript alert to pop up after 2 seconds. However, if you call a clearTimeout() function before the seconds pass, it will be canceled:

Example Copy

<button onclick="myVar = setTimeout(showAlert, 2000)">Try it</button>

<button onclick="clearTimeout(myVar)">Stop it</button>

Try it LiveLearn on Udacity

 

setInterval()

This JavaScript timer function sets an interval in milliseconds when something should change. In the example below, the displayed time changes every 2 seconds:

Example Copy

var exampleVar = setInterval(exampleTimer, 2000);
function exampleTimer() {
   var d = new Date();
   document.getElementById("example").innerHTML = d.toLocaleTimeString();  
}

Try it LiveLearn on Udacity

 

clearInterval()

This JavaScript timer function clears the interval, stopping it from running:

Example Copy

var exampleVar = setInterval(exampleTimer, 0);
function exampleTimer() {
    var date = new Date();
    document.getElementById("example").innerHTML = date.toLocaleTimeString();
}

Try it LiveLearn on Udacity

 

JavaScript Timer: Summary

  • JavaScript timing events means running the code in defined time intervals.
  • You can use JavaScript setTimeOut() function to execute some functionality after a specified amount of time.
  • You can use setInterval() function to execute some functionality continuously with defined breaks inbetween.
  • You can cancel a setTimeOut() by calling clearTimeOut() function.
  • You can cancel a setInterval() by calling JavaScript clearInterval() function.
  • You can combine this functionality with other JavaScript features, like a JavaScript alert popup.

A JavaScript Cheat Sheet: A Reference Guide of Functions

https://www.bitdegree.org/learn/javascript-cheat-sheet

A

alertShows a modal window that has a specific message and an OK button.
array.lengthReturns the length of an array
array.mapInvokes a function for every element of an array (in order)
array.pushAdds elements to an array and declares a new length
array.sortSorts array elements in either alphabetic or ascending, and descending or ascending order

B

booleanReturns either true or false based on the specified statement or condition
break and continueBreak stops a loop from running. Continue skips an iteration of a loop

C

classNameSets or returns the name of a class of an HTML element
confirmDisplays a specified message in a dialog box, containing OK and CANCEL buttons

D

decodeURIComponentDecodes URI components
  

I

ifRuns code when a condition is met
indexOfSearches the array for a specified item, then returns its position
innerHTMLSets or returns the HTML content inside an element

M

MathPerforms mathematical calculations
Math.randomGenerates a random number from 0 (inclusive) up to but not including 1 (exclusive)

N

NumberConverts object arguments into numbers
number.toStringConverts a number to a string

O

onclickAn event that occurs when the user clicks on an element
onloadTranspires when an object is loaded

R

replaceSearches a string for a regular expression or a specified value and returns a string with replaced specified values
  

S

setAttributeAdds a specified attribute to an element, giving the attribute a certain value
setIntervalExecutes a specified function multiple times at set time intervals specified in milliseconds (1000ms = 1second)
setTimeoutCalls a function after the time specified in milliseconds (1000 ms = 1 second) has passed
sliceReturns selected elements of an array into a new array object
spliceAdds or removes items from an array
string.includesDetermines whether a string contains characters of a specified string or not
string.indexOfReturns the position of the first occurrence of a specified value inside a string variable
string.splitSplits a data string into a substrings array and returns the new array
style.displaySets or returns the display type of a specified element
submitSubmits an HTML form
substrExtracts parts of a string
substringExtracts the symbols between two indexes and returns a data string
switchExecutes actions for various conditions

F

forRuns a piece of code a set number of times
forEachApplies a specified function for every item in a particular array individually

L

location.reloadReloads the current web page
  

P

parseIntConverts a string to an integer
promptDisplays a dialog box, which would require a person to type in input

T

testLooks for a match inside a string variable
throw, try and catchThe try and catch block lets you set an error handling code: try defines a code of block that will be tested for errors, and catch defines a code of block that handles the error
toLowerCaseConverts all letters in a specified string lowercase
toUpperCaseConverts all letters in a specified string to uppercase

U

use strictSets JavaScript code to be executed in strict mode
  

W

whileExecutes a block of code as long as the defined condition is true
window.historyHolds information about internet browsers history
window.locationGets information about the current address (URL)
window.navigatorContains the information about the user's browser
window.screenHolds the information about the screen of the browser (for instance, the screen width and height)

https://css-tricks.com/complete-guide-to-css-functions/

Common CSS Functions

url()

.el {
  background: url(/images/image.jpg);
}
Using url()

attr()

/* <div data-example="foo"> */
div {
  content: attr(data-example);
}
Using attr()

calc()

.el {
  width: calc(100vw - 80px);
}
Using calc()

lang()

p:lang(en) {
  quotes: "\201C" "\201D" "\2018" "\2019" "\201C" "\201D" "\2018" "\2019";
}
Using lang()

:not()

h3:not(:first-child) {
  margin-top: 0;
}
Using :not()

CSS Custom Properties

There is only one function specific to CSS custom properties, but it makes the whole thing tick!

Thevar() function is used to reference a custom property declared earlier in the document.

html {
  --color: orange;
}

p {
  color: var(--color);
}

It is incredibly powerful when combined with calc().

html {
  --scale: 1.2;
  --size: 0.8rem;
}

.size-2 {
  font-size: calc(var(--size) * var(--scale));
}
.size-2 {
  font-size: calc(var(--size) * var(--scale) * var(--scale));
}
More about using var()

Color Functions

Another common place you see CSS functions is when working with color.

rgb() and rgba()

.el {
  color: rgb(255, 0, 0);
  color: rgba(255, 0, 0, 0.5);
  color: rgb(255 0 0 / 0.5);
}
Using rgb()

hsl() and hsla()

.el {
  background: hsl(100, 100%, 50%);
  background: hsla(100, 100%, 50%, 0.5);
  background: hsl(100 100% 50% / 0.5);
}
More about using hsl()

New Color Functions

In the upcoming CSS Color Module Level 4 spec, we can ignore the a portion of rgba() and hsla(), as well as the commas. Now, spaces are used to separate the rgb and hsl arguments, with an optional / to indicate an alpha level.

We’ll also start seeing new functions like lab() and lch() that will use this new format

Pseudo Class Selector Functions

These selectors use specialized argument notation that specifies patterns of what to select. This allows you to do things like select every other element, every fifth element, every third element after the seventh element, etc.

Pseudo class selectors are incredibly versatile, yet often overlooked and under-appreciated. Many times, a thoughtful application of a few of these selectors can do the work of one or more node packages.

:nth-child()

.el:nth-child(3n) {
  background-color: #eee;
}

nth-child() allows you to target one or more of the elements present in a group of elements that are on the same level in the Document Object Model (DOM) tree.

img

In the right hands, :nth-child() is incredibly powerful. You can even solve fizzbuzz with it! If you’re looking for a good way to get started, Chris has a collection useful pseudo selector recipes.

:nth-last-child()

.el:nth-last-child(2) {
  opacity: 0.75;
}
.el:last-child {
  opacity: 0.5;
}

This pseudo class selector targets elements in a group of one or more elements that are on the same level in the DOM. It starts counting from the last element in the group and works backwards through the list of available DOM nodes.

:nth-of-type()

h2:nth-of-type(odd) {
  text-indent: 3rem;
}

:nth-of-type() matches a specified collection of elements of a given type. For example, a declaration of img:nth-of-type(5) would target the fifth image on a page.

:nth-last-of-type()

section:nth-last-of-type(3) {
  background-color: darkorchid;
}

This pseudo class selector can target an element in a group of elements of a similar type. Much like :nth-last-child(), it starts counting from the last element in the group. Unlike :nth-last-child, it will skip elements that don’t apply as it works backwards.

Animation Functions

Animation is an important part of adding that certain je ne sais quoi to your website or web app. Just remember to put your users’ needs first and honor their animation preferences.

Creating animations also requires controlling the state of things over time, so functions are a natural fit for making that happen.

cubic-bezier()

.el {
  transition-timing-function: 
    cubic-bezier(0.17, 0.67, 0.83, 0.67);
}

Instead of keyword values like ease, ease-in-out, or linear, you can use cubic-bezier() to create a custom timing function for your animation. While you can read about the math that powers cubic beziers, I think it’s much more fun to play around with making one instead.

A custom cubic bezier curve created on cubic-bezier.com. There are also options to preview and compare your curve with CSS’s ease, linear, ease-in, ease-out, and ease-in-out transitions.Lea Verou’s cubic-bezier.com.

path()

.clip-me {
  clip-path: path('M0.5,1 C0.5,1,0,0.7,0,0.3 A0.25,0.25,1,1,1,0.5,0.3 A0.25,0.25,1,1,1,1,0.3 C1,0.7,0.5,1,0.5,1 Z');
}
.move-me {
  offset-path: path("M56.06,227 ...");
}

This function is paired with the offset-path property (or eventually, the clip-path property). It allows you to “draw” a SVG path that other elements can be animated to follow.

Both Michelle Barker and Dan Wilson have published excellent articles that go into more detail about this approach to animation.

steps()

.el {
  animation: 2s infinite alternate steps(10);
}

This relatively new function allows you to set the easing timing across an animation, which allows for a greater degree of control over what part of the animation occurs when. Dan Wilson has another excellent writeup of how it fits into the existing animation easing landscape.

Box title
JavaScript
What Is JavaScript Used For?
Tutorial
Introduction
Output
Syntax
Comment
Commands
Operators
Comparison and Logical Operators
Data Types
Type Conversion
Math.random()
Function Definitions
Events
Objects
Object Properties
Prototype
Array
Sorting Arrays
Strings
Numbers
Number Format
Math Object
Onclick Event
Date
Date Formats
Scope
Regular Expressions
Reserved Words
Common Mistakes
Performance
Forms
Form Validation
Window: The Browser Object Model
Popup Boxes
Cookies
JSON
AJAX Introduction
AJAX Form
Automatic File Download
JavaScript CheatSheets of Functions
Functions
Array Methods
String Methods
Date Methods
Timing Events
Cheat Sheet <
JavaScript and HTML
JavaScript in HTML
HTML DOM Methods
HTML DOM Changing HTML
HTML DOM Animation
HTML DOM EventListener
HTML DOM Navigation
HTML DOM NodeList
HTML DOM Element Nodes
JavaScript Syntax
Array Functions
Boolean
Calling a Function
Date Functions
Global Objects
Input Text
Operator
Statements
String Functions
Math
Math.random
Number
RegEx
alert
array.filter
array.length
array.map
array.reduce
array.push
array.sort
break and continue
className
confirm
decodeURIComponent
for
forEach
if
indexOf
innerHTML
location.reload
number.toString
onclick
onload
parseInt
prompt
replace
setAttribute
setInterval
setTimeout
slice
splice
string.includes
string.indexOf
string.split
style.display
submit
substr
substring
switch
test
throw, try and catch
toLowerCase
toUpperCase
use strict
while
window.history
window.location
window.navigator
window.screen
Scroll to Top