0% found this document useful (0 votes)
8 views18 pages

Chapter 4 Javascript

Chapter 4 introduces JavaScript as a versatile, dynamically typed programming language essential for web development, supporting both client-side and server-side applications. It covers key features, programming paradigms, and various methods to integrate JavaScript into HTML, along with control statements and loops for effective coding. The chapter also discusses JavaScript's limitations and its lightweight nature, emphasizing its efficiency and popularity in modern web applications.

Uploaded by

e9923144
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views18 pages

Chapter 4 Javascript

Chapter 4 introduces JavaScript as a versatile, dynamically typed programming language essential for web development, supporting both client-side and server-side applications. It covers key features, programming paradigms, and various methods to integrate JavaScript into HTML, along with control statements and loops for effective coding. The chapter also discusses JavaScript's limitations and its lightweight nature, emphasizing its efficiency and popularity in modern web applications.

Uploaded by

e9923144
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Chapter 4

Introduction to JavaScript

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 used in millions of Web pages to improve
the design, validate forms, detect browsers, create cookies, and much more. JavaScript is the most
popular scripting language on the Internet, and works in all major browsers, such as Internet Explorer,
Mozilla Firefox, and Opera.
 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

alert("Hello, World!");

</script>

</body>
</html>
The out put

In this example
 The<script> tag is used to include JavaScript code inside an HTML document.
 alert() prints messages. Open the browser console to see the “Hello, World!” message.
To learn more about it follow the article – JavaScript Hello World
[Link]("Hello, World!"); // Prints Hello, World! to the console
In this example
 [Link](): The [Link]() 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:
o Multi-line Comment: The /* */ syntax is used to write a comment spanning
multiple lines.
o Single-line Comment: The // syntax is used for short, inline comments, like the
one explaining the [Link] function.
To learn more about comments follow the article – Comments in JavaScript
Key Features of JavaScript
Here are some key features of JavaScript that make it a powerful language for web development:
 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 [Link], which make development faster and more efficient.
Client Side and Server-Side nature of JavaScript
JavaScript’s flexibility extends to both the client-side and server-side, allowing developers to create
complete web applications. Here’s how it functions in each environment:
Client-Side:
 Involves controlling the browser and its DOM (Document Object Model).
 Handles user events like clicks and form inputs.
 Common libraries include AngularJS, ReactJS, and VueJS.
Server-Side:
 Involves interacting with databases, manipulating files, and generating responses.
 [Link] and frameworks like [Link] are widely used for server-side JavaScript, enabling
full-stack development.
Programming Paradigms in JavaScript
JavaScript supports both imperative and declarative programming styles:
 Imperative Programming: Focuses on how to perform tasks by controlling the flow of
computation. This includes approaches like procedural and object-oriented programming,
often using constructs like async/await to handle asynchronous actions.
 Declarative Programming: Focuses on what should be done rather than how it’s done. It
emphasizes describing the desired result, such as with arrow functions, without detailing the
steps to achieve it.
Applications of JavaScript
JavaScript is used in a wide range of applications, from enhancing websites to building complex
applications. Here are some examples:
 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: [Link] 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
Despite its power, JavaScript has some limitations to consider:
 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 [Link], 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. You can learn it
through tutorials and examples.
Just-In-Time (JIT) compilation is a technique used by JavaScript engines (like V8) to improve
performance. Here’s 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).
How to Add 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.
Inline JavaScript
You can write JavaScript code directly inside the HTML element using the onclick, onmouseover, or
other event handler attributes.
<button onclick="alert('Button Clicked!')">
Click Here
</button>
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.
1. 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.

<head>

<script>

function myFun() {

[Link]("demo")

.innerHTML = "Content changed!";


}
</script>
</head>

2. 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.
<body>
<h2>
Add JavaScript Code
inside Body Section
</h2>
<h3 id="demo" style="color:green;">
Html java script for It 2nd year.
</h3>
<button type="button" onclick="myFun()">
Click Here
</button>
<script>
function myFun() {
[Link]("demo")
.innerHTML = "Content changed!";
}
</script>
</body>
output

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.
Control Statements
JavaScript control statement is used to control the execution of a program based on a specific condition.
If the condition meets then a particular block of action will be executed otherwise it will execute another
block of action that satisfies that particular condition.
Types of Control Statements in JavaScript Conditional Statement: These statements are used for decision-
making, a decision n is made by the conditional statement based on an expression that is passed. Either
YES or NO.
Iterative Statement:
This is a statement that iterates repeatedly until a condition is met. Simply said, if we have an expression,
the statement will keep repeating itself until and unless it is satisfied. There are several methods that can
be used to perform control statements in JavaScript:
Table of Content
If Statement Using If-Else Statement Using Switch Statement Using the Ternary Operator (Conditional
Operator) Using For loop Approach 1:
If Statement In this approach, we are using an if statement to check a specific condition, the code block
gets executed when the given condition is satisfied.
Syntax:
if ( condition_is_given_here )
{ // If the condition is met, //the code will get executed. }
Example: In this example, we are using an if statement to check our given condition.
const num = 5;
if (num > 0)
{
[Link]("The number is positive.");
};
Output
The number is positive.
Approach 2: Using If-Else Statement The if-else statement will perform some action for a specific
condition. If the condition meets then a particular code of action will be executed otherwise it will
execute another code of action that satisfies that particular condition.
Syntax:
if (condition1)
{ // Executes when condition1 is true if (condition2)
{ // Executes when condition2 is true } }
Example: In this example, we are using the if..else statement to verify whether the given number is
positive or negative.
let num = -10;
if (num > 0)
[Link]("The number is positive.");
else
[Link]("The number is negative");
Output
The number is negative
Approach 3: Using Switch Statement The switch case statement in JavaScript is also used for decision-
making purposes. In some cases, using the switch case statement is seen to be more convenient than if-
else statements.
Syntax: switch (expression)
{
case value1:
statement1;
break;
case value2: statement2;
break; .
case valueN:
statementN;
break; default:
statement
Default;
} Example: In this example, we are using the above-explained approach. If you enter 2 the the out put of
this program is
let num = 5;
switch (num)
{
case 0:
[Link]("Number is zero.");
break;
case 1:
[Link]("Nuber is one.");
break;
case 2:
[Link]("Number is two.");
break;
default:
[Link]("Number is greater than 2.");
}
Output
Nuber is two.
Approach 4: Using the Ternary Operator (Conditional Operator)
The conditional operator, also referred to as the ternary operator (?:), is a shortcut for expressing
conditional statements in JavaScript.
Syntax: condition ? value if true : value if false
Example: In this example, we are using the ternary operator to find whether the given number is positive
or negative.
let num = 10;
let result = num >= 0 ? "Positive" : "Negative";
[Link](The number is ${result}.);
Output The number is Positive.

JavaScript for loop


The for loop continuously execute a block of code to a set number of times.
for (let i = 1; i <= 5; i++) {
[Link](i);
}

Output
1
2
3
4
5
 Initializes i with 1 and checks if i <= 5.
 Executes the [Link] statement and increments i by 1 in each iteration.
 Stops the loop when i exceeds 5.
JavaScript while loop
The while loop repeats a block of code as long as the condition is true.
let i = 1;
while (i <= 5) {
[Link](i);
i++;
}

Output
1
2
3
4
5
 Starts with i = 1 and checks if i <= 5.
 Logs the value of i and increments it by 1 after each iteration.
 Stops the loop when i exceeds 5.
JavaScript do...while loop
The do...while loop executes the block of code at least once before checking the condition.
let i = 1;
do {
[Link](i);
i++;
} while (i <= 5);

Output
1
2
3
4
5
 Executes [Link] statement once, even if the condition is false.
 Continues looping until the condition i <= 5 is no longer true.
3. Branching Statements
JavaScript return Statement
The return statement is used to end the execution of a function and optionally return a value to the
function caller.
function add(a, b) {
return a + b;
}
const res = add(5, 3);
[Link](res);

Output
8
In this example
 return n1 + n2 ends the function and sends the sum of a and b back to the caller.
 The returned value is stored in the result.
JavaScript break Statement
The break statement is used to exit a loop or switch statement prematurely.
for (let i = 1; i <= 5; i++) {
if (i === 3)
break;
[Link](i);
}

Output
1
2
 It will log 1 and 2 to the console.
 Exits the loop when i equals 3.
JavaScript continue Statement
The continue statement skips the current iteration of a loop and proceeds to the next one.
for (let i = 1; i <= 5; i++) {
if (i === 3) continue;
[Link](i);
}

Output
1
2
4
5
 It will skip logging when i equals 3.
 Logs 1, 2, 4, and 5 to the console.
4. Switching Statements
JavaScript switch Statement
The switch statement evaluates an expression and executes a block of code based on matching cases. It
provides an alternative to long if-else chain.
const day = "Monday";
switch (day) {
case "Monday":
[Link]("Start of the week.");
break;
case "Friday":
[Link] ("End of the workweek.");
break;
default:
[Link] ("It's a regular day.");
}

Output
Start of the week.
 Checks the value of day and matches it to a case.
 [Link] "Start of the week." if day is "Monday".
 [Link] "End of the workweek." if day is "Friday".
 [Link] "It's a regular day." if no cases match.
Uses of Control Flow Statements
Control flow statements are backbone in programming for
 Decision-Making: To execute specific blocks of code based on conditions (e.g., if,
if...else).
 Branching: To exit loops or skip iterations (break, continue).
 Looping: To repeat tasks (for, while, do...while).
 Switching: To handle multiple conditions effectively (switch).
JavaScript Loops
Loops in JavaScript 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.
Suppose we want to print ‘Hello World’ five times. Instead of manually writing the print statement
repeatedly, we can use a loop to automate the task and execute it based on the given condition.
for (let i = 0; i < 5; i++) {
[Link]("Hello World!");
}

Output
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Let’s now discuss the different types of loops available in JavaScript
1. JavaScript for Loop
The for loop repeats a block of code a specific number of times. It contains initialization, condition, and
increment/decrement in one line.
Syntax
for (initialization; condition; increment/decrement) {
// Code to execute
}

for (let i = 1; i <= 3; i++) {


[Link]("Count:", i);
}

Output
Count: 1
Count: 2
Count: 3
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. 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
}
let i = 0;
while (i < 3) {
[Link]("Number:", i);
i++;
}

Output
Number: 0
Number: 1
Number: 2
In this example
 Initializes the variable (let i = 0).
 Runs the loop body while the condition (i < 3) is true.
 Increments the counter after each iteration (i++).
3. 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.
Syntax
do {
// Code to execute
} while (condition);
let i = 0;
do {
[Link]("Iteration:", i);
i++;
} while (i < 3);

Output
Iteration: 0
Iteration: 1
Iteration: 2
In this example:
 Executes the code block first.
 Checks the condition (i < 3) after each iteration.
4. JavaScript for-in Loop
The for…in loop is used to iterate over the properties of an object. It only iterate over keys of an object
which have their enumerable property set to “true”.
Syntax
for (let key in object) {
// Code to execute
}
const obj = { name: "Ashetu", age: 25 };
for (let key in obj) {
[Link](key, ":", obj[key]);
}

Output
name : Ashetu
age : 25
In this example:
 Iterates over the keys of the person object.
 Accesses both keys and values.
5. JavaScript for-of Loop
The for…of loop is used to iterate over iterable objects like arrays, strings, or sets. It directly iterates the
value and has more concise syntax than for loop.
Syntax
for (let value of iterable) {
// Code to execute
}
let a = [1, 2, 3, 4, 5];
for (let val of a) {
[Link](val);
[Link]("<br />");
}

Output
1
2
3
4
5
Choosing the Right Loop
 Use for loop when the number of iterations is known.
 Use while loop when the condition depends on dynamic factors.
 Use do-while loop to ensure the block executes at least once.
 Use for…in loop to iterate over object properties.
 Use for…of loop for iterating through iterable objects

Variables and Datatypes in JavaScript

Variables and data types are foundational concepts in programming, serving as the building blocks for
storing and manipulating information within a program. In JavaScript, getting a good grasp of these
concepts is important for writing code that works well and is easy to understand.
Variables A variable is like a container that holds data that can be reused or updated later in the program.
In JavaScript, variables are declared using the keywords var, let, or const.
you can use the below keyword to define variables in JavaScript.

var
let
const
var Keyword The var keyword is used to declare a variable. It has a function-scoped or globally-scoped
behavior.
var n = 5;
[Link](n);
var n = 20; // reassigning is allowed
[Link](n);
Output 5 20
let Keyword
The let keyword is introduced in ES6, has block scope and cannot be re-declared in the same scope.
let n= 10;
2
n = 20; // Value can be updated
3
// let n = 15; //can not redeclare
4
[Link](n)

Output
20
3. const Keyword
The const keyword declares variables that cannot be reassigned. It’s block-scoped as well.
1
const n = 100;
2
// n = 200; This will throw an error
3
[Link](n)

Output
100
For more details read the article – JavaScript Variables
Data Types
JavaScript supports various datatypes, which can be broadly categorized into primitive and non-
primitive types.
Primitive Datatypes
Primitive datatypes represent single values and are immutable.
1. Number: Represents numeric values (integers and decimals).
let n = 42;
let pi = 3.14;
2. String: Represents text enclosed in single or double quotes.
let s = "Hello, World!";
3. Boolean: Represents a logical value (true or false).
let bool= true;
4. Undefined: A variable that has been declared but not assigned a value.

let notAssigned;
2
[Link](notAssigned);

Output
undefined
5. Null: Represents an intentional absence of any value.
let empty = null;
6. Symbol: Represents unique and immutable values, often used as object keys.
let sym = Symbol('unique');
7. BigInt: Represents integers larger than Number.MAX_SAFE_INTEGER.
let bigNumber = 123456789012345678901234567890n;
Non-Primitive Datatypes
Non-primitive types are objects and can store collections of data or more complex entities.
1. Object: Represents key-value pairs.
let obj = {
name: "Amit",
age: 25
};
2. Array: Represents an ordered list of values.
let a = ["red", "green", "blue"];
3. Function: Represents reusable blocks of code.
function fun() {
[Link]("Hello Javascript");
}

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.

There are various operators supported by JavaScript.


1. JavaScript Arithmetic Operators
Arithmetic Operators perform mathematical calculations like addition, subtraction, multiplication, etc.
1
const sum = 5 + 3; // Addition
2
const diff = 10 - 2; // Subtraction
3
const p = 4 * 2; // Multiplication
4
const q = 8 / 2; // Division
5
[Link](sum, diff, p, q);
Output
8884
 + adds two numbers.
 – subtracts the second number from the first.
 * multiplies two numbers.
 / divides the first number by the second.
2. JavaScript Assignment Operators
Assignment operators are used to assign values to variables. They can also perform operations like
addition or multiplication before assigning the value.
let n = 10;
n += 5;
n *= 2;
[Link](n);

Output
30
 = assigns a value to a variable.
 += adds and assigns the result to the variable.
 *= multiplies and assigns the result to the variable.
3. JavaScript Comparison Operators
Comparison operators compare two values and return a boolean (true or false). They are useful for
making decisions in conditional statements.
[Link](10 > 5);
[Link] (10 === "10");

Output
true
false
 > checks if the left value is greater than the right.
 === checks for strict equality (both type and value).
 Other operators include <, <=, >=, and !==.
4. JavaScript Logical Operators
Comparison operators are mainly used to perform the logical operations that determine the equality or
difference between the values.
const a = true, b = false;
[Link] (a && b); // Logical AND
[Link] (a || b); // Logical OR

Output
false
true
 && returns true if both operands are true.
 || returns true if at least one operand is true.
 ! negates the boolean value.
5. JavaScript Bitwise Operators
Bitwise operators perform operations on binary representations of numbers.
const res = 5 & 1; // Bitwise AND
[Link](res);

Output
1
 & performs a bitwise AND.
 | performs a bitwise OR.
 ^ performs a bitwise XOR.
 ~ performs a bitwise NOT.
6. JavaScript Ternary Operator
The ternary operator is a shorthand for conditional statements. It takes three operands.
const age = 18;
const status = age >= 18 ? "Adult" : "Minor";
[Link](status);
Output
Adult
condition ? expression1 : expression2 evaluates expression1 if the condition is true, otherwise evaluates
expression2.
7. JavaScript Comma Operator
Comma Operator (,) mainly evaluates its operands from left to right sequentially and returns the value
of the rightmost operand.
let n1, n2
const res = (n1 = 1, n2 = 2, n1 + n2);
[Link](res);

Output
3
 Each expression is evaluated from left to right.
 The final result of the expression is the rightmost value.
8. JavaScript Unary Operators
Unary operators operate on a single operand (e.g., increment, decrement).
let x = 5;
[Link] (++x); // Pre-increment
[Link] (x--); // Post-decrement (Output: 6, then x becomes 5)

Output
6
6
 ++ increments the value by 1.
 — decrements the value by 1.
 typeof returns the type of a variable.
9. JavaScript Relational Operators
JavaScript Relational operators 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.
1
const obj = { length: 10 };
[Link]("length" in obj);
[Link]([] instanceof Array);
Output
true
true
 in checks if a property exists in an object.
 instanceof checks if an object is an instance of a constructor.
10. JavaScript BigInt Operators
BigInt operators allow calculations with numbers beyond the safe integer range.
const big1 = 123456789012345678901234567890n;
const big2 = 987654321098765432109876543210n;
[Link](big1 + big2);

Output
1111111110111111111011111111100n
 Operations like addition, subtraction, and multiplication work with BigInt.
 Use n suffix to denote BigInt literals.
11. JavaScript String Operators
JavaScript String Operators include concatenation (+) and concatenation assignment (+=), used to join
strings or combine strings with other data types.
const s = "Hello" + " " + "World";
[Link] (s);

Output
Hello World
 + concatenates strings.
 += appends to an existing string.
12. JavaScript Chaining Operator (?.)
The optional chaining operator allows safe access to deeply nested properties without throwing errors if
the property doesn’t exist.
const obj = { name: "Aman", address: { city: "Addis Abeba" } };
[Link]([Link]?.city);
[Link] ([Link]?.phone);

You might also like