JavaScript Tutorial
Introduction to Scripting Language
A scripting language is a type of programming language that is mainly used to write small programs (scripts) that
automate tasks, control other software, or add functionality without the need for full compilation.
Key Features of Scripting Languages:
1. Interpreted (not compiled) – Code is executed line by line by an interpreter (e.g., Python, JavaScript).
2. Automation – Often used to automate repetitive tasks.
3. Embedded Use – Can be embedded inside other software (e.g., JavaScript inside web browsers).
4. Simpler Syntax – Usually easier to learn and write compared to full system programming languages like C++.
5. Platform Independent – Many scripting languages run across multiple operating systems without major
changes.
Examples of Scripting Languages:
Python: A versatile, general-purpose language popular for web development, data analysis, and machine learning.
JavaScript: The most widely used scripting language for client-side web development. It can also be used on the
server with [Link].
PHP: A server-side language frequently used for web development, powering websites like WordPress and
Facebook.
Ruby: A dynamic, object-oriented language known for its elegant syntax and use with the Ruby on Rails web
framework.
Bash: A command-line shell and scripting language for UNIX-like operating systems.
Perl: A language known for its powerful text processing capabilities, used in web development and system
administration.
VBScript: Developed by Microsoft for scripting Windows applications.
PowerShell: A task automation framework from Microsoft for system administration on Windows, macOS, and
Linux.
SQL: A fourth-generation language interpreted for managing data in databases.
In short: A scripting language is a lightweight programming language, usually interpreted, designed to automate
processes, control applications, or enhance functionality.
Scripting Language vs Programming Language
Feature Scripting Language Programming Language
Execution Interpreted (line by line) Compiled (converted into machine code)
Speed Slower (due to interpretation) Faster (directly executed by CPU)
Development Speed Fast, less code, simple syntax Slower, more code, strict syntax
Usage Automation, web apps, small tasks, prototyping System software, OS, high-performance apps
Platform Platform independent (needs interpreter) Platform dependent (may need recompilation)
Ease of Learning Easier to learn and use More complex and detailed
Examples Python, JavaScript, PHP, Bash, Ruby C, C++, Java, Go, Rust
Client-Side Scripting
Runs on the user’s browser (front-end).
Used to control how the webpage looks, behaves, and interacts with the user.
Reduces load on the server because execution happens on the client’s machine.
Requires a browser with scripting support.
Server-Side Scripting
Runs on the web server (back-end).
Processes user requests, communicates with databases, and sends results back to the client.
More secure because code is executed on the server (user can’t see the code).
Requires a web server with interpreter support.
Contents:
1. Introduction
2. JavaScript Basics → Variables, Data Types, Operators
3. Control Statements → if-else, loops
4. Functions
5. Objects & Arrays
6. DOM Manipulation
7. Events
8. ES6 Features → let, const, arrow functions, promises
9. Advanced Concepts → async/await, classes, modules
1. Introduction to JavaScript
JavaScript (JS) is a client-side scripting language mainly used to make web pages interactive and
dynamic.
It was created in 1995 by Brendan Eich at Netscape.
Runs directly in the browser (like Chrome, Firefox, Edge, Safari) also on the server (using [Link]).
It is one of the core technologies of the web along with HTML and CSS.
Why JavaScript?
HTML → Provides structure of a web page.
CSS → Provides style and design.
JavaScript → Provides interactivity and behavior.
What JavaScript Can Do?
Validate form input (e.g., check if email is entered).
Create interactive UI (sliders, dropdowns, popups).
Manipulate HTML & CSS dynamically (DOM manipulation).
Fetch data from servers (AJAX / Fetch API).
Create web apps, games, mobile apps, and even server-side apps.
How to run JavaScript?
There are 3 common ways:
1. Inside <script> tag in HTML.
<!DOCTYPE html>
<html>
<body>
<script>
[Link]("Hello, JavaScript!");
</script>
</body>
</html>
2. As an external file ([Link]):
[Link]
<!DOCTYPE html>
<html>
<body>
<script src="[Link]"></script>
</body>
</html>
[Link]
[Link]("Hello, JavaScript!");
3. Directly in the browser console (Right-click → Inspect → Console).
First JavaScript Program
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
</head>
<body>
<script>
// prints in the console.
[Link]("Welcome to JavaScript!");
// shows an alert box
alert("This is an alert box!");
// writes directly in the HTML document
[Link]("Hello from JS!");
</script>
</body>
</html>
[Link]() → prints in the console.
alert() → shows a popup alert.
[Link]() → writes directly on the webpage.
2. JavaScript Basics → Variables, Keywords, Data Types, Operators
Variables in JavaScript
A variable is like a container used to store data values.
Example: You can store a number, text, or object inside a variable.
Ways to Declare Variables
var → Variable can be re-declared & updated. A global scope variable.
let → cannot be re-declared but can be updated. A block scope variable.
const → Variable cannot be re-declared or updated. A block scope variable.
// Using var
var name = "Raj";
[Link](name); // Output: Raj
// Using let
let age = 24;
[Link](age); // Output: 24
// Using const
const country = "Nepal";
[Link](country); // Output: Nepal
Rules for Naming Variables
Can contain letters, digits, _ , $(but not space and other special symbols)
Must not start with a digit.
Case-sensitive (Name and name are different)
Use meaningful names (studentName not x)
Reserved words can’t be used.
Keywords in JavaScript
Keywords are reserved words in JavaScript that
have a special meaning and cannot be used as
variable names, function names, or identifiers
Data Types in JavaScript
A data type defines the kind of value a variable can hold — numbers, text, boolean, etc.
JavaScript is dynamically typed, meaning you don’t need to specify a type when declaring a variable — it’s
determined automatically.
JavaScript categorizes its data types into two main categories: primitive and non-primitive (or reference). Primitive
types are immutable and represent a single value, whereas non-primitive types are mutable and can hold collections of
data.
Checking data types
The typeof operator can check a variable's data type. For instance, typeof "hello" returns "string" ,
and typeof 42 returns "number" . Note that typeof null unexpectedly returns "object" due to a
historical issue.
a. Primitive Data Types
JavaScript has seven primitive data types:
1. String → Represents text data inside quotes.
let name = "Raj";
[Link](typeof name); // string
2. Number → Represents both integers and floating-point numbers, including special values like Infinity and NaN.
let age = 24;
let pi = 3.14;
[Link](typeof age); // number
3. Boolean → Represents logical values (true or false).
let isStudent = true;
[Link](typeof isStudent); // boolean
4. Undefined → variable declared but no value
let x;
[Link](typeof x); // undefined
5. Null → intentional empty value
let y = null;
[Link](typeof y); // object (special case)
6. Symbol → A unique, immutable value often used as an object key.
let id = Symbol("id");
[Link](typeof id); // symbol
7. BigInt → Handles very large integers.
let bigNo = 9007199254740991n;
[Link](typeof bigNo); // bigint
b. Non-Primitive Data Types
Non-primitive types store references to memory locations. These include:
1. Object: A collection of key-value pairs for complex data.
let person = { name: "Raj", age: 24 };
[Link](typeof person); // object
2. Array: An ordered collection of values (a type of object).
let fruits = ["apple", "banana", "mango"];
[Link](typeof fruits); // object (array is a special object)
3. Function: Reusable code blocks, also treated as objects in JavaScript.
function greet(name) {
//code to be executed
}
[Link](typeof greet); //function
✅ Mini Assignment (Practice)
1. Create variables of all primitive types and print their types using typeof.
2. Create an object with your name, age, and country.
3. Create an array of your 3 favorite subjects and print the first subject.
Operators in JS
An operator is a symbol that performs an operation on values or variables.
Example: let a = 10 + 5; // '+' is an operator
1. Arithmetic Operators
Used for mathematical calculations.
Operator Description Example Output
+ Addition 10 + 5 15
- Subtraction 10 - 5 5
* Multiplication 10 * 5 50
/ Division 10 / 5 2
% Modulus (remainder) 10 % 3 1
** Exponentiation 2 ** 3 8
++ Increment a++ Adds 1
-- Decrement a-- Subtracts 1
Example:
let a = 10, b = 3;
[Link](a + b); // 13
[Link](a - b); // 7
[Link](a * b); // 30
[Link](a / b); // 3.333..
[Link](a % b); // 1 (remainder)
[Link](a ** b); // 1000 (10^3)
[Link](++a ); // 11
[Link](--b); // 2
2. Assignment Operators
Used to assign values.
Operator Example Same As
= x = 5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
let num = 10;
num += 5; // num = 15
num -= 3; // num = 12
num *= 2; // num = 24
num /= 4; // num = 6
num **= 2; // num = 36
[Link](num);
3. Comparison Operators
Used to compare two values (returns true or false).
Operator Description Example Output
== Equal to 5 == "5" true
=== Strict equal (value + type) 5 === "5" false
!= Not equal 5 != 6 true
!== Strict not equal 5 !== "5" true
> Greater than 10 > 5 true
< Less than 10 < 5 false
>= Greater or equal 10 >= 10 true
<= Less or equal 10 <= 5 false
[Link](5 == "5"); // true (value only)
[Link](5 === "5"); // false (value + type)
[Link](5 != "5"); // false
[Link](5 !== "5"); // true
[Link](10 > 5); // true
[Link](10 <= 5); // false
4. Logical Operators
Operator Meaning Example Result
&& AND (a > 0 && b > 0) true if both true
|| OR (a > 0 || b > 0) true if one true
! NOT !(a > 0) reverses the result
let x = true, y = false;
[Link](x && y); // false (AND)
[Link](x || y); // true (OR)
[Link](!x); // false (NOT)
5. String Operators
The plus sign (+) is used to concatenate (join) strings.
Operator Description Example Result
+ Concatenation "Hello " + "World" "Hello World"
+= Add & assign text += "JS" append text
let firstName = "John";
let lastName = "Doe";
// Concatenation
let fullName = firstName + " " + lastName;
[Link](fullName); // John Doe
// Append
fullName += " Jr.";
[Link](fullName); // John Doe Jr.
6. Ternary/conditional Operator ( ?: )
Shortcut for if...else.
let age = 20;
let canVote = age >= 18 ? "Yes" : "No";
[Link](canVote); // Yes
Example 2: Nested ternary operator
let score = 85;
let grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "D";
[Link](grade); // B
Template Literals
Template literals are an easier way to create strings in JavaScript.
Syntax: `string text ${expression} string text`
• Use backticks (`), not single or double quotes.
• Inside ${}, you can write variables or even expressions.
let name = "Raj";
let age = 24;
[Link](`My name is ${name} and I am ${age} years old.`);// My name is Raj and I am 24
years old.
Example 2 – Expression Inside ${}
let num1 = 10;
let num2 = 5;
[Link](`The sum of ${num1} and ${num2} is ${num1 + num2}.`); // The sum of 10 and 5
is 15.
Example 3 – Inside Object
let user = { name: "Aarav", country: "Nepal" };
[Link](`User ${[Link]} is from ${[Link]}.`); // User Aarav is from Nepal.
✅ Mini Assignment (Practice)
1. Create two variables a and b with any numbers.
2. Perform all arithmetic and comparison operations and print results.
3. Join two strings with +.
4. Use a ternary operator to check if a number is positive or negative.
5. Use nested ternary to grade marks: (marks >= 90 → A+, marks >= 80 → A, marks >= 70 → B,
otherwise → Fail )
Type conversion and coercion
Type conversion means changing one data type into another.
There are two types:
1. Implicit Conversion (Type Coercion) → done automatically by JavaScript.
2. Explicit Conversion (Type Casting) → done manually by the programmer.
1. Implicit Conversion (Type Coercion)
JavaScript automatically converts data types when needed.
[Link]("5" + 2); // "52" → number 2 is converted to string
[Link]("5" - 2); // 3 → string "5" is converted to number
[Link]("10" * "2"); // 20 → both converted to numbers
[Link](5 + true); // 6 → true = 1
[Link](5 + false); // 5 → false = 0
Rule of thumb:
If there’s a string with +, JS concatenates (joins).
With other operators (-, *, /), it tries to convert to numbers.
2. Explicit Conversion (Manual Type Casting)
You convert data yourself using built-in functions.
String Conversion
let num = 42;
let strNum1 = String(num); // Using String() function
let strNum2 = [Link](); // Using toString() method
Number Conversion
[Link](Number("123")); // 123
[Link](Number("123abc")); // NaN
[Link](parseInt("50px")); // 50
[Link](parseFloat("3.14")); // 3.14
Boolean Conversion
[Link](Boolean(1)); // true
[Link](Boolean(0)); // false
[Link](Boolean("")); // false
[Link](Boolean("Hi")); // true
4. Control Statements
Control statements are used to control the flow of execution in a program — they help JavaScript make decisions and
repeat actions.
1. Conditional Statements
Used to perform different actions based on conditions.
a. if Statement
Executes a block only if the condition is true.
let age = 18;
if (age >= 18) {
[Link]("You are an adult");
}
b. if...else Statement
Executes one block if condition is true, otherwise another block.
let age = 15;
if (age < 18) {
[Link]("You are a minor");
} else {
[Link]("You are an adult");
}
c. if...else if...else Statement
Used for multiple conditions.
let marks = 85;
if (marks >= 90) {
[Link]("Grade A");
} else if (marks >= 75) {
[Link]("Grade B");
} else {
[Link]("Grade C");
}
d. Nested if
You can also put one if inside another.
let num = 10;
if (num > 0) {
if (num % 2 === 0) {
[Link]("The number is positive and even");
} else {
[Link]("The number is positive and odd");
}
} else {
[Link]("The number is not positive");
}
e. Switch Statement
Used when you have many conditions to check for the same variable.
let day = 3;
switch (day) {
case 1:
[Link]("Sunday");
break;
case 2:
[Link]("Monday");
break;
case 3:
[Link]("Tuesday");
break;
default:
[Link]("Invalid day");
}
2. Looping Statements
Used to repeat a block of code multiple times.
a. for Loop
Runs code a specific number of times.
for (let i = 1; i <= 5; i++) {
[Link]("Number:", i);
}
b. while Loop
Runs as long as the condition is true.
let i = 1;
while (i <= 5) {
[Link](i);
i++;
}
c. do...while Loop
Executes at least once, then checks the condition.
let i = 1;
do {
[Link](i);
i++;
} while (i <= 5);
d. for...of Loop & forEach Loop
Used for arrays or strings.
let fruits = ["apple", "banana", "mango"];
for (let fruit of fruits) {
[Link](fruit);
}
// forEach loop
[Link]((fruit) => [Link](fruit));
e. for...in Loop
Used for objects.
let person = { name: "Raj", age: 24, country: "Nepal" };
for (let key in person) {
[Link](key + ": " + person[key]);
}
break and continue
break → exits the loop.
for (let i = 1; i <= 5; i++) {
if (i === 3) {
break; // exits the loop when i is 5
}
[Link](i); // o/p: 1, 2
}
continue → skips one iteration.
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // skips the iteration when i is 5
}
[Link](i); // o/p: 1, 2, 4, 5
}
✅ Mini Assignment (Practice)
1. Write a program that prints numbers 1 to 10 using a loop.
2. Print only even numbers between 1 and 20.
3. Create a program that checks grades using if...else if.
4. Use a switch to print day names (1–7).
5. Functions in JavaScript
A function is a block of code designed to perform a specific task. It helps you reuse code instead of writing the same
thing multiple times.
function greet() {
[Link]("Hello, Raj!");
}
greet(); // Function call
Example 2:
function add(a, b) {
[Link](a + b);
}
add(5, 10); // Output: 15
Function with Return Value
A function can return a result using the return keyword.
function multiply(a, b) {
return a * b;
}
let result = multiply(4, 5);
[Link]("Result:", result); // Output: 20
Function with Default Parameters
You can give parameters default values.
function greet(name = "Guest") {
[Link]("Hello, " + name + "!");
}
greet(); // Hello, Guest!
greet("Raj"); // Hello, Raj!
Function Expressions
You can also assign a function to a variable.
const square = function(num) {
return num * num;
};
[Link](square(5)); // Output: 25
Arrow Functions (ES6 Feature)
A shorter way to write functions.
const add = (a, b) => a + b;
[Link](add(10, 20)); // Output: 30
If the function has multiple lines:
const greet = (name) => {
[Link]("Hello, " + name);
};
greet("Raj");
Function Scope
Local Scope
Variables declared inside a function are local to that function which are not accessible outside of that function.
function test() {
let x = 10; // local variable
[Link](x); // accessible here
}
test();
[Link](x); // ❌ Error: x is not defined
Global Scope
let x = 10; // global variable
function test() {
[Link](x); // accessible here
}
test();
[Link](x); // accessible here also
Nested Functions
A function can be declared inside another function.
function outer() {
function inner() {
[Link]("Hello from inner function");
}
inner();
[Link]("Hello from outer function");
}
outer();
✅ Mini Assignment (Practice)
1. Create a function greetUser(name) that prints “Hello, [name]!”.
2. Create a function square(num) that returns the square of a number.
3. Use an arrow function to multiply two numbers.
4. Create a function calculateAge(birthYear) that returns your current age.
6. Objects and Arrays in JavaScript
In JavaScript, Objects and Arrays are fundamental data structures used to store and organize data
efficiently.
1. Objects
An object is a collection of key–value pairs (properties).
Each key (also called a property name) is a string, and its value can be anything — a number, string,
array, another object, or even a function.
Syntax:
let objectName = {
key1: value1,
key2: value2,
key3: value3
};
Example:
const person = {
name: "Raj",
age: 24,
country: "Nepal"
};
// Access values
[Link]([Link]); // Dot notation
[Link](person["country"]); // Bracket notation
// Add new property
[Link] = "Coding";
// Update property
[Link] = 25;
// Delete property
delete [Link];
[Link](person);
// Loop through properties
for (let key in person) {
[Link](key + ": " + person[key]);
}
Methods in Objects
Objects can also contain functions called methods.
const car = {
brand: "Tesla",
model: "Model 3",
start: function() {
[Link]("Car started!");
}
};
[Link](); // call method
[Link]([Link]); // access property
Shortcut syntax (modern way):
const user = {
name: "Raj",
greet() {
[Link](`Hello, ${[Link]}!`);
}
};
[Link]();
👉 this refers to the object itself.
Nested Objects
const person = {
name: "Raj",
age: 24,
address: {
city: "Kathmandu",
country: "Nepal"
}
};
[Link]([Link]); // Raj
[Link]([Link]); // Nepal
// Looping through object properties with nested object
for (let key in person) {
if (typeof person[key] === 'object') {
for (let nestedKey in person[key]) {
[Link](`${nestedKey}: ${person[key][nestedKey]}`);
}
} else {
[Link](`${key}: ${person[key]}`);
}
}
Arrays
An array stores multiple values in a single variable, using indexes (starting from 0).
Syntax:
let arrayName = [value1, value2, value3];
Example:
const fruits = ["apple", "banana", "mango"];
// Accessing elements
[Link](fruits[0]); // first item
[Link]([Link]); // array size
// Modifying elements
fruits[1] = "kiwi"; // change second item
// Array methods
[Link]("orange"); // add at end
[Link](); // remove last
[Link]("grape"); // add at start
[Link](); // remove first
[Link](1, 1); // remove 1 item at index 1
[Link](1, 0, "blueberry"); // add at index 1
[Link](2, 1, "strawberry"); // replace 1 item at index 2
[Link](fruits);
const slicedFruits = [Link](1, 3); // copy from index 1 to 2
[Link](slicedFruits);
// Looping through array
for (let i = 0; i < [Link]; i++) {
[Link](fruits[i]);
}
// Using forEach
[Link]((fruit) => [Link](fruit));
// Using for...of
for (let fruit of fruits) {
[Link](fruit);
}
Example:
let arr = [1, 2, 3, 4, 5];
// map() → transform each element
let doubled = [Link]((x) => x * 2);
[Link]("After map:", doubled); // [2,4,8,10]
// filter() → select items based on condition
let greaterThan3 = [Link]((x) => x > 3);
[Link]("After filter:", greaterThan3); // [4,5]
// reduce() → combine all into one value
let sum = [Link]((a, b) => a + b);
[Link]("After reduce:", sum); // 12 (1+2+4+5)
// concat() → merge arrays
let newArr = [Link]([6, 7, 8]);
[Link]("After concat:", newArr); // [1,2,4,5,6,7,8]
7. DOM Manipulation in JavaScript
The DOM (Document Object Model) allows JavaScript to interact with and modify HTML and
CSS dynamically.
It’s how JavaScript makes web pages interactive — for example, showing/hiding content, changing
styles, or reacting to user actions (clicks, input, etc.).
What is the DOM?
When a web page loads, the browser creates a Document Object Model — a tree-like structure
representing all HTML elements.
JavaScript can use the DOM to access, modify, add, or delete HTML elements dynamically.
Example HTML:
<h1 id="title">Hello</h1>
<p class="msg">Welcome to JavaScript</p>
The DOM of above HTML looks like this:
Document
└── html
└── body
├── h1#title
└── [Link]
Example:
<h1 id="title">Hello</h1>
<h2 class="msg">Welcome to JavaScript</h2>
<p>This is a paragraph</p>
<p class="para2">This is second paragraph</p>
<script>
// Accessing elements
const title = [Link]("title"); // Select by ID
const msg = [Link]("msg"); // Select by class
const para = [Link]("p"); // Select all Tag name i.e.<p>
elements
// OR you can do same using querySelector as well
//const title =[Link]("#title"); // Select by ID
//const msg = [Link](".msg"); // Select by class
// const para = [Link]("p"); // Select all <p> elements
const para2 = [Link](".para2"); // Select by class
// Changing text and style
[Link] = "green";
msg[0].[Link] = "orange";
para[0].[Link] = "red";
para[0].[Link] = "20px";
[Link] = "bold";
[Link] = "This text is changed using DOM!";
// Creating and adding new element
let newPara = [Link]("p");
[Link] = "This is a new paragraph.";
[Link](newPara); // to add in the end
//[Link](newPara); // to add in the beginning
//[Link](); // to remove the element
</script>
Changing Content in DOM
You can change the text or HTML inside an element.
Property Description Example
textContent Changes text only [Link] = "Hi Raj!";
innerHTML Changes HTML inside [Link] = "<b>Welcome!</b>";
innerText Changes visible text [Link] = "Visible only text";
8. Events in JavaScript
Events in JavaScript are actions or occurrences that happen in the browser — like when a user clicks a button, types
in a field, or moves the mouse.
JavaScript can listen for these events and respond to them (this is called event handling).
What is an Event?
An event is something that happens to an element.
For example:
Clicking a button
Pressing a key
Submitting a form
Loading a page
Hovering over text
Event Handling Methods
There are three main ways to handle events in JavaScript:
1. Inline Event Handling
(Directly in HTML)
<button clicked!')">Click Me</button>
Or with a function:
<button id="btn">Click Me</button>
<script>
function showMessage() {
alert("Hello Raj!");
}
</script>
2. DOM Property Method
<button id="btn">Click Me</button>
<script>
let btn = [Link]("btn");
[Link] = function () {
alert("Button clicked!");
};
</script>
3. Using addEventListener() (Best Practice)
This is the modern and recommended method.
<button id="btn">Click Me</button>
<script>
let btn = [Link]("btn");
[Link]("click", function() {
alert("Hello Raj, you clicked the button!");
});
</script>
You can also define the function separately:
function greet() {
alert("Welcome!");
}
[Link]("click", greet);
Types of Events
JavaScript supports a wide variety of events, including:
Mouse Events: click, dblclick, mouseover, mouseout, mousedown, mouseup, mousemove
Keyboard Events: keydown, keyup, keypress
Form Events: submit, change, focus, blur, input
Window Events: load, resize, scroll, unload
Touch Events: touchstart, touchend, touchmove (for mobile devices)
Custom Events: You can also create and dispatch your own events.
Event Name Description Example
click When an element is clicked Button, link
dblclick Double click Image, button
mouseover Mouse pointer moves over element Menu hover
mouseout Mouse pointer leaves element Tooltip hide
mousedown Mouse button pressed down Drawing apps
mouseup Mouse button released Drawing apps
keydown Key is pressed Input fields
keyup Key is released Form validation
submit Form is submitted Login form
change Input value changes Dropdown
focus Element is focused Input box
blur Element loses focus Validation
load Page finishes loading Window, image
scroll User scrolls Animation triggers
Changing Text on Click
<h2 id="title">Hello Raj!</h2>
<button id="btn">Change Text</button>
<script>
[Link]("btn").addEventListener("click", function () {
[Link]("title").innerText = "You clicked the button!";
});
</script>
Mouse Events
<p id="para">Hover over this text!</p>
<script>
let p = [Link]("para");
[Link]("mouseover", () => {
[Link] = "red";
});
[Link]("mouseout", () => {
[Link] = "black";
});
</script>
Keyboard Event
<input type="text" id="name" placeholder="Type your name" />
<p id="output"></p>
<script>
[Link]("name").addEventListener("keyup", function () {
[Link]("output").innerText = [Link];
});
</script>
Mini Assignment (Practice)
DOM Manipulation:
Create a small webpage that:
1. Displays a heading and a paragraph.
2. Has a button labeled “Change Content”.
3. When you click the button:
o The heading text changes to “Welcome to JavaScript DOM!”
o The paragraph text changes to “You just updated the content using JavaScript.”
o The text color of the paragraph changes to blue.
o A new paragraph is added at the bottom saying “New element added!”
Events:
1. Create a button that changes the background color when clicked.
2. Create a paragraph that changes text color on hover.
3. Create an input box that displays what the user types in real-time.
4. Create a button that shows an alert with your name on double-click.
9. ES6+ Features in JavaScript
ES6 (ECMAScript 2015) introduced many modern and powerful features that make JavaScript cleaner, shorter, and
easier to write.
We have already covered most of the features like: let and const, Template literals, Arrow functions, Default
parameters
Let’s cover the remaining ones — Modules, Destructuring, Spread/Rest, Template Literals, and Classes.
1. Modules (import / export)
Modules let you split your code into multiple files for better organization and reuse.
Example:
[Link]
export function add(a, b) {
return a + b;
}
export const PI = 3.1416;
[Link]
import { add, PI } from './[Link]';
[Link](add(5, 10)); // Output: 15
[Link](PI); // Output: 3.1416
[Link]
<script type="module" src="[Link]"></script>
Note: You must use type="module" in your HTML:
➡️You can also use default export if exporting only one main thing:
// [Link]
export default function square(x) {
return x * x;
}
// Note: You can have only one default export per module
// [Link]
import square from './[Link]';
[Link](square(5)); // Output: 25
2. Destructuring (Arrays & Objects)
Destructuring allows you to unpack values from arrays or objects easily.
Array Destructuring:
const fruits = ["apple", "banana", "mango"];
const [first, second, third] = fruits;
[Link](first); // apple
Object Destructuring:
const person = { name: "Raj", age: 24, country: "Nepal" };
const { name, age } = person;
[Link](name); // Raj
[Link](age); // 24
You can also rename:
const { country: nation } = person;
[Link](nation); // Nepal
3. Spread and Rest Operators (...)
Spread Operator — expands elements
Used to copy or merge arrays/objects.
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // spread
[Link](arr2); // [1, 2, 3, 4, 5]
With objects:
const user = { name: "Raj", age: 24 };
const updated = { ...user, country: "Nepal" };
[Link](updated); // {name: "Raj", age: 24, country: "Nepal"}
Rest Operator — collects remaining values
Used to group remaining items into an array.
function sum(...numbers) {
return [Link]((total, n) => total + n, 0);
}
[Link](sum(1, 2, 3, 4)); // Output: 10
4. Classes (Object-Oriented JavaScript)
ES6 introduced class syntax for creating objects easily.
Example:
class Person {
constructor(name, age) {
[Link] = name;
[Link] = age;
}
greet() {
[Link](`Hello, my name is ${[Link]} and I am ${[Link]} years old.`);
}
}
// Creating objects
const person1 = new Person("Raj", 24);
const person2 = new Person("Asha", 22);
[Link](); // Hello, my name is Raj and I am 24 years old.
[Link](); // Hello, my name is Asha and I am 22 years old.
Inheritance:
You can create subclasses using extends.
class Student extends Person {
constructor(name, age, course) {
super(name, age); // call parent constructor
[Link] = course;
}
study() {
[Link](`${[Link]} is studying ${[Link]}.`);
}
}
const student1 = new Student("Raj", 24, "BCA");
[Link](); // inherited
[Link]();
🧩 Mini Assignment
1. Create a module with two exported functions (add, multiply) and import them.
2. Use destructuring to extract name and age from a person object.
3. Use spread to merge two arrays.
4. Use a rest parameter in a function that sums all given numbers.
5. Create a class Car with model, year, and a method start().
2. Core JavaScript Concepts:
Variables and Data Types:
Understanding let, const, var, and primitive data types (strings, numbers, booleans, null, undefined, BigInt, Symbol)
and objects.
Operators & Expressions:
Learning about arithmetic, assignment, comparison, and logical operators.
Conditional Statements & Loops:
Implementing if/else, switch, for, while, and do...while loops for controlling program flow.
Functions:
Defining and using functions, including arrow functions, callbacks, and understanding scope and closures.
Arrays & Objects:
Working with data structures like arrays and objects, including common array methods (map, filter, reduce, forEach).
ES6+ Features:
Exploring modern JavaScript features like modules (import/export), destructuring, spread/rest operators, template
literals, and classes.
3. Browser-Specific JavaScript (DOM Manipulation & Events):
DOM Manipulation:
Interacting with the Document Object Model to dynamically modify web page content and structure.
Events & Event Handling:
Responding to user interactions (clicks, keypresses, scrolls) and other browser events.
4. Asynchronous JavaScript & APIs:
Promises: Handling asynchronous operations and managing their resolution or rejection.
Fetch API & AJAX: Making HTTP requests to fetch data from servers and interact with APIs.
Async/Await: A cleaner syntax for writing and managing asynchronous code.
JSON: Understanding and working with JSON data format for API communication.
5. Advanced Concepts & Ecosystem:
Error Handling: Implementing try...catch blocks and other strategies for managing errors.
Debugging & Dev Tools: Utilizing browser developer tools for inspecting and debugging JavaScript code.
Object-Oriented Programming (OOP): Understanding concepts like encapsulation, inheritance,
polymorphism, and abstraction in JavaScript.
Introduction to Frameworks/Libraries: Exploring popular front-end frameworks like React, Vue, or
Angular, or back-end frameworks like [Link] with Express.
Version Control (Git & GitHub): Learning to manage code changes and collaborate with others.
Testing: Implementing unit and integration tests for JavaScript code using tools like Jest.
Deployment: Understanding how to deploy web applications.
6. Continuous Learning:
Staying updated with the latest JavaScript features, best practices, and emerging technologies is crucial for
long-term development.
Build Projects
When you start building projects, you get to know their functioning. So, build some amazing projects on JavaScript
and get hands-on experience. Here are some of the list of projects you must build in JavaScript:
1. A Calculator
2. Countdown Timer
3. To-Do List
4. Movie App
5. Social Media App Clone
6. Resume Builder
7. Online Editor
8. A Gaming App
9. A Quiz App
10. Tic Tac Toe