JavaScript History: JavaScript was invented by Brendan Eich in 1995.
It was developed for Netscape 2
The 15th edition, ECMAScript 2024, is published in July 2024.
Features:
JavaScript is a lightweight and interpreted language.
JavaScript can be used for Client-side developments as well as Server-
side developments
JavaScript contains a standard library of objects, like Array, Date, and Math, and a
core set of language elements like operators, control structures, and statements.
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 file 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.
<script>
// JavaScript Code
</script>
Why It is Interpreted Language?
An interpreted language is one that does not require compiling into machine language. It is
executed by an interpreter who reads the source code and converts it into a form that is directly
executed. The interpreter executes code line by line which makes JavaScript synchronous in
nature.
Static Vs Dynamic Websites:
A static website is one where web pages are delivered exactly as they are stored, with no real-time
content changes. In contrast, a dynamic website generates content in real time, typically using
databases and scripting languages to provide interactivity and personalized experiences.
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.
Advantages OF JavaScript:
Basic StructureOf HTML:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
/*body sections*/
</body>
</html>
The <script> Tag
In HTML, JavaScript code is inserted between <script> and </script> tags.
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
Meaning OF “document.getElementById(“demo”).innerHTML ="Hello JavaScript";
"finds" an HTML element (with id="demo"), and changes the element content
(innerHTML) to "Hello JavaScript":
What is innerHTML in JavaScript?
innerHTML is an HTML element property that has two uses for web developers:
1) You can use it to get the internal HTML content of any HTML element as an HTML string.
2) You can also use it to set or change elements’ innerHTML content.
Limitations of JavaScript
JavaScript has some limitations which are natural and unavoidable.
1. JavaScript works in the browser and having less communication with the
webserver. For this reason, it cannot handle some server tasks if it is required
to do in the browser.
2. JavaScript has not any method or way to create the graphic or picture. It can
manipulate the existing pictures.
3. Core JavaScript works somewhat differently in different browsers.
4. JavaScript is not used to read or write the files on client machines.
5. It does not support inheritance, public, private and protected terms hence do
not follow the object-oriented concept completely
Setting JavaScript in Firefox
Here are the steps to turn on or turn off JavaScript in Firefox:
1. Open a new tab → type about: config in the address bar.
2. Then you will find the warning dialog. Select i’ll be careful, i promise!
3. Then you will find the list of configure options in the browser.
4. in the search bar, type JavaScript enabled.
5. Now, you will find an option to enable or disable JavaScript by rightclicking
on the value of that option → select toggle. If JavaScript enabled
is true; it converts to false by clicking toggle. If JavaScript is disabled; it
gets enabled by clicking toggle.
Setting JavaScript in Chrome
Here are the steps to turn on or off JavaScript in chrome:
1. click the chrome menu at the top right corner of your browser.
2. select Settings.
3. click Show advanced settings at the end of the page.
4. under the Privacy section, click the content settings button.
5. in the “JavaScript” section, select “do not allow any site to run JavaScript” or
“allow all sites to run JavaScript (recommended)”
Basic Structure of JavaScript program
<!DOCTYPE>
<html>
<head><title></title></head>
<body >
<script type="text/javascript">
Add javascript code here
</script>
</body>
</html>
Case Sensitivity: JavaScript is case sensitive i.e., upper case letter and lower-case
letter has differentmeaning. For example, the word “alert” has a lower case “a”. so, if
we type the wordwith an uppercase “a” then JavaScript will show an error and the
alert box will not be displayed.
Whitespace & Semi Colon: JavaScript ignores spaces, tabs, and newlines that
appear in JavaScript programs. You can use spaces, tabs, and newlines freely in
your program and you are free to format and indent the programs in a neat and
consistent way that makes the code easy to read and understand. The following code
could be written without semicolons.
Session 1: JavaScript Syntax :
1: Javascript Statement:
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.
2: Semicolon:
It marks the end of a statement in javascript. Semicolons separate JavaScript
statements.
3: JavaScript Programs
A computer program is a list of "instructions" to be "executed" by a computer.
In a programming language, these programming instructions are
called statements.
A JavaScript program is a list of programming statements.
4: JavaScript White Space
JavaScript ignores multiple spaces. You can add white space to your script to make it
more readable. The following lines are equivalent:
Example :
let person = "Hege";
let person="Hege";
5: JavaScript Line Length and Line Breaks
For best readability, programmers often like to avoid code lines longer than 80
characters.
If a JavaScript statement does not fit on one line, the best place to break it is
after an operator:
6: JavaScript Code Blocks
JavaScript statements can be grouped together in code blocks, inside curly
brackets {...}.
The purpose of code blocks is to define statements to be executed together.
Example:
7: JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action to
be performed. Our Reserved Words Reference lists all JavaScript keywords.
Note:
1: While let and const are block-scoped, var declarations are either globally scoped or
function-scoped.
2: Let variables can be updated but not re-declared, const variables cannot be updated
or re-declared, and var variables may both be updated and re-declared inside their
scope.
8: JavaScript Comments
JavaScript comments can be used to explain JavaScript code, and to make it more
readable. Comments are ignored, and will not be executed.
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).
Example:
Multi-line Comments
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored by JavaScript.
Example
JavaScript is Case Sensitive
All JavaScript identifiers are case sensitive.
Example: The variables lastName and lastname, are two different variables:
Output:
Section-1: Exercise Questions
Ques 1: Write a program to display a message which says “Did you enjoy learning Javascript
session?”by using getElementById() .
Solution:
Ques 2: Write a program to display which says “Welcome to the world of computing”by using
write() .
Solution:
Ques 3: Write a program to display your name, school and class teacher with an writeln
method.
Solution:
Ques 4: Write a program to add two number by using multiple line statement.
Ans:
Session 2: JavaScript Variable
1: Variables:
In programming, a variable is a container (storage area) to hold data. For Example, let
num = 5; Here, num is a variable. It's storing 5.
2: JavaScript Identifiers / Names
All JavaScript variables must be identified with unique names.These unique names
are called identifiers. Identifiers can be short names (like x and y) or more descriptive
names (age, sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
Names can contain letters, digits, underscores, and dollar signs.
Names must begin with a letter.
Names can also begin with $ and _ (but we will not use it in this tutorial).
Names are case sensitive (y and Y are different variables).
Reserved words (like JavaScript keywords) cannot be used as names.
JavaScript and Camel Case
Programmers have used different ways of joining multiple words into one variable
name:
Hyphens: first-name, last-name, master-card, inter-city.
Hyphens are not allowed in JavaScript. They are reserved for subtractions.
Underscore: first_name, last_name, master_card, inter_city
Upper Camel Case (Pascal Case): FirstName, LastName, MasterCard
Lower Camel Case: firstName, lastName, masterCard, interCity.
JavaScript var keyword:
The var is the oldest keyword to declare a variable in JavaScript.
Global scoped or function scoped
The scope of the var keyword is the global or function scope. It means variables
defined outside the function can be accessed globally, and variables defined inside a
particular function can be accessed within the function.
Example 1: Variable ‘a’ is declared globally. So, the scope of the variable ‘a’ is global,
and it can be accessible everywhere in the program. The output shown is in the
console.
Source code Output
var a = 10 10
function f() {
10
console.log(a)
}
f();
console.log(a);
Example 2: The variable ‘a’ is declared inside the function. If the user tries to access
it outside the function, it will display the error. Users can declare the 2 variables with
the same name using the var keyword. Also, the user can reassign the value into
the var variable. The output is shown in the console.
Source code Output
function f() { 10
var a = 10;
ReferenceError: a is not
console.log(a)
defined
}
f();
console.log(a);
Example 3: The user can re-declare the variable using var and the user can update
the var variable. The output is shown in the console.
Source code Output
var a = 10 7
var a = 8
a=7
Example 4: If users use the var variable before the declaration, it initializes with
the undefined value.
Source code Output
console.log(a); undefined
var a = 10;
JavaScript let keyword:
The let keyword is an improved version of the var keyword.
Block scoped:
The scope of a let variable is only block scoped. It can’t be accessible outside the
particular block ({block}). Let’s see the below example.
Example 1: The output is shown in the console.
Source code Output
let a = 10; 9
function f() {
10
let b = 9
console.log(b);
console.log(a);
}
f();
Variables are Containers for Storing Data
JavaScript Variables can be declared in 4 ways:
1: Automatically : If we are using undeclared variables. They are automatically
declared when first used:
Output:
2: Using var : var is the keyword that tells JavaScript you're declaring a variable. x is
the name of that variable. = is the operator that tells JavaScript a value is coming up
next. variables declared by the var keyword cannot be block-scoped.
Output:
3: Using let : JavaScript let is a keyword used to declare variables in JavaScript that
are block scoped.
Block Scope: The variables which are declared inside the { } block are known as
block-scoped variables. variables declared by the var keyword cannot be block-
scoped.
Example:
<script>
{
let num=10;
// calling the function inside block
console.log (num)
}
// calling the function outside block throws a Error
console.log (num)
</script>
Output:
10
Uncaught ReferenceError: num is not defined
Global Scope: A global scope variable is a variable declared in the main body of the
source code, outside all functions.
Example:
let num=10;
console.log(num);
function fun(){
console.log(num);
}
fun(); // calling the function
Output:
10
10
Function Scope: A function scope variable is a variable declared inside a function and
cannot be accessed outside the function.
Example: Using const
Javascript Data Types
JavaScript provides different data types to hold different types of values. There are
two types of data types in JavaScript.
Primitive data type
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:
var a=40;//holding number
var b="Rahul";//holding string
JavaScript primitive data types : There are five types of primitive data types in
JavaScript. They are as follows:
Data Type Description
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
// Numbers:
let length = 16;
let weight = 7.5;
// Strings:
let color = "Yellow";
let lastName = "Johnson";
// Booleans
let x = true;
let y = false;
// Object:
const person = {firstName:"John", lastName:"Doe"};
// Array object:
const cars = ["Saab", "Volvo", "BMW"];
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
Q1: What is a variable?
Ans : Variables are containers for storing information. Creating a variable in JavaScript is called
"declaring" a variable: var carName; After the declaration, the variable is empty (it has no value).
Q2:State the key Differences between Local Variable and Global Variable?
Ans:
a) The local variable is declared inside a function, whereas the Global variable is declared outside
the function.
b) Local variables are created when the function has started execution and is lost when the
function terminates, on the other hand, a Global variable is created as execution starts and is
lost when the program ends.
c) The local variable doesn’t provide data sharing, whereas the Global variable provides data
sharing.
Q3: What is a constant variable?
Ans: The const declaration declares block-scoped local variables. The value of a constant can't be
changed through reassignment using the assignment operator.
Q4: What are undeclared and undefined variables?
Ans:
Undefined: It occurs when a variable has been declared but has not been assigned any value.
Undefined is not a keyword.
Undeclared: It occurs when we try to access any variable that is not initialized or declared earlier
using the var or const keyword.
JavaScript Operators- JavaScript operators are symbols that are used to perform operations on
operands. For example:
Example: var sum=10+20;
1: Arithmetic Operators- Arithmetic operators are used to perform arithmetic operations on the
operands. The following operators are known as JavaScript arithmetic operators.
Operator Description Example
+ 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
2: JavaScript Comparison Operators - The JavaScript comparison operator compares the two
operands. The comparison operators are as follows:
Operator Description Example
== 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
3: JavaScript Bitwise Operators - The bitwise operators perform bitwise operations on operands.
The bitwise operators are as follows:
Operator Description Example
& 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
>>> Bitwise Right Shift with Zero (10>>>2) = 2
4: JavaScript Logical Operators - The following operators are known as JavaScript logical
operators.
Operator Description Example
&& Logical AND (10==20 && 20==33) = false
|| Logical OR (10==20 || 20==33) = false
! Logical Not !(10==20) = true
5: JavaScript Assignment Operators - The following operators are known as JavaScript
assignment operators.
Operator Description Example
= Assign 10+10 = 20
+= Add and assign var a=10; a+=20; Now a = 30
-= Subtract and assign var a=20; a-=10; Now a = 10
*= Multiply and assign var a=10; a*=20; Now a = 200
/= Divide and assign var a=10; a/=2; Now a = 5
%= Modulus and assign var a=10; a%=2; Now a = 0
6: 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.
Operator Precedence and Associativity
When an expression contains numbers of operators and operand and the order of evaluations is
ambiguous then operator precedence and associative rules comes in
the picture.
Operator Precedence: It refers to the way in which the operator binds to its operand. It
determines the what operation is done first over the another. In precedence operator’s
hierarchy is formed and operator with highest precedence stood at the top.
Example, multiplication operator has the higher precedence than addition so multiplication bind
tightly than addition with operand.
Operator Associativity: It refers to the order in which an operator evaluates its operand i.e.
from left to right or right to left. When an expression has operator with equal precedence then
association normally is left to right.
Practice Questions
1: Name the type of operators listed below (assignment, relational, logical etc):
a) < b) ++ c) && d) ?:
2: Name the type of operators listed below (assignment, relational, logical etc):
a) ! b) == c) % d) =
3: Operators with higher precedence are evaluated before operators with relatively lower
precedence. Arrange the operators given below in order of higher precedence to lower
precedence.
(i) && (ii) % (iii) >= (iv) ++
Ans. (i) ++ (ii) % (iii) >= (iv) &&
4: Arrange the operators given below in order of higher precedence to lower precedence.
(i) () (ii) ?: (iii) == (iv) | |
Ans. (i) () (ii) == (iii) | | (iv) ?:
5: Arrange the operators given below in order of higher precedence to lower precedence.
(i) + (ii) && (iii) != (iv) ++
Ans. (i) ++ (ii) + (iii) != (iv) &&
6: What will be the output of the following. if x=5 initially?
(i) document.write(5 * ++x)
(ii) document.write(5 * x++)
Ans:
(i) 30
(ii) 25
7: What is the result stored in x, after evaluating the following expression?
var x = 5;
x = x++ * 2 + 3 * –x;
document.write(x)
Ans. x=-8
8: Give the output of this code
var a = 9;
a++;
document.write( (a);
a -= a – - – a;
document.write( (a);
Ans:
10
8
9: Evaluate the following expression: when a=10, b=8
i) ++a-b– ii) a%b++ iii) a*=b+5 iv) x=69>>>2
Ans
(i) 3 (ii) 2 (iii) 130 (iv) 17
10: If m=5 and n=2 output the values of m and n after execution in (i) and (ii).
(i) m -= n;
(ii) n = m + m/n;
Ans:
(i) the value of m is 3 and n is 2
(ii) The value of m is 5 and n is 7
11: What will be the output of the following code?
var k = 5, j = 9;
k += k++ – ++j + k;
document.write(“k=” +k);
document.write(“j=” +j);
Ans.
k= 6
j= 10
12: What is the value of y after evaluating the expression given below
y+=++y + y– + –y; when var y=8.
Ans. y=33
13: Give the output of the following expression: when a=7.
a+=a++ + ++a + –a + a–;
document.write(a)
Ans.
a=39
14: If int y=10 then find y and z after executing this statement:
int z=(++y * (y++ +5));
Ans. y=12 z=176
15: What will be the result stored in x after evaluating the following expression?
var x=4;
x += (x++) + (++x) + x;
Ans.
x=20
16: What is the value of y after evaluating the expression given below?
y += ++y + y– + –y; when int y = 8.
Ans:
y=8+9+9+7
y = 33
17: What is the value of x1 if x=5 ?
x1=++x – x++ + –x
Ans.
x1= ++x – x++ + –x
x1= 6 (x is incremented to 6) – 6 (x is incremented to 7) + 6 (x is decremented to 6)
=6
18: Give the output of the following expression :
a+=a++ + ++a + -–a + a-– ; when a = 7
Ans.
a+=a++ + ++a + –-a + a–- ;
a = 7 + (a++ + ++a + -–a + a–-);
a = 7 + (7 + 9 + 8 + 8);
a = 39
19: If int y = 10 then find int z = (++y * (y++ + 5));
Ans.
Increment operator has the highest precedence. So, ++y and y++ will be evaluated starting from left. In
++y, the value of y will be incremented to 11 and then 11 will be used in the expression.
When y++ is evaluated, the current value of y i.e. 11 will be used and then y will be incremented from 11
to 12.
var z = (++y * (y++ + 5));
= 11 * (11 + 5 )
= 11 * 16
= 176