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
FunctionsArray Methods
String Methods
Date Methods
Timing Events
Cheat Sheet <
JavaScript and HTML
JavaScript in HTMLHTML 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 FunctionsBoolean
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
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
- 1. JavaScript Function: Main Tips
- 2. What are Functions?
- 3. Basic Syntax
- 4. Function Invocation
- 5. Using Return Statement
- 6. Why Use Functions?
- 7. Functions as Variables
- 8. JavaScript Function: Summary
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;
}
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).
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
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
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
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;
}
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);
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);
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);
}
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
- 1. JavaScript Array Methods: Main Tips
- 2. Most Common Methods
- 3. Changing Elements
- 4. Numeric Sort
- 5. JavaScript Array Methods: Summary
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
JavaScript Array Methods: Summary
- Arrays have a lot of methods you can use to manipulate them and their content.
toString()
andvalueOf()
are not methods unique to arrays. All JavaScript objects have these methods.- To make JavaScript remove from array properly, use JavaScript
pop()
orshift()
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
- 1. JavaScript String Methods: Main Tips
- 2. Searches in a String
- 3. Extracting String Parts
- 4. Replacing String Content
- 5. Converting Cases
- 6. Joining Strings
- 7. Converting a String to an Array
- 8. JavaScript String Methods: Summary
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");
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");
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");
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);
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);
This method slices the other part of a string if the second parameter is excluded:
Example Copy
var ans = txt.slice(7);
It can be counted starting from the end:
Example Copy
var ans = txt.slice(-12);
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);
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);
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;
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
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
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");
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");
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");
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");
/i
is used to solve this problem:
Example Copy
txt = "Let's visit bitdegree!";
var x = txt.replace(/bitdegree/i, "bitdegree.org");
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
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
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
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
toLowerCase()
method converts the text into lowercase:
Example Copy
var txt1 = "Hi World!"; // String
var txt2 = txt1.toLowerCase(); // txt2 is txt1 converted to lower
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);
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!");
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
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
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
- 1. JavaScript Date: Main Tips
- 2. get Methods
- 3. set Methods
- 4. Parsing Dates
- 5. JavaScript Compare Dates
- 6. UTC Date Methods
- 7. JavaScript Date: Summary
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 andset
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:
Method | Description |
---|---|
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();
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();
getDay() Method
getDay()
returns the weekday as a number:
Example Copy
var dt = new Date();
document.getElementById("dateOut").innerHTML = dt.getDay();
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:
Method | Description |
---|---|
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;
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;
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
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
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
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;
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;
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;
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:
Method | Description |
---|---|
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).
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
- 1. JavaScript Timer: Main Tips
- 2. Most Common Timer Functions
- 2.1. setTimeOut()
- 2.2. clearTimeOut()
- 2.3. setInterval()
- 2.4. clearInterval()
- 3. JavaScript Timer: Summary
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()
andclearInterval()
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>
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
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
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
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>
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();
}
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();
}
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 callingclearTimeOut()
function. - You can cancel a
setInterval()
by calling JavaScriptclearInterval()
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
alert | Shows a modal window that has a specific message and an OK button. |
---|---|
array.length | Returns the length of an array |
array.map | Invokes a function for every element of an array (in order) |
array.push | Adds elements to an array and declares a new length |
array.sort | Sorts array elements in either alphabetic or ascending, and descending or ascending order |
B
boolean | Returns either true or false based on the specified statement or condition |
---|---|
break and continue | Break stops a loop from running. Continue skips an iteration of a loop |
C
className | Sets or returns the name of a class of an HTML element |
---|---|
confirm | Displays a specified message in a dialog box, containing OK and CANCEL buttons |
D
decodeURIComponent | Decodes URI components |
---|---|
I
if | Runs code when a condition is met |
---|---|
indexOf | Searches the array for a specified item, then returns its position |
innerHTML | Sets or returns the HTML content inside an element |
M
Math | Performs mathematical calculations |
---|---|
Math.random | Generates a random number from 0 (inclusive) up to but not including 1 (exclusive) |
N
Number | Converts object arguments into numbers |
---|---|
number.toString | Converts a number to a string |
O
onclick | An event that occurs when the user clicks on an element |
---|---|
onload | Transpires when an object is loaded |
R
replace | Searches a string for a regular expression or a specified value and returns a string with replaced specified values |
---|---|
S
setAttribute | Adds a specified attribute to an element, giving the attribute a certain value |
---|---|
setInterval | Executes a specified function multiple times at set time intervals specified in milliseconds (1000ms = 1second) |
setTimeout | Calls a function after the time specified in milliseconds (1000 ms = 1 second) has passed |
slice | Returns selected elements of an array into a new array object |
splice | Adds or removes items from an array |
string.includes | Determines whether a string contains characters of a specified string or not |
string.indexOf | Returns the position of the first occurrence of a specified value inside a string variable |
string.split | Splits a data string into a substrings array and returns the new array |
style.display | Sets or returns the display type of a specified element |
submit | Submits an HTML form |
substr | Extracts parts of a string |
substring | Extracts the symbols between two indexes and returns a data string |
switch | Executes actions for various conditions |
F
for | Runs a piece of code a set number of times |
---|---|
forEach | Applies a specified function for every item in a particular array individually |
L
location.reload | Reloads the current web page |
---|---|
P
parseInt | Converts a string to an integer |
---|---|
prompt | Displays a dialog box, which would require a person to type in input |
T
test | Looks for a match inside a string variable |
---|---|
throw, try and catch | The 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 |
toLowerCase | Converts all letters in a specified string lowercase |
toUpperCase | Converts all letters in a specified string to uppercase |
U
use strict | Sets JavaScript code to be executed in strict mode |
---|---|
W
while | Executes a block of code as long as the defined condition is true |
---|---|
window.history | Holds information about internet browsers history |
window.location | Gets information about the current address (URL) |
window.navigator | Contains the information about the user's browser |
window.screen | Holds 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.
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.
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.
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
FunctionsArray Methods
String Methods
Date Methods
Timing Events
Cheat Sheet <
JavaScript and HTML
JavaScript in HTMLHTML 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 FunctionsBoolean
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