Javascript tutorial - Learn from scratch

Hello everyone, this JavaScript tutorial helps you learn the JavaScript programming language from scratch quickly and effectively. 


JavaScript is an open-source & most popular client-side scripting language fortified by all browsers. JavaScript is utilized mainly for enhancing the interaction of a utilizer with the webpage.JavaScript is not a compiled language, but it is a translated language. The JavaScript Translator (embedded in the browser) is responsible for translating the JavaScript code for the web browser.

There are many useful Javascript frameworks and libraries available: 

  • Angular
  • Node.js
  • React.js
  • jQuery
  • Vue.js
  • Ember.js
  • Ext.js
  • Webix
  • MobX
  • Omniscient
  • Anime.js
  • Chart.js
  • Cleave.js
  • Popper
  • Riot.js
  • Mithril
  • Socket
  • Polymer
It is really impossible to give a complete list of all the available Javascript frameworks and libraries.

We are going to learn the following javascript components

  1. JavaScript - Syntax
  2. JavaScript - Comments
  3. JavaScript - DataTypes
  4. JavaScript - Operators
  5. JavaScript - if--else
  6. JavaScript - switch
  7. JavaScript - Loop
  8. JavaScript - Function
  9. JavaScript - Object
  10. JavaScript - Array
  11. JavaScript - String
  12. JavaScript - Date
  13. JavaScript - Math
  14. JavaScript - Number
  15. JavaScript - Boolean
  16. JavaScript- this

1.JavaScript - Syntax

Basic Syntax:

<script>
document.write("Hello world");
</script>

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

// Variable declaration
var a, d, e;

// Assign value to the variable
a = 15;

2.JavaScript - Comments

Single line comment 

// This is a single-line comment.

Example of single-line comments

// This is a single line comment
alert("Single line comment");
//alert("Hello");

Multiple line comments 

In JavaScript multi-line comments start with /* and end with */. 

Example of multiple line comments

/* Multiple line comments start here
alert("Hello");
Multiple line comments end here*/
alert("JavaScript multipleline comments.");

3.JavaScript - DataTypes

Primitive Data Types 
  • String 
  • Number 
  • Boolean 
  • Null 
  • Undefined 

Non-primitive Data Type 
  • Object 
  • Date 
  • Array

4.JavaScript - String

The string is a primitive data type in JavaScript. A string is a textual content. It must be enclosed in single or double quotation marks.
The string value can be assigned to a variable using equal to (=) operator. Example: String literal assigned to a variable

var str1 = "Hello World";
var str2 = 'Greetings from KNF';

A string can also be treated like a zero-index based character array

var str = 'Greetings from KNF';

str[0] // G
str[1] // r
str[2] // e
str[3] // e
str[4] // t
str.length // 18 based character array.

The string is character index, it can be accessed using for loop and for-of loop.

var str = 'Greetings from KNF';

for(var i =0; i< str.length; i++)
console.log(str[i]);

for(var ch of str)
console.log(ch);


It can be concatenated using the plus (+) operator in JavaScript.

var str = 'Hello ' + "World " + 'from ' + 'Knowledgefactory ';

JavaScript allows you to create a String object using the new keyword, as shown below.

var str1 = new String();
str1 = 'Greetings from KNF';

// or

var str2 = new String('Greetings from KNF');
alert(str1)
alert(str2)

5.JavaScript - Number

Number type represents an integer, float, hexadecimal, octal or exponential value. The first character in a Number type must be an integer value and it must not be enclosed in quotation marks.

var int = 234;
var float = 210.45;
var hex = 0xfff;
var exponential = 1.56e3;
var octal = 040;

Number object JavaScript also provides Number objects which can be used with a new keyword. 

var hex = new Number(0xfff);

6.JavaScript - Boolean

The Boolean object represents two values, either "true" or "false".

Example: Boolean

var YES = true;

var NO = false;

Any type of comparison will return a Boolean result.

alert(5 > 9); // false

alert(11< 4); // false

alert(1 == 1); // true

alert(2>1); //true

JavaScript includes Boolean objects to represent true or false. It can be initialized using a new keyword.

var val = new Boolean(value);

7.JavaScript - Null

In JavaScript null is "nothing". It is supposed to be something that doesn't exist.

var user = {firstName:"Sibin", lastName:"Knf", age:90};
user = null; // Now value is null, but type is still an object

8.JavaScript - Undefined

We can also empty an object by setting it to undefined

var user = {firstName:"Sibin", lastName:"Knf", age:90};
user = undefined; // Now both value and type is undefined

9.JavaScript - Object

There are 3 ways to create objects. 
  • By object literal 
  • By creating an instance of Object directly (using the new keyword) 
  • By using an object constructor (using the new keyword)
The syntax of creating an object using object literal is given below:

object={property1:value1,property2:value2.....propertyN:valueN}

Let’s see the simple example of creating an object in JavaScript.

emp={id:12,name:"Sibin",salary:10000}
document.write(emp.id+" "+emp.name+" "+emp.salary);

The syntax of creating an object directly is given below:

var objectname=new Object();

Here, a new keyword is used to create an object.
Let’s see the example of creating an object directly.

<script>
var emp=new Object();
emp.id=345;
emp.name="Sibin KNF";
emp.salary=1000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

The example of creating an object by object constructor is given below. The 'this' keyword refers to the current object.

<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(213,"sibin knf",10000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>

10.JavaScript - Date

Date objects are created with the new Date( ) as shown below.
  • Date() 
  • Date(milliseconds) 
  • Date(dateString) 
  • Date(year, month, day, hours, minutes, seconds, milliseconds)
Example:

<script>
var d = new Date();
document.write( d.getFullYear());
document.write("<br>");
document.write( d.getMonth());
document.write("<br>");
document.write( d.getDate());
document.write("<br>");
document.write( d.getHours());
document.write("<br>");
document.write( d.getMinutes());
document.write("<br>");
document.write(d.getMilliseconds());
</script>

11.JavaScript - Array

The Array object lets you store multiple values in a single variable. It stores a fixed-size sequential accumulation of elements of the same type. An array is utilized to store a collection of data,  but it is often more useful to think of an array as a collection of variables of the same type.

Use the following syntax to create an Array object

var skills = new Array( "javascript", "java", "python" );

12.JavaScript - Operators

JavaScript includes the following categories of operators. 
  • Arithmetic Operators 
  • Comparison Operators 
  • Logical Operators 
  • Assignment Operators 
  • Conditional Operators
Arithmetic Operators

Addition (+) The addition operator takes two numerical operands and gives their numerical sum. It also concatenates two strings or numbers.

Syntax:
e + b

Subtraction (-) The subtraction operator gives the difference of two operands in the form of numerical value.

Syntax:
e - b

Multiplication (*) The multiplication operator gives the product of operands where one operand is a multiplicand and another is a multiplier.

Syntax:
e * b

Division (/) The division operator provides the quotient of its operands where the right operand is the divisor and the left operand is the dividend.

Syntax:
e / b

Modulus (%) The modulus operator returns the remainder left over when a dividend is divided by a divisor. The modulus operator is also known as a remainder operator. It takes the sign of the dividend.

Syntax:
e % b

Exponentiation (**) The exponentiation operator gives the result of raising the first operand to the power of the second operand. The exponentiation operator is right-associative.

Syntax:
e ** b

Increment (++) The increment operator increments (adds one to) its operand and returns a value.

Syntax:
x++ or ++x

Decrement (–) The decrement operator decrements (subtracts one from) its operand and returns a value.

Syntax:
x-- or --x

Unary (-) This is a unary operator i.e. it operates on a single operand. It gives the negation of an operand.

Syntax:
-x

Unary (+) This is a way to convert a non-number into a number.

Syntax:
+x

Comparison Operators

Comparison operators compare two values and give back a boolean value: either true or false. Comparison operators are used in decision making and loops.



Logical Operators

Logical operators perform logical operations: AND, OR, and NOT.



Assignment Operators



Conditional Operators

The conditional operator or ternary operator first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation.

?: (Conditional )
If Condition is true? Then value X: Otherwise value Y

13.JavaScript - if--else

JavaScript supports the following forms of if..else statement 
  • if statement
  • if...else statement 
  • if...else if... statement
if statement 

The if statement  allows JavaScript to make decisions and execute statements conditionally. 
Syntax The syntax for a basic if statement is as follows −

if (expression) {
Statement(s) to be executed if the expression is true
}

if...else statement

The 'if...else'  allows JavaScript to execute statements in a more controlled way. 
Syntax

if (expression) {
Statement(s) to be executed if the expression is true
} else {
Statement(s) to be executed if the expression is false
}

if...else if... statement 

The if...else if... statement is an advanced form of if…else that allows JavaScript to make a correct decision out of several conditions. 
Syntax


if (expression 1) {
Statement(s) to be executed if the expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if the expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if the expression 3 is true
} else {
Statement(s) to be executed if no the expression is true
}

14.JavaScript - switch

The objective of a switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression.
Syntax

switch (expression) {
case condition 1: statement(a)
break;
case condition 2: statement(b)
break;
...
case condition n: statement(c)
break;
default: statement(s)
}

15.JavaScript - Loop

The JavaScript loops are used to iterate the piece of code using for, while, do-while, or for-in loops. It makes the code compact. It is mostly used in an array.
There are four types of loops in JavaScript. 
  • for loop 
  • while loop 
  • do-while loop 
  • for-in loop
JavaScript For loop

Let’s see the simple example of for loop in javascript.

<script>
for (i=1; i<=10; i++)
{
document.write(i + "<br/>")
}
</script>

JavaScript while loop

Let’s see the simple example of while loop in javascript.

<script>
var i=1;
while (i<=10)
{
document.write(i + "<br/>");
i++;
}
</script>

JavaScript do while loop

Let’s see the simple example of a do-while loop in javascript.

<script>
var i=11;
do{
document.write(i + "<br/>");
i++;
}while (i<=20);
</script>
 
JavaScript for-in loop

Let’s see the simple example of the for-in loop in javascript.

<script>
const student = {
name: 'Sibin',
role: 'Developer',
age: 90
}

// using for...in
for ( let key in student ) {

// display the properties
document.write(`${key} => ${student[key]}`);
}
</script>

16.JavaScript - Function 

A JavaScript function is a block of code designed to perform a particular task.

Example


function myFunction(p1, p2) {
return p1 * p2; // The function returns the product of p1 and p2
}

The code inside the function will execute when "something" invokes (calls) the function: 
  • When an event occurs (when a user clicks a button) 
  • When it is invoked (called) from JavaScript code 
  • Automatically (self invoked)

17.JavaScript - this 

The JavaScript this keyword refers to the object it belongs to.
Look at the following example,

<script>
var myVar = 188;

function myFunction() {
var myVar = 123;

alert(myVar); // 123
alert(this.myVar); // 188
}

myFunction(); // inferred as window.myFunction()
</script>

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete