0% found this document useful (0 votes)
0 views

JavaScript Notes

Uploaded by

mosaimose.n
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

JavaScript Notes

Uploaded by

mosaimose.n
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

Introduction to JavaScript

Definition: JavaScript is a high-level, dynamic programming language used to


make web pages interactive. It is a core technology of the World Wide Web,
alongside HTML and CSS.

JavaScript is a versatile, dynamically typed programming language used for


interactive web applications, supporting both client-side and server-
side development, and integrating seamlessly with HTML, CSS, and a rich
standard library.

 JavaScript is a single-threaded language that executes one task at a


time.

 It is an Interpreted language which means it executes the code line by


line.

 The data type of the variable is decided at run-time in JavaScript that’s


why it is called dynamically typed.

“Hello, World!” Program in Browser Console

A “Hello, World!” program is the simplest way to get started with any
programming language. Here’s how you can write one using JavaScript.

<html>
<head></head>
<body>
<h1>Check the console for the message!</h1>
<script>
// This is our first JavaScript program
console.log("Hello, World from console..!");
alert("Hello, World from alert..!");
</script>
</body>
</html>

In this example

The <script> tag is used to include JavaScript code inside an HTML


document.

console.log() prints messages to the browser’s developer console. Open the


browser console to see the “Hello, World!” message.
“Hello World” Program in Server Console

We can also print the “Hello World” program directly into the console
terminal without embedded it into HTML. Create an index.js file and add the
code to it.

/* This is a multi-line comment.

It can span several lines. */

console.log("Hello, World from the console..!"); // Prints Hello, World! to the


console

In this example

console.log(): The console.log() method is used to print messages to the


browser’s developer console. Open the console (usually with F12 or Ctrl +
Shift + J) to see the message “Hello, World!” displayed.

Comments in the Code:

 Multi-line Comment: The /*…… */ syntax is used to write a comment


spanning multiple lines.
 Single-line Comment: The // syntax is used for short, inline
comments, like the one explaining the console.log function.

Key Features of JavaScript

 Client-Side Scripting: JavaScript runs on the user’s browser, so has a


faster response time without needing to communicate with the server.

 Versatile: JavaScript can be used for a wide range of tasks, from


simple calculations to complex server-side applications.

 Event-Driven: JavaScript can respond to user actions (clicks,


keystrokes) in real-time.

 Asynchronous: JavaScript can handle tasks like fetching


data from servers without freezing the user interface.
 Rich Ecosystem: There are numerous libraries and frameworks built
on JavaScript, such as React, Angular, and Vue.js, which make
development faster and more efficient.

Client Side and Server Side nature of JavaScript

 Client-side: Involves controlling the browser and its Document Object


Model (DOM), handling user events like clicks and form inputs.
Libraries such as AngularJS, ReactJS, and VueJS are commonly used.

 Server-side: Involves interacting with databases, manipulating files,


and generating responses. With Node.js and frameworks like
Express.js, JavaScript is also widely used on the server side.

 Imperative Programming: Focuses on how to perform tasks,


controlling the flow of computation. It includes approaches like
procedural and object-oriented programming, often using constructs
like async/await to handle actions.

 Declarative Programming: Focuses on what should be done rather


than how it’s done. It emphasizes describing the desired result, like
with arrow functions, without detailing the steps to achieve it.

Applications of JavaScript

 Web Development: JavaScript adds interactivity and dynamic


behavior to static websites, with popular frameworks
like AngularJS enhancing development.

 Web Applications: JavaScript powers robust web applications,


leveraging APIs, React, and Electron to create dynamic user
experiences like Google Maps.

 Server Applications: Node.js brings JavaScript to the server side,


enabling powerful server applications and full-stack development.

 Game Development: JavaScript, combined with HTML5 and libraries


like Ease JS, enables the creation of interactive games for the web.

 Smartwatches: Pebble JS allows JavaScript to run on smartwatches,


supporting apps that require internet connectivity.
Limitations of JavaScript

 Security Risks : JavaScript can be used for attacks like Cross-Site


Scripting (XSS), where malicious scripts are injected into a website to
steal data by exploiting elements like <img>, <object>, or <script>
tags.

 Performance : JavaScript is slower than traditional languages for


complex tasks, but for simple tasks in a browser, performance is
usually not a major issue.

 Complexity : To write advanced JavaScript, programmers need to


understand core programming concepts, objects, and both client- and
server-side scripting, which can be challenging.

 Weak Error Handling and Type Checking : JavaScript is weakly


typed, meaning variables don’t require explicit types. This can lead to
issues as type checking is not strictly enforced.

Why JavaScript is known as a lightweight programming language ?

 JavaScript is considered a lightweight language due to its low CPU


usage, minimalist syntax, and ease of implementation.
 With no explicit data types and a syntax similar to C++ and Java, it’s
easy to learn and runs efficiently in browsers.
 Unlike heavier languages like Dart or Java, JavaScript, especially
with Node.js, performs faster and uses fewer resources.
 While it has fewer built-in libraries, this makes it more flexible,
though external libraries are often needed for advanced functionality.
 JavaScript’s efficiency and simplicity make it a top choice for web
development.

Is JavaScript Compiled or Interpreted or both ?

JavaScript is both compiled and interpreted. The V8 engine improves


performance by first interpreting code and then compiling frequently used
functions for speed. This makes JavaScript efficient for modern web apps. It’s
mainly used for web development but also works in other environments.

Just-In-Time (JIT) compilation is a technique used by JavaScript engines


(like V8) to improve performance. How it works:

 Interpretation: Initially, the code is interpreted line-by-line by the


engine.
 Hot Code Detection: The engine identifies frequently executed code,
such as often-called functions.

 Compilation: The “hot” code is compiled into optimized machine code


for faster execution.

 Execution: The compiled machine code is then executed directly,


improving performance compared to repeated interpretation.

 JIT compilation balances between interpretation (for quick startup) and


compilation (for faster execution).

Discuss JavaScript Versions, features and their year of release?

JavaScript Syntax

JavaScript syntax refers to the rules and conventions dictating how code is
structured and arranged within the JavaScript programming language. This
includes statements, expressions, variables, functions, operators and control
flow constructs.

Syntax meaning in coding

In coding, “syntax” refers to the set of rules that defines the structure and
format of the code in a programming language. It dictates how code should
be written so that it can be correctly interpreted and executed by the
compiler or interpreter.

Adding JavaScript in HTML Document

To add JavaScript in HTML document, several methods can be used. These


methods include embedding JavaScript directly within the HTML file or
linking an external JavaScript file.

JavaScript code is embedded in HTML using the <script> tag. The script can
be added using several methods i.e.

1. Inline JavaScript

Writing JavaScript code directly inside the HTML element using the onclick,
onmouseover, or other event handler attributes. E.g.

<html>
<head></head>
<body>
<h2> Adding JavaScript in HTML Document </h2>
<button onclick="alert('JavaScript Button Clicked..!')"> Click Here
</button>
</body>
</html>

2. Internal JavaScript (Within <script> Tag)

You can write JavaScript code inside the <script> tag within the HTML file.
This is known as internal JavaScript and is commonly placed inside the
<head> or <body> section of the HTML document.

i. JavaScript Code Inside <head> Tag

Placing JavaScript within the <head> section of an HTML document ensures


that the script is loaded and executed as the page loads. This is useful for
scripts that need to be initialized before the page content is rendered.

<html>
<head>
<script>
function myFun() {
document.getElementById("demo")
.innerHTML = "This content is from JavaScript Code Inside
head Tag..!";
}
</script>
</head>
<body>
<h2>Add JavaScript Code inside Head Section </h2>
<h3 id="demo" style="color:green;"> To demostrate JavaScript
Code Inside head Tag </h3>
<button type="button" onclick="myFun()"> Click Here </button>
</body>
</html>

ii. JavaScript Code Inside <body> Tag


JavaScript can also be placed inside the <body> section of an HTML page.
Typically, scripts placed at the end of the <body> load after the content,
which can be useful if your script depends on the DOM being fully loaded.

<html>
<head></head>
<body>
<h2> Add JavaScript Code inside Body Section </h2>
<h3 id="demo" style="color:green;"> To demostrate JavaScript Code
Inside body Tag </h3>
<button type="button" onclick="myFun()"> Click Here </button>
<script>
function myFun() {
document.getElementById("demo")
.innerHTML = " This content is from JavaScript Code Inside body
Tag..!";
}
</script>
</body>
</html>

iii. External JavaScript (Using External File)

For larger projects or when reusing scripts across multiple HTML files, you
can place your JavaScript code in an external .js file. This file is then linked to
your HTML document using the src attribute within a <script> tag.

HTML:

<html>
<head>
<script src="script.js"></script>
</head>
<body>
<h2> External JavaScript </h2>
<h3 id="demo" style="color:green;"> To demonstrate External
JavaScript </h3>
<button type="button" onclick="myFun()"> Click Here </button>
</body>
</html>
JavaScript:

/* Filename: script.js*/

function myFun () {

document.getElementById('demo')

.innerHTML = 'This content is from external JavaScript'

Advantages of External JavaScript

 Faster Page Load Times: Cached external JavaScript files don’t need
to be reloaded every time the page is visited, which can speed up
loading times.

 Improved Readability and Maintenance: Keeping HTML and


JavaScript separate makes both easier to read and maintain.

 Separation of Concerns: By separating HTML (structure) and


JavaScript (behavior), your code becomes cleaner and more modular.

 Code Reusability: One external JavaScript file can be linked to


multiple HTML files, reducing redundancy and making updates easier.

Asynchronous and Deferred JavaScript

JavaScript can be loaded asynchronously or deferred to optimize page


performance, especially for larger scripts.
By default, JavaScript blocks the rendering of the HTML page until it is fully
loaded, but using async or defer can help improve load times.

1. async Attribute
This attribute loads the script asynchronously, i.e. the script will be
downloaded and executed as soon as it is available, without blocking the
page.
<script src="script.js" async></script>

2. defer Attribute
This attribute delays the execution of the script until the entire HTML
document has been parsed. This is particularly useful for scripts that
manipulate the DOM.
<script src="script.js" defer></script>
Referencing External JavaScript Files
There are three ways to reference an external script in JavaScript:
 By using a full URL: src = "https://www.kcau.ac.ke/js/script.js"
 By using a file path: src = "/js/script.js"
 Without using any path: src = "script.js"

JavaScript 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().

1. Using innerHTML

To access an HTML element, JavaScript can use the document.getElementById(id)


method.

 The id attribute defines the HTML element.


 The innerHTML property defines the HTML content:

<!DOCTYPE html>
<html>
<body>
<h2>Inner HTML output</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
2. Using document.write()

For testing purposes, it is convenient to use document.write():

<!DOCTYPE html>
<html>
<body>
<h2>Using Document.write</h2>
<script> document.write(5 + 6); </script>
</body>
</html>
Note: Using document.write() after an HTML document is loaded, will delete
all existing HTML. Thus document.write() method should only be used for
testing. E.g.

<!DOCTYPE html>
<html>
<body>
<h2>Using Document.write - deletes html </h2>
<p>Other html data that will be deleted also </p>
<button type="button" onclick="document.write(5 + 6)">Click Here
</button>
</body>
</html>

3. Using window.alert()

You can use an alert box to display data:

<!DOCTYPE html>
<html>
<body>
<h2>Using windows alert </h2>
<script>
window.alert(5 + 6);
//alert(5 + 6);
</script>
</body>
</html>
You can skip the window keyword as shown under the commented line.
The window object is the global scope object. This means that variables,
properties, and methods by default belong to the window object. This
also means that specifying the window keyword is optional.

4. Using console.log()

For debugging purposes, you can call the console.log() method in the
browser to display data.

<!DOCTYPE html>

<html>

<body>

<h2>Using console </h2>

<script> console.log(5 + 6); </script>

</body>

</html>

JavaScript Print

JavaScript does not have any print object or print methods; thus you cannot
access output devices from JavaScript.

The only exception is that you can call the window.print() method in the
browser to print the content of the current window.

<!DOCTYPE html>
<html>
<body>
<h2>Using windows print function: </h2>
<p>This will print the <b> current page </b> to either device, pdf
format etc.</p>
<button onclick="window.print()">Print this page</button>
</body>
</html>

JavaScript Statements/code
JavaScript statements are programming instructions that a computer
executes. They are composed of:
 Values
 Operators
 Expressions
 Keywords
 Comments
This statement tells the browser to write a given data/ statement inside an
HTML element id. E.g.
document.getElementById("demo").innerHTML = "Internet application
Programming.";

The statements are executed, one by one, in the same order as they are
written.

JavaScript statements are separated by Semicolons. E.g.

 let x, y, z; // Declare 3 variables


 x = 5; // Assign the value 5 to x

Ending statements with semicolon is not required, but highly recommended.

JavaScript Keywords/Reserved words:

JavaScript statements often start with a keyword to identify the JavaScript


action to be performed. E.g.

Keyword Description
var Declares a variable
let Declares a block variable
const Declares a block constant
if Marks a block of statements to be executed on a condition
switch Marks a block of statements to be executed in different cases
for Marks a block of statements to be executed in a loop
function Declares a function
return Exits a function
try Implements error handling to a block of statements
Note: Reserved words cannot be used as names for variables.
Giving examples, discuss various types of JavaScript statements?

JavaScript Events:

JavaScript Events are actions or occurrences that happen in the


browser. They can be triggered by various user interactions or by the
browser itself. E.g.

<html>
<script>
function myFun() {
document.getElementById(
"iap").innerHTML = "Click event triggered, for Internet
Application Programming";
}
</script>
<body>
<button onclick="myFun()">Click me </button>
<p id="iap"></p>
</body>
</html>
 The onclick attribute in the <button> calls the myFun() function
when clicked.

 The myFun() function updates the <p> element with id=”iap” by


setting its innerHTML to “Click event triggered, for Internet Application
Programming”.

 Initially, the <p> is empty, and its content changes dynamically on the
button click.
Event Types:

JavaScript supports a variety of event types. Common categories include:

 Mouse Events: click, dblclick, mousemove, mouseover, mouseout

 Keyboard Events: keydown, keypress, keyup

 Form Events: submit, change, focus, blur

 Window Events: load, resize, scroll

Common JavaScript Events

Event Description
Attribute
onclick Triggered when an element is clicked.
onmouseover Fired when the mouse pointer moves over an
element.
onmouseout Occurs when the mouse pointer leaves an
element.
onkeydown Fired when a key is pressed down.
onkeyup Fired when a key is released.
onchange Triggered when the value of an input element
changes.
onload Occurs when a page has finished loading.
onsubmit Fired when a form is submitted.
onfocus Occurs when an element gets focus.
onblur Fired when an element loses focus.

Event Handling Methods

1. Inline HTML Handlers

<button onclick="alert('Button clicked!')">Click Me</button>

Full code below:

<html>
<body>
<h2> Inline HTML Handlers </h2>
<button onclick="alert('Button clicked!')">Click Me</button>
</body>
</html>
2. DOM Property Handlers

let btn = document.getElementById("myButton");


btn.onclick = () => {
alert("Button clicked!");
};

3. addEventListener() (Preferred)

btn.addEventListener("click", () => {
alert("Button clicked using addEventListener!");
});

addEventListener() is the most versatile and recommended method as it


supports multiple event listeners and removal of listeners.

Practical Applications

1. Form Validation

<html>
<body>
<h2>Form Validation</h2>
<form id="formval">
<input type="text" placeholder="Enter some values"
id="formInput" />
<button type="submit">Submit</button>
</form>
<script>
document.querySelector("#formval").addEventListener("submit",
(e) => {
let input = document.querySelector("#formInput");
if (!input.value) {
e.preventDefault();
alert("Input cannot be empty");
}
else{
alert("Something inserted into database.");
}
});
</script>
</body>
</html>

JavaScript Variables
JavaScript Variables can be declared in 4 ways:

 Automatically
 Using var
 Using let
 Using const
var a = 10 // Old style
let b = 20; // Prferred for non-const
const c = 30; // Preferred for const (cannot be changed)

The var keyword was used in all JavaScript code from 1995 to 2015.

The let and const keywords were added to JavaScript in 2015.

The var keyword should only be used in code written for older browsers.

JavaScript Identifiers

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.

 Variable names must begin with a letter, underscore (_), or dollar sign
($).
 Names are case sensitive (y and Y are different variables).

 Reserved words/keywords (like function, class, return, etc.) cannot be


used as variable names.

Declaring a JavaScript Variable

Creating a variable in JavaScript is called "declaring" a variable. E.g.

var carName;

let carName;

Variable initialization

Assigning value to a variable. E.g.

carName = "Nissan";

Program Example

<p id="demo"></p>
<script>
let carName = "Nissan";
document.getElementById("demo").innerHTML = carName;
</script>

You can declare many variables in one statement by starting the statement
with let and separate the variables by comma:

let person = "John Mark", carName = "Nissan", price = 200;

Below is an example program to illustrate the same:


<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p>You can declare many variables in one statement.</p>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
let course = "BIT", unit_code = " BIT 04204 ", unitName ="Internet
Application Programming";
document.getElementById("demo").innerHTML = course;
document.getElementById("demo1").innerHTML = unit_code;
document.getElementById("demo2").innerHTML = unitName;
</script>
</body>
</html>

Global and Local variables in JavaScript

Importance

Enables for writing clean, maintainable, and error-free code.

Variables can be declared with different scopes, affecting where and how
they can be accessed.

Global Variables
They are declared outside of any function or block scope.

They are accessible from anywhere within the script, including inside
functions and blocks. Variables declared without the var, let,
or const keywords inside a function automatically become global variables.

However, variables declared with var, let, or const inside a function are local
to that function unless explicitly marked as global using window (in browser
environments) or global (in Node.js).

Key Characteristics of Global Variables:

 Scope: Accessible throughout the entire script, including inside


functions and blocks.
 Automatic Global Variables: If a variable is declared inside a
function without var, let, or const, it automatically becomes a global
variable (a common source of bugs).

Example:

<!DOCTYPE html>
<html>
<head><title>Global Variables</title></head>
<body>
<script>
let petName = 'Jimmy' // Global variable
myFunction()

function myFunction() {
fruit = 'apple'; // Considered global
console.log('My pet name is ' + petName + ' - from global')
}

console.log('My pet name is ' + petName +'.' + ' Fruit name is ' +
fruit + ' - Considered global')
</script>

</body>
</html>

Explanation: We can see that the variable petName is declared in the


global scope and is easily accessed inside functions. Also, the fruit was
declared inside the function without any keyword so it was considered global
and was accessible inside another function.

Local Variables
Local variables are defined within functions in JavaScript.
They are confined to the scope of the function that defines them and cannot
be accessed from outside.
Attempting to access local variables outside their defining function results in
an error.

Key Characteristics of Local Variables:


 Scope: Limited to the function or block in which they are declared.
 Function-Specific: Each function can have its own local variables,
even if they share the same name.

Example:
<!DOCTYPE html>
<html>
<head><title>Local Variables</title></head>
<body>
<script>
myfunction();
anotherFunc();
let petName;
function myfunction() {
let petName = "Simba"; // local variable
console.log(petName);
}

function anotherFunc() {
let petName = "Jimmy"; // local variable
console.log(petName);
}
console.log(petName);
</script>

</body>
</html>

Discuss when to use either const, var, or let in JavaScript variable


declaration?.

More Examples:

A program to calculate the area and circumference of a circle.

<!DOCTYPE html>
<html>
<body>
<h1>Calculate Area and Circumference</h1>

<p>JavaScript program to calculate Area and Circumference of a


circle. Capture radius from user keyboard.</p>

<p id="area1"></p>
<p id="cir"></p>
<script>
// Capture the radius from the user using prompt()
let radius = parseFloat(prompt("Enter the radius of the circle:"));

// Calculate the area (πr²)


const PI = 3.142;
const area = PI*radius*radius;
// Calculate the circumference (2πr)
const circumference = 2*PI *radius;

// Output the results


document.getElementById("area1").innerHTML = "Area: "+ area;
document.getElementById("cir").innerHTML = "Circumference: "+
circumference;
</script>
</body>
</html>

A JavaScript program to add two numbers entered by the user.

<!DOCTYPE html>
<html>
<body>
<h1>Add Two Numbers Entered by the User</h1>
<p>JavaScript program to add two numbers captured from user
keyboard.</p>
<p id="add"></p>
<script>
// store input numbers
const num1 = parseInt(prompt('Enter the first number '));
const num2 = parseInt(prompt('Enter the second number '));
//add two numbers
const sum = num1 + num2;

// display the sum


document.getElementById("add").innerHTML = "The sum is: "+ sum;
//console.log(`The sum of ${num1} and ${num2} is ${sum}`);
</script>
</body>
</html>

JavaScript Program to Calculate the Area of a Triangle

<!DOCTYPE html>
<html>
<head><title>Area of triangle</title></head>
<body>
<p id="area1"></p>
<script>
const baseValue = prompt('Enter the base of a triangle: ');
const heightValue = prompt('Enter the height of a triangle:
');
// calculate the area
const areaValue = (baseValue * heightValue) / 2;
document.getElementById("area1").innerHTML = "The area
of the triangle is: "+ areaValue;

/*console.log(`The area of the triangle is ${areaValue}`); */


</script>

</body>
</html>

JavaScript Operators

JavaScript operators are symbols or keywords used to perform operations


on values and variables. They are the building blocks of JavaScript
expressions and can manipulate data in various ways.

The main types of JavaScript operators include:


 Arithmetic Operators
 Assignment Operators
 Comparison Operators
 Logical Operators
 Bitwise Operators
 String Operators
 Conditional (Ternary) Operator
 Type Operators
 Comma Operator
 Unary Operators

1. Arithmetic Operators

Arithmetic Operators perform mathematical calculations like addition,


subtraction, multiplication, etc.

OPERATOR NAME SYMB USAGE OPERATION


OL
Addition Operator + a+b Add two numbers or concatenate the
string
Subtraction - a–b Difference between the two operators
Operator
Multiplication * a*b Multiply two number
Operator
Division Operator / a/b Find the quotient of two operands
Modulus Operator % a%b Find the remainder of two operands
Exponentiation ** a ** b Raise the Left operator to the power of
Operator the right operator
Increment Operator ++ a++ Return the operand and then increase
++a by one.
Increase operand by one and then
return.
Decrement -- a- – Return operand and then decrease by
Operator – -a one
Decrease operand by one and then
return
Unary Plus(+) +a It operates on a single
operand. Converts NaN to number.
Preferred because it does not perform
any other operations on the number.
Unary Negation (-) -a It operates on a single
operand. Converts operand to
negative.

2. JavaScript Assignment Operators

Used to assign values to variables. They can also perform operations like
addition or multiplication before assigning the value.

OPERATOR USAG MEANI OPERATION


NAME E NG
Addition a+=b a=a+b Adds the value to the right operand to
Assignment a variable and assigns the result to the
variable. Addition or concatenation is
possible.
Subtraction a-=b a=a-b Subtracts the value of the right
Assignment operand from a variable and assigns
the result to the variable.
Multiplication a*=b a=a*b Multiplies a variable by the value of
Assignment the right operand and assigns the
result to the variable.
Division a/=b a=a/b Divides a variable by the value of the
Assignment right operand and assigns the result to
the variable.
Remainder a%=b a=a%b Divides a variable by the value of the
Assignment right operand and assigns the
remainder to the variable.
Exponentiation a**=b a=a**b Raises the value of a variable to the
Assignment power of the right operand.
Left Shift a<<= a=a<<b Moves the specified amount of bits to
Assignment b the left and assigns the result to the
variable.
Right Shift a>>= a=a>>b Moves the specified amount of bits to
Assignment b the right and assigns the result to the
variable.
Bitwise AND a&=b a=a&b Uses the binary representation of both
Assignment operands, does a bitwise AND
operation on them, and assigns the
result to the variable.
Bitwise OR a|=b a=a | b Uses the binary representation of both
Assignment operands, does a bitwise OR operation
on them, and assigns the result to the
variable.
Bitwise XOR a^=b a=a^b Uses the binary representation of both
Assignment operands, does a bitwise XOR
operation on them, and assigns the
result to the variable.
Logical AND a&&= x && (x Assigns the value of y into x only
Assignment b = y) if x is a truthy value.
Logical OR ||= x || (x = Used to assign the value of y to x if the
Assignment y) value of x is falsy.
Nullish ??= x ?? (x = Assigns the value of y to x if the value
coalescing y) of x is null.
Assignment

3. JavaScript Comparison Operators

Comparison operators compare two values and return a boolean (true or


false). They are essential tools for checking conditions and making
decisions in your code.

OPERATOR NAME USAGE OPERATION


Equality Operator a == b Compares the equality of two operators
Inequality Operator a != b Compares inequality of two operators. It
negates.
Strict Equality a === b Compares both the value and type of
Operator the operand
Strict Inequality a !== b Compares inequality with type
Operator
Greater than Operator a>b Checks if the left operator is greater
than the right operator
Greater than or equal a >= b Checks if the left operator is greater
Operator than or equal to the right operator
Less than Operator a<b Checks if the left operator is smaller
than the right operator
Less than or equal a <= b Checks if the left operator is smaller
Operator than or equal to the right operator

== compares values with type coercion, meaning it converts both values to


a common type before comparing.

=== compares values without type coercion, ensuring both the value and
type must match exactly.

4. JavaScript Logical Operators

Comparison operators are mainly used to perform the logical operations that
determine the equality or difference between the values.

OPERATOR NAME USAGE OPERATION


Equality Operator a == b Compares the equality of two operators
Inequality Operator a != b Compares inequality of two operators
Strict Equality a === b Compares both the value and type of the
Operator operand
Strict Inequality a !== b Compares inequality with type
Operator
Greater than a>b Checks if the left operator is greater than
Operator the right operator
Greater than or a >= b Checks if the left operator is greater than
equal Operator or equal to the right operator
Less than Operator a<b Checks if the left operator is smaller than
the right operator
Less than or equal a <= b Checks if the left operator is smaller than
Operator or equal to the right operator

5. JavaScript Bitwise Operators

Bitwise operators perform operations on binary representations of numbers.

OPERATOR NAME USAG DESCRIPTION


E
Bitwise AND(&) a & b Returns true if both operands are true
Bitwise OR(|) a|b Returns true even if one operand is true
Biwise XOR(^) a^b Returns true if both operands are different
Bitwise NOT(~) ~a Flips the value of the operand
Bitwise Left a << Shifts the bit toward the left
Shift(<<) b
Bitwise Right a >> Shifts the bit towards the right
Shift(>>) b
Zero Fill Right a Shifts the bit towards the right but adds 0
Shift(>>>) >>> from left
b

6. JavaScript Ternary Operator

The ternary operator is a shorthand for conditional statements. It takes three


operands.

The Ternary Operator in JavaScript is a shortcut for writing simple if-else


statements. It’s also known as the Conditional Operator because it works
based on a condition. The ternary operator allows you to quickly decide
between two values depending on whether a condition is true or false.

How Ternary Operator Work


The ternary operator works with three parts:
 Condition: A statement that returns true or false.
 Value if True: What happens if the condition is true?
 Value if False: What happens if the condition is false?
Syntax:
condition ? trueExpression : falseExpression

Example:

// JavaScript to illustrate Conditional operator

let age = 60;

let res = (age > 59) ? "Adult" : "Not Adult";

console.log(res);

7. JavaScript Comma Operator


Comma Operator (,) mainly evaluates its operands from left to right
sequentially and returns the value of the rightmost operand.

The comma operator is often used in for loops to include multiple


expressions within the loop initialization or increment sections. It can also be
used in variable assignments and other contexts where multiple
operations need to be performed in sequence. Also used to include multiple
expressions in a single variable declaration statement, but only the last
expression’s value will be assigned to the variable.

Example:

let x = (1, 2, 3);


console.log(x);

Output: 3

8. JavaScript Relational Operators

They are used to compare its operands and determine the relationship
between them. They return a Boolean value (true or false) based on the
comparison result.

They are:

1. The in-operator - checks if a specified property exists in an object or if an


element exists in an array. It returns a Boolean value. E.g.

let languages = ["HTML", "CSS", "JavaScript"];


// true (index 1 exists in the array)
console.log(1 in languages);
// false (index 3 doesn't exist in the array)
console.log(3 in languages);

Output:
true
false

2. The instanceof operator in JavaScript tests if an object is an instance of


a particular class or constructor, returning a Boolean value.

let languages = ["HTML", "CSS", "JavaScript"];


console.log(languages instanceof Array);
console.log(languages instanceof Object);
console.log(languages instanceof String);
console.log(languages instanceof Number);

Output:
true
true
false
false

In JavaScript,

Operator How it works


< (Less than) Returns true if the left operand is less than the
right operand; otherwise, it returns false.
> (Greater than) Returns true if the left operand is greater than
the right operand; otherwise, it returns false.
<= (Less than or equal Returns true if the left operand is less than or
to) equal to the right operand; otherwise, it returns
false.
>= (Greater than or Returns true if the left operand is greater than or
equal to) equal to the right operand; otherwise, it returns
false.
== (Equality) Compares two values for equality after
converting both values to a common type (type
coercion). It returns true if the values are equal;
otherwise, it returns false.
!= (Inequality) Compares two values for inequality after
converting both values to a common type (type
coercion). It returns true if the values are not
equal; otherwise, it returns false.
=== (Strict equality) Compares two values for equality without
converting their types. It returns true if the
values are equal and of the same type;
otherwise, it returns false.
!== (Strict inequality) Compares two values for inequality without
converting their types. It returns true if the
values are not equal or not of the same type;
otherwise, it returns false.

9. JavaScript String Operators

JavaScript String Operators include concatenation (+) and concatenation


assignment (+=), used to join strings or combine strings with other data
types. E.g.

const s = "Hello" + " " + "World";


console.log(s);
Output
Hello World

1. Concatenate Operator
This combines strings using the ‘+’ operator and creates a new string.
let str1 = "BIT 04204";
let str2 = " Internet Application Programming";
let result = (str1 + str2);
console.log(result);

Output:
BIT 04204 Internet Application Programming

2. Concatenate Assignment Operator

We can modify one string by adding content of another one to it.

let str1 = " BIT 04204 ";


let str2 = " Internet Application Programming ";
str1 += str2;
console.log(str1);

Output:
BIT 04204 Internet Application Programming

Control Structures
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 if Statement

Use the if statement to specify a block of JavaScript code to be executed if a


condition is true.

Syntax:

if (condition) {
// block of code to be executed if the condition is true
}

Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if</h2>
<p id="age"> if condtion..!</p>
<script>
let age1 = parseInt(18);
if (age1<= 18) {
document.getElementById("age").innerHTML = "You are a Young
person. !";
}
</script>
</body>
</html>

The if else Statement

Use the else statement to specify a block of code to be executed if the


condition is false.

if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

Example:

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if-else</h2>
<p id="age"> if else structure..! </p>
<script>
let age1 = parseInt(prompt("Enter your age: "));
if (age1<= 18) {
document.getElementById("age").innerHTML = "You are a Young
person. !";
}
else {
document.getElementById("age").innerHTML = "You are an Adult. !";
}
</script>
</body>
</html>

The if - else if Statement

Use the else if statement to specify a new condition if the first condition is
false.

Syntax:

if (condition1) {
// block of code
}

else if (condition2) {
// block of code

else if (n) {
// block of code
}

else {
// block of code – like default
}

Example:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript if</h2>
<p id="marks">if else if - grading system..!</p>

<script>
let avg_marks = parseInt(prompt("Enter your avarage marks: "));

if (avg_marks >=70 && avg_marks<=100) {


document.getElementById("marks").innerHTML = " You are scored A. ";
}
else if(avg_marks>=60 && avg_marks<70){
document.getElementById("marks").innerHTML = " You are scored B. ";
}
else if(avg_marks>=50 && avg_marks<60){
document.getElementById("marks").innerHTML = " You are scored C. ";
}
else if(avg_marks>=40 && avg_marks<50){
document.getElementById("marks").innerHTML = " You are scored D. ";
}
else if(avg_marks>=0 && avg_marks<40){
document.getElementById("marks").innerHTML = " You are scored E. ";
}
else {
document.getElementById("marks").innerHTML = " Invalid marks. ";
}
</script>
</body>
</html>

The JavaScript Switch Statement

Use the switch statement to select one of many code blocks to be executed.

Works similar to an if else if conditional statements.

Syntax:

switch(expression) {
case 1:
// statement(s)
break;
case 2:
// statement(s)
break;

…..
default:
// statement(s)
}

This is how it works:

 The switch expression is evaluated once.


 The value of the expression is compared with the values of each case.
 If there is a match, the associated statement(s) is executed.
 If there is no match, the default statement(s) is executed.

The break Keyword


 When JavaScript reaches a break keyword, it breaks out of the switch
block.
 This will stop the execution inside the switch block.
 It is not necessary to break the last case in a switch block. The block
breaks (ends) there anyway.

The default Keyword


The default keyword specifies the code to run if there is no case match.

Example:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript switch statements</h2>

<p id="day"></p>

<script>
//let day1 = parseInt(prompt("Enter 0 - 6, to see the day: "));
let day;
switch (new Date().getDay()){
//switch (day1) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
default:
day = "Invalid day of the week. Please put 0 - 6";
}
document.getElementById("day").innerHTML = "Today is " + day;
</script>

</body>
</html>

JavaScript Loops
Loops are used to reduce repetitive tasks by repeatedly executing a block of
code as long as a specified condition is true. This makes code more concise
and efficient.

Types of Loops
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 For Loop


The for statement creates a loop with 3 optional expressions:
Syntax:
for (initialization; condition; increment/decrement) {
// Code to execute
}

Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript for loop</h2>

<script>
//let i = 5;
for (let i = 1; i <= 5; i++) {
console.log("Count:", i);
}
</script>
</body>
</html>
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
In this example
 Initializes the counter variable (let i = 1).
 Tests the condition (i <= 3); runs while true.
 Executes the loop body and increments the counter (i++).

2. The For In Loop


The JavaScript for in statement loops through the properties of an Object:
Syntax:
for (key in object) {
// code block to be executed
}

Example:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript For In Loop</h2>


<p id="id1"></p>
<script>
const person = {fname:"John", lname:"kamau", age:24};
let txt = "";
for (let x in person) {
txt += person[x] + " ";
}
document.getElementById("id1").innerHTML = txt;
</script>
</body>
</html>

Example Explained
 The for in loop iterates over a person object
 Each iteration returns a key (x)
 The key is used to access the value of the key
 The value of the key is person[x]

3. The For Of Loop


The JavaScript for of statement loops through the values of an iterable
object.
It lets you loop over iterable data structures such as Arrays, Strings, Maps,
NodeLists, and more:

Syntax:
for (variable of iterable) {
// code block to be executed
}
variable - For every iteration the value of the next property is assigned to
the variable. Variable can be declared with const, let, or var.
iterable - An object that has iterable properties.

Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For Of Loop</h2>
<p id="car"></p>
<script>
const cars = ["BMW", "Volvo", "Nissan","VW"];
let text = "";
for (let x of cars) {
text += x + "<br>";
}
document.getElementById("car").innerHTML = text;
</script>
</body>
</html>

4. JavaScript while Loop

The while loop executes as long as the condition is true. It can be thought of
as a repeating if statement.

Syntax:

while (condition) {
// Code to execute
}

Example:

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript while loop</h2>

<script>
let count = 1;
while (count <= 5) {
console.log(count);
count++;
}

</script>
</body>
</html>
Output:
1
2
3
4
5

5. JavaScript do-while Loop

The do-while loop is similar to while loop except it executes the code block at
least once before checking the condition.

There are mainly two types of loops.

 Entry Controlled loops: The test condition is tested before entering


the loop body. For Loop and While Loops are entry-controlled loops.

 Exit Controlled Loops: The test condition is tested or evaluated at


the end of the loop body. Therefore, the loop body will execute at least
once, irrespective of whether the test condition is true or false. The do-
while loop is exit controlled loop.

Syntax:
do {
// Code to execute
} while (condition);

Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript do while loop</h2>
<script>
let test = 1;
do {
console.log(test);
test++;
} while(test<=5)
</script>
</body>
</html>
Output:
1
2
3
4
5

Nested loops.
A nested loop is a loop within another loop.
Example 1: Right-Angled Triangle Pattern
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<body> <body>
<h2>Pattern using for loop <h2>Right-Angled Triangle using while
</h2> loop </h2>
<script> <script>
let rows = let rows = parseInt(prompt("Enter the
parseInt(prompt("Enter the number of rows:"));
number of rows:")); let i = 1;
let pattern = ""; let pattern = "";

for (let i = 1; i <= rows; i++) { while (i <= rows) {


for (let j = 1; j <= i; j++) { let j = 1;
pattern += "* "; while (j <= i) {
} pattern += "* ";
pattern += "\n"; j++;
} }
console.log(pattern); pattern += "\n";
alert(pattern); i++;
}
</script> console.log(pattern);
</body> alert(pattern);
</html> </script>
</body>
</html>

Example 2: Number Pyramid


<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<body> <body>

<h2>Number Pyramid using for loop <h2>Pyramid Pattern using while Loop
</h2> </h2>
<script> <script>
let rows = parseInt(prompt("Enter the let rows = parseInt(prompt("Enter the
number of rows:")); number of rows:"));
let pattern = ""; let i = 1;
let pattern = "";
for (let i = 1; i <= rows; i++) {
for (let j = 1; j <= rows - i; j++) { while (i <= rows) {
pattern += " "; let spaces = 1;
} while (spaces <= rows - i) {
for (let k = 1; k <= i; k++) { pattern += " ";
pattern += k + " "; spaces++;
} }
pattern += "\n"; let stars = 1;
} while (stars <= 2 * i - 1) {
pattern += "*";
console.log(pattern); stars++;
alert(pattern); }
pattern += "\n";
</script> i++;
</body> }
</html> console.log(pattern);
alert(pattern);
</script>
</body>
</html>

Example 3: Diamond Pattern


<!DOCTYPE html>
<html>
<body>

<h2>Diamond Pattern using for loop </h2>


<script>
let rows = parseInt(prompt("Enter the number of rows:"));
let pattern = "";

// Upper part of the diamond


for (let i = 1; i <= rows; i++) {
for (let j = 1; j <= rows - i; j++) {
pattern += " ";
}
for (let k = 1; k <= 2 * i - 1; k++) {
pattern += "*";
}
pattern += "\n";
}

// Lower part of the diamond


for (let i = rows - 1; i >= 1; i--) {
for (let j = 1; j <= rows - i; j++) {
pattern += " ";
}
for (let k = 1; k <= 2 * i - 1; k++) {
pattern += "*";
}
pattern += "\n";
}

console.log(pattern);
alert(pattern);

</script>

</body>
</html>

JavaScript Function
These are reusable blocks of code designed to perform specific tasks. They
allow you to organize, reuse, and modularize code. It can take inputs,
perform actions, and return outputs.

Function Declarations
A Function Declaration (also known as a Function Statement) is a way
to define a function in programming. It is a statement that creates a function
with a specified name and body, allowing it to be called anywhere in the
code.

Syntax:
function functionName(parameters) {
// function body
return someValue; // (optional)
}

Example:

function sum(x, y) {
return x + y;
}
console.log(sum(2, 5));

Function Syntax and Working

A function definition is sometimes also termed a function declaration or


function statement. Below are the rules for creating a function in JavaScript:

 Begin with the keyword function followed by,


 A user-defined function name (In the above example, the name
is sum)

 A list of parameters enclosed within parentheses and separated by


commas (In the above example, parameters are x and y)

 A list of statements composing the body of the function enclosed


within curly braces {} (Such as, “return x + y”).

Return Statement
When we want to return some values from a function after performing some
operations, we make use of the return. This is an optional statement. In the
above function, “sum()” returns the sum of two as a result.

Function Parameters

Parameters are input passed to a function. In the above example, sum()


takes two parameters, x and y.

Calling Functions

After defining a function, the next step is to call them to make use of the
function. We can call a function by using the function name separated by the
value of parameters enclosed between the parenthesis.

Example 1: Functions to add two numbers


<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions to add two numbers </h2>


<script>
// Function to add two numbers
function addNumbers(a, b) {
return a + b;
}

// Taking user input


let num1 = parseFloat(prompt("Enter first number:"));
let num2 = parseFloat(prompt("Enter second number:"));

// Function call and displaying the result


let sum = addNumbers(num1, num2);
console.log("The sum is: " + sum);
alert("The sum is: " + sum);

</script>
</body>
</html>

Explanation:
1. The function addNumbers(a, b) takes two parameters and returns
their sum.
2. The prompt() function is used to take user input, which is converted to
a number using parseFloat().
3. The function is called with the user inputs as arguments.
4. The result is displayed using console.log() and alert().

Example 2: Find the Maximum of Two Numbers.

<!DOCTYPE html>
<html>
<body>

<h2>Find the Maximum of Two Numbers </h2>


<script>
// Function to find the maximum of two numbers
function findMax(a, b) {
return a > b ? a : b;
}

// Taking user input


let num1 = parseFloat(prompt("Enter first number:"));
let num2 = parseFloat(prompt("Enter second number:"));

// Function call and displaying the result


let maxNumber = findMax(num1, num2);
console.log("The larger number is: " + maxNumber);
alert("The larger number is: " + maxNumber);

</script>

</body>
</html>

Example 3:
<!DOCTYPE html>
<html>
<body>
<h2>Calculate area and circumference of circle </h2>
<script>
// Function to calculate the area of a circle
function calculateArea(radius) {
return Math.PI * radius * radius;
}

// Function to calculate the perimeter (circumference) of a circle


function calculatePerimeter(radius) {
return 2 * Math.PI * radius;
}

// Taking user input


let radius = parseFloat(prompt("Enter the radius of the circle:"));

// Function calls
let area = calculateArea(radius);
let perimeter = calculatePerimeter(radius);

// Displaying the results


console.log("The area of the circle is: " + area.toFixed(2));
console.log("The perimeter (circumference) of the circle is: " +
perimeter.toFixed(2));

alert("The area of the circle is: " + area.toFixed(2) + "\nThe perimeter is: " +
perimeter.toFixed(2));

</script>

</body>
</html>

Explanation:
1. calculateArea(radius) – Computes the area using the formula:
Area=π×r2
2. calculatePerimeter(radius) – Computes the perimeter using the
formula: Perimeter=2×π×r
3. prompt() gets the radius from the user.
4. The functions are called with the user input.
5. The results are displayed using console.log() and alert().
6. toFixed(2) rounds the output to 2 decimal places.

Why Functions?

 Functions can be used multiple times, reducing redundancy.


 Break down complex problems into manageable pieces.

 Manage complexity by hiding implementation details.

 Can call themselves to solve problems recursively.

Read more on:

Function invocation and function call. Differentiate the two as used in


JavaScript.

You might also like