Categories
Tutorials

Learning JavaScript

JavaScript is one of the most popular programming languages that is used both on the client-side and server-side to make web pages more interactive. When writing programs in JavaScript, they are named “Scripts”. When we talk about web pages you can say:

  • HTML is the noun or skeleton of a webpage
  • CSS is the adjective i.e., adds skin to HTML skeleton
  • JavaScript is the verb i.e., brings HTML to action

JavaScript is used for:

  • For interactivity in web pages
  • Creating mobile and web applications using React, React native, Vue, Angular, Node.Js
  • For developing server applications and building web servers using Node.Js
  • For Game development

Why you should learn JavaScript?

  • JavaScript is one of the 3 languages (HTML/CSS/JS) all web developers must learn. It is a high-level programming language that all modern web browsers support. It is also one of the core technologies of the web, along with HTML and CSS that you may have learned previously.
  • These days web pages are not the only place where JavaScript is used. Many desktop and server programs use JavaScript now. Node.js is the best known. Some databases, like MongoDB and CouchDB, also use JavaScript as their programming language.

How to add JavaScript in Html Document?

Internal JavaScript

In HTML Document, JavaScript code is added between <script> and </script> tags.

  • HTML Document can contain any number of scripts.

Scripts can be placed in <head> or <body> or in both

Example

<script>
function tempFunction()
{
   document.getElementById("temp").innerHTML = "Welcome to Interns School";
}
</script>

External JavaScript

You can also write JavaScript code in a separate .js file(JavaScript File).

  • In the js file, code is not written within <script> tags.
  • External js file can be added to HTML Document by  putting  the name of the script file in the src (source) attribute of a <script> tag:
  • More than one js file can be added to a document by adding multiple script tags containing the js file’s reference.

External script reference can be placed in  <head> or <body>

Syntax of JavaScript

JavaScript can be implemented using JavaScript statements that are placed within the <script>… </script> HTML tags in a web page. You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it is normally recommended that you should keep it within the <head> tags.

The <script> tag alerts the browser program to start interpreting all the text between these tags as a script. A simple syntax of your JavaScript will appear as follows.

<script ...>
    JavaScript code
</script>

The script tag takes two important attributes:

  • Language − This attribute specifies what scripting language you are using. Typically, its value will be javascript.
  • Type − This attribute is what is now recommended to indicate the scripting language in use and its value should be set to “text/javascript”.

So your JavaScript segment will look like:

<script language="javascript" type="text/javascript">
   JavaScript code
</script>

Set of Rule for JavaScript

Set of rules to define how JavaScript programs are constructed.

Whitespaces

Spaces and line breaks can be added as you want to define clearance and indentation in your code. Whitespaces are not meaningful in JavaScript.

Case Sensitive

JavaScript variable names are case sensitive. This means that the language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.

So the identifiers variable_name and Variable_name will convey different meanings in JavaScript.

Similarly,  variable color and Color are two different variables.

Identifiers

An identifier is a name used to identify variables, keywords, functions, labels, and objects.

In JavaScript, the first letter of identifiers can be a letter, or an underscore (_), or a dollar sign ($).

Note: Numbers cannot be the first letter

Examples:

Temp
$temp
_temp
temp
TEMP
tem$p
temp2

Comments

Comments are used to explain code, and to make it more readable.

There are 2 ways you can comment out in JavaScript:

1. Single Line Comments: Single line comments start with //. Any text between // and the end of the line will be ignored by JavaScript (will not be executed). This example below uses a single-line comment before each code line:

2. Multi-line Comments: Multi-line comments start with /* and end with */. Any text between /* and */ will be ignored by JavaScript. This example below uses a multi-line comment (a comment block) to explain the code:

Example:

// Single line comment

/*
  It is used to comment
  More than 1 line.
*/

Semicolons

Ending lines with Semicolons is optional in JavaScript. They are by default added by JavaScript interpreter.

JavaScript Values

In JavaScript, there are two types of values:

  • Literals
  • Variables

Literals

Fixed values that are provided in source code are called literals and have types like numbers, strings, object or array literals, etc.

10.50 (Numbers or decimals)

“John” or ‘john’ (Strings)

true (boolean)

{Box shadow: 'red', box-shape: 'Rectangle'} (Object-properties)

let colors= ['Red',  ‘Green']; (Arrays)

Variables

Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container. Before you use a variable in a JavaScript program, you must declare it.

Variables are declared with the var, let and const keywords as follows:

<script type = "text/javascript">
var y = 6; 
let x = 6; 
const z = 6;
</script>

You can also declare multiple variables with the same keyword as follows:

<script type = "text/javascript">
var money, name; 
let x, y; 
</script>

Storing a value in a variable is called variable initialization. You can do variable initialization at the time of variable creation or at a later point in time when you need that variable.

For instance, you might create a variable named money and assign the value 2000.50 to it later. For another variable, you can assign a value at the time of initialization as follows.

<script type = "text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>

Note: Use the var keyword only for declaration or initialization, once for the life of any variable name in a document. You should not re-declare same variable twice.

The table below will show the difference between the different variable declaration types:

var let const
Can be redeclared Cannot be redeclared Cannot be redeclared
Can be initialized later Can be initialized later Must be initialized at the time of declaration
Don’t have Block Scope Have Block Scope Have Block Scope
Value can be reassigned Value can be reassigned Value cannot be reassigned but can be changed
Example
var y = 6; let x = 6; const z = 6;

Example:

// How to create variables:
var x;
let y;

// How to use variables:
x = 1;
y = 2;
let z = x + y;

Types

JavaScript variables don’t have any specific type associated with them i.e. a single variable can hold numeric and string data types depending on the value assigned to it.

There are 2 main kinds of types JavaScript:

  • Primitive types
  • Object Type

Primitive Types

Primitive Types are:

Boolean

Booleans can have 2 values: true and false

null

A special keyword denoting a null value.

Note: null is not the same as NULL or any other variant as JavaScript is a case-sensitive language

undefined

In JavaScript, a variable whose value is not defined is called as undefined (value and type both are undefined).

Example:

let a;
a = undefined;

Note: As shown above the value of a variable can be set to undefined, it will empty the variable.

Empty

Empty values are not related to undefined. An empty string has both a legal value and a type.

Example:

let fruit= "";    // The value is "", the type is "string"

Number

An Integer or decimal number.

Example:

let a= 4.5;
let length = 16;

BigInt

An integer with arbitrary precision. (e.g. 9007199254740992n)

Example:

const bigValue = BigInt(9007199254740991)

String

A series of characters representing a text value.

Example:

let a = “John”

Object Types

In JavaScript, objects are written with curly braces {}.

Object properties are written as name: value pairs, separated by commas.

Example:

const Employee= {Name:"John", Salary:10,000, age:50, eyeColor:"blue"};

Output

JavaScript can “display” data in different ways:

  • Writing into an HTML element, using innerHTML.
  • Writing into the HTML output using document.write().
  • Writing into an alert box, using window.alert().
  • Writing into the browser console, using console.log().

Expressions

An expression is a combination of values, variables, and operators that JavaScript engine can evaluate and return value. Computation of expression is called evaluation.

Primary Expressions

Example:

  • 0.02
  • ‘something’
  • false
  • this
  • undefined
  • j

Arithmetic Expressions

Those expressions that evaluate to a number.

Example:

  • 5 / 2
  • j–
  • i += 2
  • a * 4

Logical expressions

Expressions that involve logical operators and evaluate to a boolean value.

Example:

  • z && y
  • a || b
  • !x

String Expressions

Expressions that involve Strings along with operators and evaluate to a string value.

Example:

let a = 'I’ + ‘am' + 'John'

Operators

Operators are used to combine two or more expressions, generally converting them to complex expressions.

Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is called the operator. JavaScript supports the following types of operators.

  • Assignment Operators
  • Arithmetic Operators
  • Comparison Operators
  • Logical (or Relational) Operators
  • String Operator
  • Conditional (or ternary) Operators

We  will discuss these types of operators one by one:

Assignment operators

Assignment operators are used to assign values to JavaScript variables.  The following table contains commonly used Assignment operators:

Operator Usage Example
= Assigns value to variable let y = 10;
+= Adds a value to a variable. let a = 15;

a += 5;

-= Subtracts a value from a variable. let a = 15;

a -= 5;

*= Multiplies a variable. let a = 15;

a *= 5;

/= Divides a variable let a = 15;

a /= 5;

%= Assigns a remainder to a variable let a = 15;

a %= 6;

Other assignment operators are: <<=,>>=,>>>=,&=,^=,|= and **=

Arithmetic Operators

Arithmetic operators are used to perform arithmetic on numbers(JavaScript variables, expressions or literals). You must be familiar with following two terms:

  • Operators:  Defines the operation to be performed e.g. multiplication, addition etc.
  • Operands: Numbers in an arithmetic operation is performed

The following table contains commonly used Arithmetic operators:

Operator

Usage

Example

“+”

(Addition)

Adds numbers let x = 5;

let y = 2;

let z = x + y;

“-”

(Subtraction)

Subtracts Numbers let x = 5;

let y = 2;

let z = x – y;

“*”

(Multiplication)

Multiplies Numbers let x = 5;

let y = 2;

let z = x * y;

“/”

(Division)

Divides Numbers let x = 6;

let y = 2;

let z = x / y;

“%”

(Modulus)

Returns Reminder of division let x = 5;

let y = 2;

let z = x % y;

“**”

(Exponentiation)

Raises the first operand to the power of 2nd operand let x = 5;

let y = 2;

let z = x ** y;

“–”

(Decrement)

Decrements numbers let x = 4;

x–;

let y = x;

“++”

(Increment)

Increments numbers let x = 4;

x–;

let y = x;

Comparison operators

Comparison operators are used in logical statements for comparison (Equality or difference) between values or variables and upon evaluation return True or False. The following table contains commonly used Comparison operators:

Operator

Usage Example Returns

==

Equal to let x = 5;

x == 5

x == “5”

True

True

===

Equal value or Equal type let x = 5;

x === 5

x === “5”

True

False

!=

Not Equal to let x = 5;

x != 7

True

!==

Not Equal value or not Equal type let x = 5;

x !== 5

x !== “5”

False

True

>

Greater than let x = 5;

x > 7

False

<

Less than let x = 5;

x < 7

True

>=

Greater than or equal to let x = 5;

x >= 7

False

<= Less than or equal to

let x = 5;

x <= 7

True

Logical Operators

Logical operators are used in logical statements to determine logic between values or variables and upon evaluation return True or False. The following table contains commonly used Comparison operators:

Operator

Usage Example

Returns

&& AND

(Returns True if both expressions are True else return False)

let x = 7;

let y = 2;

(x < 9 && y > 1)

(x < 9 && y < 1)

True

False

|| OR

(Returns False if both expressions are false else return True)

let x = 7;

let y = 2;

(x == 2 || y == 3)

(x == 7 || y == 0)

False

True

! NOT

(Returns True if expression is false else return true)

let x = 7;

let y = 2;

!(x === y)

!(x > y)

True

False

String Operators

In JavaScript “+” and “+=” operators are used to add (concatenate) the strings.

Example

Output

let string1 = “Alia”;

let string2 = “Ahmed”;

let output = string1 + ” ” + string2 ;

Alia Ahmed

let string1 = “Alia “;

let string2 += “Ahmed”;

Alia Ahmed

let y = “10” + 5;

let z = “Hi” + 5;

(Note: Result of addition of string and number is string)

15

Hi5

Precedence of Operators

Precedence describes the order in which operations are performed in arithmetic expressions consisting of multiple operators.

Order of precedence of operators is

  1. () Expression in parentheses are executed first
  2. Multiplication (*), Division (/) , Modulus (%)
  3. Addition(+), Subtraction (-)
  4. Assignment (=)
  5. Operators having the same precedence are computed from left to right

Example:

let x = 100 + 50 - 3;

Output:

147

Conditionals

Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.

Hence, conditional operators are used when you want to perform different actions based on different decisions.

In JavaScript we have the following conditional statements:

  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to specify many alternative blocks of code to be executed

The following table shows conditional operators:

Operator

Usage

Examples

if Used to specify a block of code that should be executed if the condition is true else the if block will not be executed.

(Can be used alone)

if (5>2) { //  do something }
else Used to specify a block of code that should be executed if the condition in “if block” is false.

(As you know else cannot be used alone it must be followed by an if statement )

if (a == true)

{

//  do something

}

else

{

//  do something else

}

else if Used to specify a block of code with a new condition  that should be executed if the condition in “if block” is false.

(As you know else if cannot be used alone it must be followed by an if statement or an else if statement)

if (b == 10)

{

//  do something if condition is true

}

else if (b < 10)

{

//  do something if condition in if is false and this condition is true

}

else

{

//  do something if both of the above conditions i.e. in if and else if are false

}

switch Used to select one code block to be executed out of many.

(After the evaluation of expression in switch statement the resultant value is compared to every case and if there is a match that code block is executed. If none of the cases is matched then the default code block is executed.

Remember only one case is executed as after each case it breaks out of switch block )

switch(expression)

{

case x:

// code block

break;

case y:

// code block

break;

default:

// code block

}

Strings

JavaScript strings are sequences of zero or more characters that are used as containers to store and manipulate text.

Strings are written inside single ” or double quotes “”.

Example:

let fruit= "Apple";  // Double quotes
let fruit2= 'Apple';  // Single quotes

String-Length

You can calculate the length of the string by using the built-in length function.

Example:

let fruit= "Apple";
fruit.length;    // Will return 5
let string1= "";
string1.length;    // Will return 0 as it is an empty string

Escape Character

In order to include special characters in string  backslash (/) is used otherwise JavaScript will misunderstand these special characters. So, backslash is used to convert special characters to string characters.

Code Usage
\’ To include Single Quote ( ‘ )
\” To include Double Quotes ( ‘’ )
\\ To include backslash ( \ )

Note:
You can also use quotes inside the string without using backslash but they should be different than main surrounding quotes(if you want them to be displayed)

Example:

let string1= "She is 'Alia'"; //She is 'Alia'
let answer3 = 'She is "Alia"'; //She is "Alia"

String Templates

JavaScript Strings can also be defined by template literals. Template literals use (``) instead of quotes ("") to define a string.

Some properties of template literals are:

  •  Template literals allow you to include single and double quotes within strings without any restriction or modification.

Example:

let string1= `She's often called "Allie"`;
  • Major use of template literals is to define multiline strings easily (by just pressing enter key and a new line is created) without using escaping characters.

Example:

let string1=
`My habit
is to do
gardening
after I finish
my school work`;
  • Template literals allow String Interpolation : Automatic replacing of variables and expressions in string  with real values.

The syntax for String Interpolation is ${...}

Example-1 (Variable Substitution):

let name= "Alia";
let color = "Black";
let string1= `${name} favorite color is ${color}.`;

Example-2 (Expression Substitution):

let length= 5;
let width= 6;
let area= `Area: ${length * width}`;

Arrays

In JavaScript , Array can be used to store multiple values in a single variable and its values can be accessed by using index numbers.

Creating Empty Array

Empty array can be created by using 2 ways:

  • const array_name = [];
  • const array_name = Array();

Creating pre-filled Array

  • Pre-filled array can be created in following ways:
const colors = ["Red", "Blue", "Yellow"];

// another way of declaring pre-filled array
const colors = Array.of("Red", "Blue", "Yellow");
  • You can also also create an empty array and then add values.

Example:

const colors= [];
colors[0] = "Red";
colors[1] = "Blue";
colors[2] = "Yellow";
  • An array can contain values of different types:

Example:

const array1 = [7, 'Apple', ['dog', 'cat']]
  • An array can be created with keyword new:

Example

const colors = new Array("Red", "Blue", "Yellow");
  • You can initialize an array of specific size with a set of values

Example:

myArray(12).fill(0) //Create a zero filled array of size-12
  • 2D array can be created as:

Example:

const matrix = [
 [1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]
]
matrix[0][0] //1
matrix[2][1] //8

Accessing Array Elements

Array elements can be accessed by referring to index numbers. Array indexes start with ‘0’ .

Example:

const colors=["Red", "Blue", "Yellow"];
let element1 = colors[0]; // element = "Red"

Changing Array Elements

Array elements can be changed as:

const colors=["Red", "Blue", "Yellow"];
colors[1]= "Black"; 

//Now the array becomes ("Red", "Black", "Yellow")

Length Property

In order to get the length of the array, JavaScript provides a built-in length function.

Example:

const colors=["Red", "Blue", "Yellow"];
colors.length;  // Returns 3

Length property can also be used at various places and one of such is the example below where we use the length property to access the last index of an array:

colors[colors.length - 1]; // Returns "Yellow"

Adding Array Elements

Elements can be added to array by following ways:

// Adds a new element (Black) to colors
colors.push("Black");  

// Adds "Black" to colors
colors[colors.length] = "Black";  

// Adds "Orange" at start of colors
colors.unshift("Orange") 

Removing Array Elements

Elements can be removed from array by following ways:

  • const colors=[“Red”, “Blue”, “Yellow”];
  • colors.pop();  // Removes item from end of colors(i.e. Yellow)
  • colors.shift() // Removes item from start of colors(i.e. Red)

Merging Arrays

2 Arrays can be merged in  following ways:

Using concat:

const colors1=["Red", "Blue"];
const colors2=["Pink","Yellow"];
const allColors = colors1.concat(colors2) //["Red","Blue","Pink","Yellow"];

Using the spread operator (...)

const allColors =[...colors1,...colors2]//["Red","Blue","Pink","Yellow"];

Loops

Loops can execute a block of code a number of times. They are handy, if you want to run the same code over and over again, each time with a different value. JavaScript supports different kinds of loops:

  • for – loops through a block of code a number of times
  • for/in – loops through the properties of an object
  • for/of – loops through the values of an iterable object
  • while – loops through a block of code while a specified condition is true
  • do/while – also loops through a block of code while a specified condition is true

The following table shows the different kind of loops:

Loop Keyword

Usage & Syntax

Examples

for for (initialization; condition; increment/decrement)

{

// code block to be executed

}(Note:Statement 1 and 3 are optional so they can be omitted with a proper substitution instead of them)

(1) Simple Loop

let string= “”; for (let i = 0; i < 5; i++) { string+= “value of i is ” + i + “<br>”; }

(2) Iterating an array

const colors=[“Red”, “Blue”, “Yellow”]; let i = 0; let len = colors.length; let string= “”; for (; i < len; ) { string+= colors[i] + “<br>”; i++; }

for in for (key in object) {

// code block to be executed

}

(Note: It is used to loop through the properties of an object or array. Each iteration returns a key (x)and this key is used to access the value of the key)

const employee= {name:”John”, salary:100,000, age:28}; let string= “”; for (let z in employee) { string+= employee[z]; }
for of for (variable of iterable) {

// code block to be executed

}

Note: It is used to loop through the iterable objects (Arrays, Strings, Maps, NodeLists etc).In every next iteration, next property value is assigned to the variable.

let language = “Python”; let string= “”; for (let x of language) { string += x; }
while while (condition) {

// code block to be executed

}

(Note:

The code block is executed as long as condition is true )

let string= “”; while (i < 5) { string += “The value of i is ” + i; i++; }
do while do {

// code block to be executed

}while (condition);(Note:

Code block will be executed before checking if the condition is true, then the loop will be repeated as long as the condition is true.

Even if the condition is false , loop will be executed at least once. )

let string= “”; let i= 0; do { string += “The value of i is ” + i; i++; } while (i < 5);

Functions

A function is a block of code designed to perform a particular task which can be called anywhere in your program. This eliminates the need of writing the same code again and again. It helps programmers in writing modular codes. Functions allow a programmer to divide a big program into a number of small and manageable functions.

Like any other advanced programming language, JavaScript also supports all the features necessary to write modular code using functions.

Like functions in other programming languages, the syntax of JavaScript functions is almost similar.

Syntax

function functionName(parameter1, parameter2,..) {
  // code to be executed
}

Example:

let result = tempFunction(5, 7);   // Function is called, return value will end up in result
function tempFunction(a, b) {
	return a + b; // Function returns the addition of a and b
}
// The value in variable “result” will be 12

Function Definition

Before we use a function, we need to define it. The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces.

The basic syntax is shown below:

function functionname(parameter-list) { statements } 

Let say we want to define a helloWorld function which alerts Hello World. Here is how we will do it:

function helloWorld() {
   // alert is a function which outputs hello world in browser as a popup.
   alert("Hello World"); 
}

Calling a Function

To invoke a function somewhere later in the script, you would simply need to write the name of that function as shown in the following example:

<html>
   <head>   
      <script type="text/javascript">
         function sayHello() {
            document.write("Hello there!");
         }
      </script>
   </head>
   <body>
      <p>Click the following button to call the function</p>      
      <form>
         <input type = "button" onClick="sayHello()" value="Say Hello"/>
      </form>      
      <p>Use different text in write method and then try...</p>
   </body>
</html>

Function Parameters

Till now, we have seen functions without parameters. But there is a facility to pass different parameters while calling a function. These passed parameters can be captured inside the function and any manipulation can be done over those parameters. A function can take multiple parameters separated by comma.

We have modified our sayHello function here. Now it takes two parameters.

function sayHello(name, age) {
   document.write (name + " is " + age + " years old.");
}

The return Statement

In JavaScript, a function can have an optional return statement. This is required if you want to return a value from a function. This statement should be the last statement in a function.

For example, you can pass two numbers in a function and then you can expect the function to return their multiplication in your calling program. It defines a function that takes two parameters and concatenates them before returning the resultant in the calling program.

function concatenate(first, last) {
   var full;
   full = first + last;
   return full;
}

function secondFunction() { 
   var result;
   result = concatenate('Zara', 'Ali');
   document.write(result);
}

Arrow Functions

These functions were introduced in ES6. They allow you to write shorter function syntax.

Syntax

(parameter1,parameter2,..) => { //... }

// Arrow functions have no name

Note:

  • No parentheses are required if the function has only 1 parameter.
  • Arrow functions return value by default

Example without Parameter:

hello = () =>
{
   return "Hello World!";
}

Example With Parameter:

hello = (param1) => "Hello " + param1;