Introduction to JavaScript
JavaScript is a versatile, high-level programming language that is a core technology
of the World Wide Web, alongside HTML and CSS.
It is used to create interactive and dynamic web pages, enabling features such as
real-time updates, form validation, animations, and much more.
JavaScript is a client-side language, meaning it runs in the user's web browser, but it
can also be used on the server-side with environments like Node.js.
Key Features of JavaScript
1. Interactivity: JavaScript makes web pages interactive and dynamic. It allows
you to respond to user actions, such as clicks, mouse movements, and
keyboard input.
2. Client-Side and Server-Side: Originally designed for client-side (browser)
scripting, JavaScript is now also widely used on the server side with Node.js,
enabling full-stack development with a single language.
3. Object-Oriented: JavaScript supports object-oriented programming principles,
allowing for the creation of reusable objects and encapsulation of code.
Basic Syntax rules of JavaScript
The following rules apply to the basic syntax of JavaScript:
● JavaScript is case-sensitive.
● Statements should end in a semicolon (;).
● Variables:
● Must be defined before being used. The variable name
can contain A – Z, a – z, underscore or digits and must
start with a letter or an underscore (“_”).
● Assume the type of the data that is put into the variable.
The data type does not have to be explicitly defined
● Are global variables when defined outside of a function,
and are available anywhere in the current script context.
Variables created within a function are local variables,
and can be used only within that function.
● Strings have to be enclosed in quotation marks, either a single or
double. For example: print(”Hello ” + ‘world ‘+
Country.name) produces the following: Hello world US.
● To increment a variable, such as a = a + 1, you can use a++.
You can decrement a variable in the same way, as in a--.
● To enter comments in the script, use "//"(single line comment)
to start a single line comment or the combination of "/*" and "*/"
to enclose a multi-line comment.
JavaScript Statements
JavaScript statements are made of: Values, Operators, Keywords,
Expressions, and Comments. JavaScript statements are executed in the
same order as they are written, line by line.
Examples of JavaScript Statements
Semicolons
● Semicolons separate JavaScript statements.
● A semicolon marks the end of a statement in JavaScript.
Example:
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.
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:
function myFunction() {
console.log("Hello");
console.log("How are you?");
}
myFunction()
Output
Hello
How are you?
White Space
JavaScript ignores multiple white spaces.
Example:
console.log(10*2);
console.log(10 * 2);
Output
20
20
JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript
function many times to reuse the code.
Advantage of JavaScript function
There are mainly two advantages of JavaScript functions.
1. Code reusability: We can call a function several times so it save coding.
2. Less coding: It makes our program compact. We don’t need to write many
lines of code each time to perform a common task.
JavaScript Function Syntax
The syntax of declaring function is given below.
1. function functionName([arg1, arg2, ...argN]){
2. //code to be executed
3. }
JavaScript Functions can have 0 or more arguments.
JavaScript Function Example
Let’s see the simple example of function in JavaScript that does not has arguments.
<script>
function msg(){
alert("hello! this is message");
</script>
<input type="button" onclick="msg()" value="call function"/>
Test it Now
Output of the above example
Hello! this is message
JavaScript Function Arguments
We can call function by passing arguments. Let’s see the example of function that
has one argument.
<script>
function getcube(number){
alert(number*number*number);
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
Test it Now
Output of the above example
Click = 64
JavaScript Variable
JavaScript variable
JavaScript Local variable
JavaScript Global variable
A JavaScript variable is simply a name of storage location. There are two types of
variables in JavaScript : local variable and global variable.
Variables are used to store data in JavaScript.The values of the variables
are allocated using the assignment operator(“=”).
Example of JavaScript variable
Let’s see a simple example of JavaScript variable.
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
Test it Now
Output of the above example
30
JavaScript local variable
A JavaScript local variable is declared inside block or function. It is accessible within
the function or block only. For example:
<script>
function abc(){
var x=10;//local variable
</script>
JavaScript global variable
A JavaScript global variable is accessible from any function. A variable i.e. declared
outside the function or declared with window object is known as global variable. For
example:
<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
function b(){
document.writeln(data);
a();//calling JavaScript function
b();
</script>
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method).
For example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is an object-based language. Everything is an object in JavaScript.
JavaScript is template based not class based. Here, we don't create class to get the
object. But, we direct create objects.
Creating Objects in JavaScript
There are 3 ways to create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
1) JavaScript Object by object literal
The syntax of creating object using object literal is given below:
1. object={property1:value1,property2:value2.....propertyN:valueN}
As you can see, property and value is separated by : (colon).
Let’s see the simple example of creating object in JavaScript.
1. <script>
2. emp={id:102,name:"Shyam Kumar",salary:40000}
3. document.write(emp.id+" "+emp.name+" "+emp.salary);
4. </script>
Test it Now
Output of the above example
102 Shyam Kumar 40000
2) By creating instance of Object
The syntax of creating object directly is given below:
1. var objectname=new Object();
Here, new keyword is used to create object.
Let’s see the example of creating object directly.
1. <script>
2. var emp=new Object();
3. emp.id=101;
4. emp.name="Ravi Malik";
5. emp.salary=50000;
6. document.write(emp.id+" "+emp.name+" "+emp.salary);
7. </script>
Test it Now
Output of the above example
101 Ravi 50000
3) By using an Object constructor
Here, you need to create function with arguments. Each argument value can be
assigned in the current object by using this keyword.
The this keyword refers to the current object.
The example of creating object by object constructor is given below.
1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6. }
7. e=new emp(103,"Vimal Jaiswal",30000);
8.
9. document.write(e.id+" "+e.name+" "+e.salary);
10. </script>
Test it Now
Output of the above example
103 Vimal Jaiswal 30000
JavaScript If-else
The JavaScript if-else statement is used to execute the code whether condition is
true or false. There are three forms of if statement in JavaScript.
1. If Statement
2. If else statement
3. if else if statement
JavaScript If statement
It evaluates the content only if expression is true. The signature of JavaScript if
statement is given below.
if(expression){
//content to be evaluated
Flowchart of JavaScript If statement
Let’s see the simple example of if statement in javascript.
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
</script>
Test it Now
Output of the above example
value of a is greater than 10
JavaScript If...else Statement
It evaluates the content whether condition is true of false. The syntax of JavaScript
if-else statement is given below.
if(expression){
//content to be evaluated if condition is true
else{
//content to be evaluated if condition is false
Flowchart of JavaScript If...else statement
Let’s see the example of if-else statement in JavaScript to find out the even or odd
number.
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
else{
document.write("a is odd number");
</script>
Test it Now
Output of the above example
a is even number
JavaScript If...else if statement
It evaluates the content only if expression is true from several expressions. The
signature of JavaScript if else if statement is given below.
if(expression1){
//content to be evaluated if expression1 is true
else if(expression2){
//content to be evaluated if expression2 is true
else if(expression3){
//content to be evaluated if expression3 is true
else{
//content to be evaluated if no expression is true
}
Let’s see the simple example of if else if statement in javascript.
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
else if(a==15){
document.write("a is equal to 15");
else if(a==20){
document.write("a is equal to 20");
else{
document.write("a is not equal to 10, 15 or 20");
</script>
Test it Now
Output of the above example
a is equal to 20
JavaScript Loops
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 array.
There are four types of loops in JavaScript.
1. for loop
2. while loop
3. do-while loop
1) JavaScript For loop
The JavaScript for loop repeat the elements for the fixed number of times. It should
be used if number of iteration is known. The syntax of for loop is given below.
for (initialization; condition; increment)
code to be executed
Let’s see the simple example of for loop in javascript.
<script>
for (i=1; i<=5; i++)
document.write(i + "<br/>")
}
</script>
Test it Now
Output:
2) JavaScript while loop
The JavaScript while loop repeats the elements for the infinite number of times. It
should be used if number of repetition is not known. The syntax of while loop is
given below.
while (condition)
code to be executed
Let’s see the simple example of while loop in javascript.
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
</script>
Test it Now
Output:
11
12
13
14
15
3) JavaScript do while loop
The JavaScript do while loop repates the elements for the infinite number of times
like while loop. But, code is executed at least once whether condition is true or false.
The syntax of do while loop is given below.
do{
code to be executed
}while (condition);
Let’s see the simple example of do while loop in javascript.
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
Test it Now
Output:
21
22
23
24
25
JavaScript Comments
JavaScript comments are used to explain the code to make it more
readable. It can be used to prevent the execution of a section of code if
necessary. JavaScript comments are ignored while the compiler executes
the code.
Single Line Comments
A single-line comment in JavaScript is denoted by two forward slashes
(//),
Syntax:
// your comment here
Example 1: This example illustrates the single-line comment.
Javascript
// A single line comment
console.log("Hello Geeks!");
Output
Hello Geeks!
Multi-line Comments
A multiline comment in JavaScript is a way to include comments that span
multiple lines in the source code.
Syntax:
/*
This is a multiline comment
It can span multiple lines
*/
Example: This example illustrates the multi-line comment using /* … */
Javascript
/* It is multi line comment.
It will not be displayed upon
execution of this code */
console.log("Multiline comment in
javascript");
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands.
For example:
1. var sum=10+20;
Here, + is the arithmetic operator and = is the assignment operator.
There are following types of operators in JavaScript.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on the operands. The
following operators are known as JavaScript arithmetic operators.
Oper Description Example
ator
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
* Multiplication 10*20 = 200
/ Division 20/10 = 2
% Modulus 20%10 = 0
(Remainder)
++ Increment var a=10; a++; Now a = 11
-- Decrement var a=10; a--; Now a = 9
JavaScript Relational Operators
The JavaScript comparison operator compares the two operands. The comparison
operators are as follows:
Oper Description Example
ator
== Is equal to 10==20 =
false
=== Identical (equal and of same type) 10==20 =
false
!= Not equal to 10!=20 = true
!== Not Identical 20!==20 =
false
> Greater than 20>10 = true
>= Greater than or equal to 20>=10 = true
< Less than 20<10 = false
<= Less than or equal to 20<=10 =
false
JavaScript Bitwise Operators
The bitwise operators perform bitwise operations on operands. The bitwise
operators are as follows:
Ope Description Example
rato
r
& Bitwise AND (10==20 & 20==33) =
false
| Bitwise OR (10==20 | 20==33) = false
^ Bitwise XOR (10==20 ^ 20==33) =
false
~ Bitwise NOT (~10) = -10
<< Bitwise Left Shift (10<<2) = 40
>> Bitwise Right Shift (10>>2) = 2
JavaScript Logical Operators
The following operators are known as JavaScript logical operators.
Operat Descriptio Example
or n
&& Logical AND (10==20 && 20==33) = false
|| Logical OR (10==20 || 20==33) = false
! Logical Not !(10==20) = true
JavaScript Assignment Operators
The following operators are known as JavaScript assignment operators.
Oper Description Example
ator
= Assign 10+10 = 20
+= Add and assign var a=10; a+=20; Now a = 30
-= Subtract and var a=20; a-=10; Now a = 10
assign
*= Multiply and var a=10; a*=20; Now a = 200
assign
/= Divide and assign var a=10; a/=2; Now a = 5
%= Modulus and var a=10; a%=2; Now a = 0
assign
JavaScript Special Operators
The following operators are known as JavaScript special operators.
Operator Description
(?:) Conditional Operator returns value based on the condition. It is like if-else.
, Comma Operator allows multiple expressions to be evaluated as single
statement.
delete Delete Operator deletes a property from the object.
in In Operator checks if object has the given property
instanceof checks if the object is an instance of given type
new creates an instance (object)
typeof checks the type of object.
void it discards the expression's return value.
yield checks what is returned in a generator by the generator's iterator.
Javascript Data Types
JavaScript provides different data types to hold different types of values. There are
two types of data types in JavaScript.
1. Primitive data type
2. Non-primitive (reference) data type
JavaScript is a dynamic type language, means you don't need to specify type of the
variable because it is dynamically used by JavaScript engine. You need to use var
here to specify the data type. It can hold any type of values such as numbers, strings
etc. For example:
1. var a=40;//holding number
2. var b="Rahul";//holding string
JavaScript primitive data types
There are five types of primitive data types in JavaScript. They are as follows:
Data Description
Type
String represents sequence of characters e.g. "hello"
Number represents numeric values e.g. 100
Boolean represents boolean value either false or true
Undefined represents undefined value
Null represents null i.e. no value at all
JavaScript non-primitive data types
The non-primitive data types are as follows:
Data Description
Type
Object represents instance through which we can access members
Array represents group of similar values
RegExp represents regular expression
JavaScript String
The JavaScript string is an object that represents a sequence of characters.
There are 2 ways to create string in JavaScript
1. By string literal
2. By string object (using new keyword)
1) By string literal
The string literal is created using double quotes. The syntax of creating string using
string literal is given below:
1. var stringname="string value";
Let's see the simple example of creating string literal.
<script>
var str="This is string literal";
document.write(str);
</script>
Test it Now
Output:
This is string literal
2) By string object (using new keyword)
The syntax of creating string object using new keyword is given below:
1. var stringname=new String("string literal");
Here, new keyword is used to create instance of string.
Let's see the example of creating string in JavaScript by new keyword.
<script>
var stringname=new String("hello javascript string");
document.write(stringname);
</script>
Test it Now
Output:
hello javascript string
JavaScript String Methods
1) JavaScript String charAt(index) Method
The JavaScript String charAt() method returns the character at the given index.
1. <script>
2. var str="javascript";
3. document.write(str.charAt(2));
4. </script>
Test it Now
Output:
2) JavaScript String concat(str) Method
The JavaScript String concat(str) method concatenates or joins two strings.
1. <script>
2. var s1="javascript ";
3. var s2="concat example";
4. var s3=s1.concat(s2);
5. document.write(s3);
6. </script>
Test it Now
Output:
javascript concat example
3) JavaScript String indexOf(str) Method
The JavaScript String indexOf(str) method returns the index position of the given
string.
1. <script>
2. var s1="javascript from javatpoint indexof";
3. var n=s1.indexOf("f");
4. document.write(n);
5. </script>
Test it Now
Output:
11
4) JavaScript String toLowerCase() Method
The JavaScript String toLowerCase() method returns the given string in lowercase
letters.
1. <script>
2. var s1="JavaScript toLowerCase Example";
3. var s2=s1.toLowerCase();
4. document.write(s2);
5. </script>
Test it Now
Output:
javascript tolowercase example
5) JavaScript String toUpperCase() Method
The JavaScript String toUpperCase() method returns the given string in uppercase
letters.
<script>
var s1="JavaScript toUpperCase Example";
var s2=s1.toUpperCase();
document.write(s2);
</script>
Test it Now
Output:
JAVASCRIPT TOUPPERCASE EXAMPLE
Numeric arrays, specifically, are arrays that primarily contain numbers. Here's a
comprehensive guide to working with numeric arrays in JavaScript:
Creating a Numeric Array
You can create a numeric array using various methods:
Using Array Literal Syntax:
javascript
Copy code
let numbers = [1, 2, 3, 4, 5];
Using the Array Constructor:
javascript
Copy code
let numbers = new Array(1, 2, 3, 4, 5);
Creating an Empty Array and Adding Elements:
javascript
Copy code
let numbers = [];
numbers.push(1);
numbers.push(2, 3, 4, 5);
Accessing Elements in a Numeric Array
You can access elements using their index, which starts at 0:
javascript
Copy code
console.log(numbers[0]); // Output: 1
console.log(numbers[4]); // Output: 5