Javascript is a popular scripting language that many people around the world use. It is a powerful programming language that works well in many different contexts. You will learn everything there is to know about Javascript in this tutorial.
What is JS
Javascript is a scripting language for client-side and server-side (Nodejs).
Javascript is mainly used to enhance user interaction with the website. In other words, you can make your website more dynamic and interactive. In web applications, people often use JS to do special effects such as sliders, pop-ups, or form validations before sending data to the server, etc.
Javascript is not only limited to the framework of building web applications, but also widely used in application development, mobile games, or server applications.
How to use JS
There are many ways you can run JavaScript code, such as: Using the web browser’s console tab, Using Node.js, Use JS directly on HTML files.
In this tutorial, we will focus on introducing you to the third method, which is also the most commonly used. JavaScript was created to make Web pages interactive, which is why JavaScript and HTML are often used together. To write JS code directly on an HTML file, you would apply the following syntax:
<script type="text/javascript">
//javascript code here
</script>
Alternatively, you can create a JS script, save it with the extension “.js” and import it into an HTML file with the following syntax:
<script type="text/javascript"></script>
For example:
<script src="index.js"></script>
To check if our JavaScript code has run or not, we will press the shortcut ‘F12’, and select the tab Console on the browser to see the results.
Javascript Tutorial
JavaScript Arrays
Usually, a variable accepts only a single element value. So, if you want to declare or store multiple elements at once, JavaScript has Arrays that will do this. Understandably, Array is an object that can store multiple elements.
Declare arrays
Simple syntax for creating arrays includes:
1. Use the [ ] array character:
const IT_web = ['LearnShareIT', 'W3bschool'];
2. Use the new keyword
You can also create an array using the new Array() expression in JavaScript.
const IT_web = new Array("LearnShareIT", "
W3bschool
");
In addition, arrays also allow you to store arrays, functions, and other objects within it, for example:
const mix = [
{ID: 78},
[8, 1 , 2],
function func() { console.log('Programming')}
];
Element access
Each element in the array is assigned an index (starting from 0). To access any element in the array, you will work with indexes according to the syntax:
arr[index];
For example
const IT_web = ['LearnShareIT', 'W3bschool'];
console.log(IT_web[0]); // LearnShareIT
console.log(IT_web[1]); // W3bschool
To learn more about arrays, you can follow in our detailed article about JS Arrays.
JavaScript Date
In JavaScript, dates and times are represented by the Date object. The Date object provides date and time information and other methods when working with Date.
Create a Date object
There are four ways to create a Date object.
- new Date().
- new Date(time – in milliseconds).
- new Date(a string of characters).
- new Date(year, month, day, hour, minute, second, millisecond).
Details of the declaration syntax of Date you can follow in this article: JS Date
Methods for working with time in JavaScript
Method | Description |
now() | Returns the numeric value corresponding to the current time. |
getFullYear() | Returns the year, corresponding to the local time |
getMonth() | Gets the number of months, from 0 to 11 in local time. |
getHours() | Gets the number of hours from 0 to 23, corresponding to the local time. |
getUTCDate() | Gets the day of the month (1–31) corresponding to the global time. |
setFullYear() | Sets the year value according to the local time. |
setMonth() | Sets the month value to the local time. |
setUTCDate() | Sets the day of the month in global time. |
Date format
Unlike other programming languages, JavaScript does not provide built-in functions for formatting dates. However, we can format the time as we like in the example below.
For example:
const a = new Date();
const myDate = a.getDate();
const myMonth = a.getMonth();
const myYear = a.getFullYear();
let b = myDate + '/' + (myMonth + 1) + '/' + myYear;
console.log(b); // 17/10/2022
JavaScript Element
In fact, the data structure of a web page is represented as a tree. In it, each node will correspond to a DOM.
Each DOM node will have a nodeType property – which is an integer – to represent the node’s type, with the following value:
- document.ELEMENT_NODE (1) : common nodes like html, head, body, title, h1, p,…
- document.TEXT_NODE (3) : the text element on the web page
- document.COMMENT_NODE(8) : the comment element.
Each DOM node always contains lots of links to other DOM nodes.
Node.parentNode: points to the parent node of a node. If a node has no parent node (document), then parentNode is null.
For example, for each node p
and h1
, the parentNode is the body.
The top parent element includes: documentElement and body
On a tree node diagram, the top nodes will be direct as a document with the properties:
<html> = document.documentElement
document.documentElement is the top document node and also the node of the <html> tag.
<body> = document.body
Also, the <body> element – document.body. is also considered a popular DOM node.
<head> = document.head
The < head >
tags will be available as document.head.
However, document.body can also be null.
This happens when at runtime, the script cannot access an element that does not exist.
In particular, if a script is inside the <head>, then document.body is not available because the browser has not read it.
Node.childNodes: points to an object akin to an array, containing the children of a node.
For example, for node body, childNodes is a list with child nodes h1, p, p
.
Node.firstChild: points to the first child node of a node in childNodes.
For example, for node body, firstChild is h1
.
Node.lastChild: points to the last child node of a node in childNodes.
For example, for node body, lastChild is p
(2nd).
Node.previousSibling: points to the previous adjacent node (with the same parentNode).
For example, for node p (first), previousSibling is h1
.
Node.nextSibling: points to the next adjacent node (with the same parentNode).
For example, for node p
(1st), nextSibling is _p
_(2nd).
Learn more about JS Elements properties and methods in the articles JavaScript HTML DOM Elements
JavaScript Object
An object is a data type that allows for storing multiple sets of data.
Note: If you are familiar with other programming languages, objects in JavaScript are a little different. You won’t need to create classes to create objects.
The following is an example of an object in JavaScript.
const dev_staff = {
name: 'John',
ID:8
};
dev_staff is an object that stores values of data types such as string and numeric data.
Object declaration
Syntax:
const object_name = {
key 1: value 1,
key 2: value 2
}
Here, each member of an object is a key and value pair separated by commas and enclosed in curly braces {}.
Attributes of the object
In JavaScript, key and value pairs are called properties.
For example:
const dev_staff = {
name: 'John',
ID:8
};
Here, two key and value pairs with different data types are name: ‘John’ and ID:8, which are two properties of the dev_staff object.
Accessing an object’s properties
You can access the value of an attribute using its key.
1. Use the dot symbol
Syntax:
Name_object.key
For example:
const dev_staff = {
name: 'John',
ID:8
};
console.log(dev_staff.name); // John
2. Use brackets [ ]
The syntax of bracket notation.
Object_name["property_name"]
For example:
const dev_staff = {
name: 'John',
ID:8
};
console.log(dev_staff["name"]); // John
In JavaScript, an object can also contain a function.
JavaScript String
String data type in JavaScript is used to store text values.
Declare a string in javascript.
In JavaScript, string literals are created by enclosing them in double quotes, Backticks, or single quotes.
- Using Single quote: ‘Hello LearnShareIT’
- Using double quotes: “Hello LearnShareIT”
- Using Backticks: `Hello LearnShareIT`
For example:
let title = 'Hello';
let IT_web = "LearnShareIT";
let myresult = `${title} ${IT_web} !!`;
Single quotes, double quotes are practically the same thing and you can use either.
Backticks ‘` are often used when we need to include variables or expressions into a string. This is done by wrapping variables or expressions with the $ sign and curly braces {variable or expression} like the example above.
Accessing the characters of the string
You can access characters in a string in two ways.
1. See string literals like an array. We will use the index to access.
For example:
const IT_web = 'LearnShareIT';
console.log(IT_web[0]); // L
2. Another way is to use charAt() method.
const IT_web = 'LearnShareIT';
console.log(IT_web.charAt(0)); // L
JavaScript Variables
In programming, a variable is a storage area to hold data. Similarly, JavaScript also uses variables to store certain data.
Declare variables
To declare variables in JavaScript, you use the let keyword (the var keyword is obsolete and should not be used).
The syntax for declaring variables is as follows:
let <variable name>;
You can now assign a value to the variable “devName” using the assignment operator (=), for example:
let devName;
devNumber = "TiffDoan";
That is, the variable “devName” is linking to the memory with the value “TiffDoan”. And you can access the memory using the variable’s name as follows:
let devName = "TiffDoan";
console.log(devName); // The result displayed on the console is: "TiffDoan"
To declare multiple variables, you can use commas (,) to separate variables on the same line:
let devName = "TiffDoan",
job = "Programmer",
major = "IT";
JavaScript Variable Naming Rules
1. Variable names must start with a letter, either an underscore ‘_’ or a $ sign.
For example:
let myNumber = 10;
let _myNumber = 20;
let $myNumber = 30;
2. Variable names cannot start with a number.
For example:
let 1myNumber;
3. JavaScript is case sensitive. So two variables named a and A respectively are two different variables.
For example:
var dev;
var Dev;
4. Keywords in JavaScript cannot be set as variable names.
For example:
let new = 10;
Here, since new is a keyword, the variable declaration will throw an error.
Note:
In JavaScript, variable names are usually written in camelCase if it is a combination of different words, i.e., the first letter of the word after it will be capitalized. For example: numDev, nameDev.
JavaScript Number
In recent versions of JavaScript, there are two types of numbers:
- Floating Numbers: These are regular numbers in JavaScript that are stored in the IEEE-754 64-bit format. These are the numbers we are using most of the time, and we will talk about them in this tutorial.
- BigInt: represents an integer of arbitrary length.
Declare number
var name = value;
//or
var name = new Number(value);
For example:
//Declare an integer variable
var myNumber = 8;
// Declare the variable as a real number
var myNumber = 8.8;
//Declare an exponential variable
var myNumber = 1e6 // 1000000
Number() function
The Number() function is used to convert other data types to numeric data types.
Example: Convert data type to numeric data type.
let dev1 = '20';
let dev2 = false;
let devNumber = Number(dev1);
let myNumber = Number(dev2);
console.log(devNumber); // 20
console.log(myNumber); // 0
Operator ‘+’ used with numeric data type
Use the ‘+’ operator with numbers to sum numbers.
For example:
let myNumber = 40 + 3;
When using the ‘+’ operator with numbers and strings, it will perform the concatenation and return the string as a result.
Example: Using the + operator performs a concatenation between a numeric data type and a character string.
let myNumber = '40' + 3;
console.log(myNumber); // 403
When a numeric string is used with other mathematical operations, the numeric string is converted to a number.
For example:
let myNumber = '3' * 2;
let devNumber = '2' - 1;
console.log(myNumber); // 6
console.log(devNumber); // 1
JavaScript File
A JavaScript file is considered a document used to contain JavaScript code and is saved with the .js extension. JavaScript files can contain functions: open – close windows, commands to execute in web pages….
How to open .JS files
To open a .JS file double click (double click) on the file. Or right-click on the file and select Open. Some extension files need to install specialized software to open. In some cases, the .JS file is corrupted and needs to be fixed before it can be opened. Use the software/or tools below to open and fix the error file.
Software to open files .JS
Below is a list of software that can open, convert or edit user-contributed .JS files.
- Microsoft Visual Studio 2019
- Jetbrains IntelliJ IDEA
- Jetbrains IntelliJ IDEA
- ES-Computing EditPlus
- text editor
- Web browser
- Bare Bones BBEdit
- MacroMates TextMate
- File Viewer for Android
- FileViewer Plus
- Convert .JS files
The .JS file can be converted to another format to suit the intended use. Usually, the software that can open the file can convert it to another format.
Learn more about working with JavaScript files in the following articles:
- Import a JavaScript file into a TypeScript file
- Import Functions from another file using JavaScript
- Export all functions from a file in JavaScript
- Get the filename without the path using JavaScript
- How to import a JSON file in JavaScript (ES6 Modules)
JavaScript Maps
- How To Merge Maps In JavaScript
- Iterate over a Map in Reverse Order using JavaScript
- How to Filter a Map in JavaScript
Summary
The above are the basics when you start getting acquainted with JavaScript. Hope everyone can apply it in their program. Stay tuned for the next articles and stay up to date with the next articles on JavaScript programming on LearnShareIT!
Other Tutorial
- Get the Status Code of an Axios HTTP Error in JavaScript
- How to access the Value of a Promise in JavaScript
- Make includes() case insensitive in JavaScript
- Get the Stack Trace from an Error in JavaScript
- How to Toggle a Boolean in JavaScript
- How to use await outside of an async function in JavaScript
- Wait for a Promise to Resolve before Returning in JS
- How to check if type is Boolean using JavaScript
- How to export multiple Classes in JavaScript
- How To Stop A For Loop In JavaScript
- Solution To Check If A Value Is A Promise Using JavaScript
- Solution To Get The User’s Locale In The Browser Using JavaScript
- How to Check if a Function is Defined in JavaScript
- Convert Truthy or Falsy values to Boolean in JavaScript
- Check if a Function returns True in JavaScript
- Check if Parameter is provided to Function in JavaScript
- Check if a URL is an Image using JavaScript
- Export a Function in JavaScript
- How to Check if a Function is Async in JavaScript
- Get Country name from Country code using JavaScript
- How to export Constants in JavaScript
- Import two classes with the same name in JavaScript
- Check if a URL is Localhost in JavaScript
Hi guys, wellcome to LearnShareIt. I’m Tiffany and I’m also who responsible for the quality of this website’s content. I previously worked on software development projects for ten years as a developer. Hopefully, our project will bring a lot of value to the community.
Job: Programmer/Project management
Major: IT
Programming Languages: Python, C, HTML, MySQL, SQL Server, C#, C++, Javascript, CSS, Java, VB