Javascript Tutorial – Excellence Technology

JavaScript Tutorial

JavaScript (JS) is the most popular lightweight, interpreted compiled programming language. It can be used for both Client-side as well as Server-side developments. It is also known as a scripting language for web pages. This free JavaScript Tutorial is designed to help both beginners and experienced professionals master the fundamentals of JavaScript and unleash their creativity to build powerful web applications. From basic syntax and data types to advanced topics such as object-oriented programming and DOM manipulation.

What is JavaScript ?

JavaScript is a lightweight, cross-platformsingle-threaded, and interpreted compiled programming language. It is also known as the scripting language for webpages. It is well-known for the development of web pages, and many non-browser environments also use it.

JavaScript is a weakly typed language (dynamically typed). JavaScript can be used for Client-side developments as well as Server-side developments. JavaScript is both an imperative and declarative type of language. JavaScript contains a standard library of objects, like ArrayDate, and Math, and a core set of language elements like operatorscontrol structures, and statements

  • Client-side: It supplies objects to control a browser and its Document Object Model (DOM). Like if client-side extensions allow an application to place elements on an HTML form and respond to user events such as mouse clicksform input, and page navigation. Useful libraries for the client side are AngularJSReactJSVueJS, and so many others.
  • Server-side: It supplies objects relevant to running JavaScript on a server. For if the server-side extensions allow an application to communicate with a database, and provide continuity of information from one invocation to another of the application, or perform file manipulations on a server. The useful framework which is the most famous these days is node.js.
  • Imperative language – In this type of language we are mostly concerned about how it is to be done. It simply controls the flow of computation. The procedural programming approach, object, oriented approach comes under this as async await we are thinking about what is to be done further after the async call.
  • Declarative programming – In this type of language we are concerned about how it is to be done, basically here logical computation requires. Her main goal is to describe the desired result without direct dictation on how to get it as the arrow function does.

How to Link JavaScript File in HTML ?

JavaScript can be added to HTML file in two ways:

  • Internal JS: We can add JavaScript directly to our HTML file by writing the code inside the <script> tag. The <script> tag can either be placed inside the <head> or the <body> tag according to the requirement.
  • External JS: We can write JavaScript code in another files having an extension.js and then link this file inside the <head> tag of the HTML file in which we want to add this code.

Syntax:

<script>
// JavaScript Code
</script>

History of JavaScript

It was created in 1995 by Brendan Eich while he was an engineer at Netscape. It was originally going to be named LiveScript but was renamed. Unlike most programming languages, JavaScript language has no concept of input or output. It is designed to run as a scripting language in a host environment, and it is up to the host environment to provide mechanisms for communicating with the outside world. The most common host environment is the browser. 

Features of JavaScript

According to a recent survey conducted by Stack Overflow, JavaScript is the most popular language on earth. 
With advances in browser technology and JavaScript having moved into the server with Node.js and other frameworks, JavaScript is capable of so much more. Here are a few things that we can do with JavaScript: 

  • JavaScript was created in the first place for DOM manipulation. Earlier websites were mostly static, after JS was created dynamic Web sites were made.
  • Functions in JS are objects. They may have properties and methods just like other objects. They can be passed as arguments in other functions.
  • Can handle date and time.
  • Performs Form Validation although the forms are created using HTML.
  • No compiler is needed.

Applications of JavaScript

  1. Web Development: Adding interactivity and behavior to static sites JavaScript was invented to do this in 1995. By using AngularJS that can be achieved so easily.
  2. Web Applications: With technology, browsers have improved to the extent that a language was required to create robust web applications. When we explore a map in Google Maps then we only need to click and drag the mouse. All detailed view is just a click away, and this is possible only because of JavaScript. It uses Application Programming Interfaces(APIs) that provide extra power to the code. The Electron and React are helpful in this department.
  3. Server Applications: With the help of Node.js, JavaScript made its way from client to server and Node.js is the most powerful on the server side.
  4. Games: Not only in websites, but JavaScript also helps in creating games for leisure. The combination of JavaScript and HTML 5 makes JavaScript popular in game development as well. It provides the EaseJS library which provides solutions for working with rich graphics.
  5. Smartwatches: JavaScript is being used in all possible devices and applications. It provides a library PebbleJS which is used in smartwatch applications. This framework works for applications that require the Internet for their functioning.
  6. Art: Artists and designers can create whatever they want using JavaScript to draw on HTML 5 canvas, and make the sound more effective also can be used p5.js library.
  7. Machine Learning: This JavaScript ml5.js library can be used in web development by using machine learning.
  8. Mobile Applications: JavaScript can also be used to build an application for non-web contexts. The features and uses of JavaScript make it a powerful tool for creating mobile applications. This is a Framework for building web and mobile apps using JavaScript. Using React Native, we can build mobile applications for different operating systems. We do not require to write code for different systems. Write once use it anywhere!

Limitations of JavaScript

  1. Security risks: JavaScript can be used to fetch data using AJAX or by manipulating tags that load data such as <img>, <object>, <script>. These attacks are called cross-site script attacks. They inject JS that is not part of the site into the visitor’s browser thus fetching the details. 
  2. Performance: JavaScript does not provide the same level of performance as offered by many traditional languages as a complex program written in JavaScript would be comparatively slow. But as JavaScript is used to perform simple tasks in a browser, so performance is not considered a big restriction in its use.
  3. Complexity: To master a scripting language, programmers must have a thorough knowledge of all the programming concepts, core language objects, and client and server-side objects otherwise it would be difficult for them to write advanced scripts using JavaScript.
  4. Weak error handling and type checking facilities: It is a weakly typed language as there is no need to specify the data type of the variable. So wrong type checking is not performed by compile.

Why JavaScript is known as a lightweight programming language ?

JavaScript is considered lightweight due to the fact that it has low CPU usage, is easy to implement, and has a minimalist syntax. Minimalist syntax as in, has no data types. Everything is treated here as an object. It is very easy to learn because of its syntax similar to C++ and Java.

A lightweight language does not consume much of your CPU’s resources. It doesn’t put excess strain on your CPU or RAM. JavaScript runs in the browser even though it has complex paradigms and logic which means it uses fewer resources than other languages. For example, NodeJs, a variation of JavaScript not only performs faster computations but also uses fewer resources than its counterparts such as Dart or Java.

Additionally, when compared with other programming languages, it has fewer in-built libraries or frameworks, contributing as another reason for it being lightweight. However, this brings a drawback in that we need to incorporate external libraries and frameworks. 

JavaScript Versions

JavaScript is a modern scripting language that is popular worldwide among developers. It is a lightweight, interpreted compiled language that can be used on both client-side as well as the server side. It was invented in the year 1995 by Brendan Eich. Over the years the language has improved a lot and a lot of new features have been added which make the coding process even easier. This language became an ECMA standard in the year 1997.

How to Add JavaScript in HTML Document ?

In this article, we are going to learn how can we add JavaScript to an HTML document. JavasScript code is inserted between <script> and </script> tags when used in an HTML document. Scripts can be placed inside the body or the head section of an HTML page or inside both the head and body. We can also place JavaScript outside the HTML file which can be linked by specifying its source in the script tag.

These are the basic approaches for doing this:

 

Table of Content

  • Add JavaScript Code inside the Head Section
  • Add JavaScript Code inside Body Section
  • External JavaScript

Add JavaScript Code inside the Head Section

JavaScript code is placed inside the head section of an HTML page and uses the <script> element. Insert the <script> tag between the opening <head> and closing </head> tags, and place your JavaScript code inside. This ensures the script is loaded and executed when the page loads.

Add JavaScript Code inside Body Section

JavaScript Code is placed inside the body section of an HTML page and in this also we use <script> </script> tag inside and above the closing tag of </body>.

External JavaScript

JavaScript can also be used in external files. The file extension of the JavaScript file will be .js. To use an external script put the name of the script file in the src attribute of a script tag. External scripts cannot contain script tags.

Advantages of External JavaScript

  • Cached JavaScript files can speed up page loading.
  • It makes JavaScript and HTML easier to read and maintain.
  • It separates the HTML and JavaScript code.
  • It focuses on code reusability which is one JavaScript Code that can run in various HTML files.

External JavaScript References

We can reference an external script in three ways in javascript:

  • By using a full URL:
src = "https://www.geeksforgeek.org/js/script.js"
  • By using a file path:
src = "/js/script.js"
  • Without using any path:
src = "script.js"

 

JavaScript Syntax

JavaScript Syntax is used to define the set of rules to construct a JavaScript code. You need to follow all these so that you can work with JavaScript.

Syntax:

console.log("Basic Print method in JavaScript");

JavaScript syntax refers to the set of rules that determines how JavaScript programs are constructed:

// Variable declaration
let c, d, e;

// Assign value to the variable
c = 5;

// Computer value of variables
d = c;
e = c/d;

These are the features of JavaScript which have some predefined syntax:

Table of Content

JavaScript Variables

A JavaScript variable is the simple name of the storage location where data is stored. There are two types of variables in JavaScript which are listed below: 

  • Local variables: Declare a variable inside of a block or function.
  • Global variables: Declare a variable outside function or with a window object.

Example: This example shows the use of Javascript variables.

 
// Declare a variable and initialize it
// Global variable declaration
let Name = "Apple";
 
// Function definition
function MyFunction() {
 
    // Local variable declaration
    let num = 45;
 
    // Display the value of Global variable
    console.log(Name);
 
    // Display the value of local variable
    console.log(num);
}
 
// Function call
MyFunction();

Output: 

Apple
45

JavaScript Operators

JavaScript operators are symbols that are used to compute the value or in other words, we can perform operations on operands. Arithmetic operators ( +, -, *, / ) are used to compute the value, and Assignment operators ( =, +=, %= ) are used to assign the values to variables.

Example: This example shows the use of javascript operators.

 
// Variable Declarations
let x, y, sum;
 
// Assign value to the variables
x = 3;
y = 23;
 
// Use arithmetic operator to
// add two numbers
sum = x + y;
 
console.log(sum);

 

Output: 

26

JavaScript Expression

Expression is the combination of values, operators, and variables. It is used to compute the values.

Example: This example shows a JavaScript expression.

 
// Variable Declarations
let x, num, sum;
 
// Assign value to the variables
x = 20;
y = 30
 
// Expression to divide a number
num = x / 2;
 
// Expression to add two numbers
sum = x + y;
 
console.log(num + "<br>" + sum);

 

Output:

10
50

JavaScript Keyword

The keywords are the reserved words that have special meanings in JavaScript. 

// let is the keyword used to
// define the variable
let a, b;
// function is the keyword which tells
// the browser to create a function
function GFG(){};

JavaScript Comments

The comments are ignored by the JavaScript compiler. It increases the readability of code. It adds suggestions, Information, and warning of code. Anything written after double slashes // (single-line comment) or between /* and */ (multi-line comment) is treated as a comment and ignored by the JavaScript compiler.

Example: This example shows the use of javascript comments.

 
// Variable Declarations
let x, num, sum;
 
// Assign value to the variables
x = 20;
y = 30
 
/* Expression to add two numbers */
sum = x + y;
 
console.log(sum);

 

Output:

50

JavaScript Data Types

JavaScript provides different datatypes to hold different values on variables. JavaScript is a dynamic programming language, which means do not need to specify the type of variable. There are two types of data types in JavaScript. 

  • Primitive data type
  • Non-primitive (reference) data type
// It store string data type
let txt = "GeeksforGeeks";
// It store integer data type
let a = 5;
let b = 5;
// It store Boolean data type
(a == b )
// To check Strictly (i.e. Whether the datatypes
// of both variables are same) === is used
(a === b)---> returns true to the console

// It store array data type
let places= [“GFG”, “Computer”, “Hello”];
// It store object data (objects are
// represented in the below way mainly)
let Student = {
firstName:”Johnny”,
lastName:”Diaz”,
age:35,
mark:”blueEYE”}

JavaScript Functions

JavaScript functions are the blocks of code used to perform some particular operations. JavaScript function is executed when something calls it. It calls many times so the function is reusable.

Syntax: 

function functionName( par1, par2, ....., parn ) {  
// Function code
}

The JavaScript function can contain zero or more arguments.

Example: This example shows the use of Javascript functions.

 
// Function definition
function func() {
 
    // Declare a variable
    let num = 45;
 
    // Display the result
    console.log(num);
}
 
// Function call
func();

 

Output: 

45

JavaScript Statements

The programming instructions written in a program in a programming language are known as statements. The order of execution of Statements is the same as they are written.

Semicolons

  • Semicolons separate JavaScript statements.
  • A semicolon marks the end of a statement in JavaScript. 

Example: In this example, we have shown the use of Semicolons.

 
 
let a, b, c;
a = 2;
b = 3;
c = a + b;
console.log("The value of c is " + c + ".");
Output
The value of c is 5.

Multiple statements on one line are allowed if they are separated with a semicolon.

a=2;b=3;z=a+b;

Code Blocks

JavaScript statements can be grouped together inside curly brackets. Such groups are known as code blocks. The purpose of grouping is to define statements to be executed together. 

Example: In this example, we have shown Code Blocks. 

 
function myFunction() {
    console.log("Hello");
    console.log("How are you?");
}
myFunction()
 
Output
 
Hello
How are you?

White Space

JavaScript ignores multiple white spaces.

Example: In this example, we have shown that JavaScript ignores white spaces.

 
console.log(10 * 2);
console.log(10 * 2);
Output
20
20

Both the result will be the same

Line Length and Line Breaks

JavaScript code’s preferred line length by most programmers is up to 80 characters. The best place to break a code line in JavaScript, if it doesn’t fit, is after an operator

Example: In this example, we have shown Line Length and Line Breaks

document.getElementById("geek1").innerHTML =
"Hello Geek!";

Keywords

Keywords are reserved words and cannot be used as a variable name. A JavaScript keyword tells about what kind of operation it will perform. 

Some commonly used keywords are:

  • break and continue: break keyword is used to terminate a loop and continue is used to skip a particular iteration in a loop and move to the next iteration.
  • do…. while: In this, the statements written within the do block are executed till the condition in while is true.
  • for: It helps in executing a block of statements till the condition is true.
  • function: This keyword is used to declare a function.
  • return: This keyword is used to exit a function.
  • switch: This helps in executing a block of codes depending on different cases.
  • var, let, and const: These keywords are used to declare a variable in js. 

Variables and Datatypes in JavaScript

Understanding variables and data types in JavaScript will help you to write error-free code. In this article, we are going to learn what are Variables and Datatypes in JavaScript.

Variables

In JavaScript, variables are used to store and manage data. They are created using the varlet, or const keyword.

var:

Declares a variable. It has a function-scoped or globally-scoped behavior.

var x = 10;

Example: In this example, we will declare variables using var.

var a = "Hello Geeks"
var b = 10;
var c = 12;
var d = b + c;
 
console.log(a);
console.log(b);
console.log(c);
console.log(d);
Output
Hello Geeks
10
12
22

let:

Introduces block-scoped variables. It’s commonly used for variables that may change their value.

let y = "Hello";

Example: In this example, we will declare variables using let.

 
let a = "Hello learners"
let b = "joining";
let c = " 12";
let d = b + c;
 
console.log(a);
console.log(b);
console.log(c);
console.log(d);
 
Output
Hello learners
joining
 12
joining 12

const:

Declares variables that cannot be reassigned. It’s block-scoped as well.

const PI = 3.14;

Example: In this example, we will declare the variable using the const keyword.

 
const a = "Hello learners"
console.log(a);
 
const b = 400;
console.log(b);
 
const c = "12";
console.log(c);
// Can not change a value for a constant
//c = "new"
//console.log(c) will show error
 
Output
Hello learners
400
12

Data Types

JavaScript is a dynamically typed (also called loosely typed) scripting language. In JavaScript, variables can receive different data types over time. The latest ECMAScript standard defines eight data types Out of which seven data types are Primitive(predefined) and one complex or Non-Primitive.

Primitive Data Types

The predefined data types provided by JavaScript language are known as primitive data types. Primitive data types are also known as in-built data types.

  1. Number: JavaScript numbers are always stored in double-precision 64-bit binary format IEEE 754. Unlike other programming languages, you don’t need int, float, etc to declare different numeric values.
  2. String: JavaScript Strings are similar to sentences. They are made up of a list of characters, which is essentially just an “array of characters, like “Hello GeeksforGeeks” etc.
  3. Boolean: Represent a logical entity and can have two values: true or false.
  4. Null: This type has only one value that is null.
  5. Undefined: A variable that has not been assigned a value is undefined.
  6. Symbol: Symbols return unique identifiers that can be used to add unique property keys to an object that won’t collide with keys of any other code that might add to the object.
  7. BigInt: BigInt is a built-in object in JavaScript that provides a way to represent whole numbers larger than 253-1.

Non-Primitive Data Types

The data types that are derived from primitive data types of the JavaScript language are known as non-primitive data types. It is also known as derived data types or reference data types.

  • Object: It is the most important data type and forms the building blocks for modern JavaScript. We will learn about these data types in detail in further articles.