0% found this document useful (0 votes)
12 views93 pages

Unit1 3

JavaScript is a versatile, dynamically typed programming language used for both client-side and server-side web development, allowing for interactive applications. It features single-threaded execution, asynchronous capabilities, and a rich ecosystem of libraries and frameworks. Key applications include web development, server applications, and game development, while it also has limitations such as security risks and performance issues.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views93 pages

Unit1 3

JavaScript is a versatile, dynamically typed programming language used for both client-side and server-side web development, allowing for interactive applications. It features single-threaded execution, asynchronous capabilities, and a rich ecosystem of libraries and frameworks. Key applications include web development, server applications, and game development, while it also has limitations such as security risks and performance issues.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 93

Java Script

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> •The<script> tag is used to include


JavaScript code inside an HTML
<head></head> document.
<body>
<h1>Check the console for the
•console.log() prints messages to the
message!</h1> browser’s developer console. Open the
<script> browser console to see the “Hello,
// This is our first JavaScript program World!” message.
console.log("Hello, World!");
</script>
</body>
</html>
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 , VueJS which make development faster
and more efficient.
Client Side and Server Side nature of JavaScript
•Client-side: Involves controlling the browser and its 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.
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.
<html>
<head></head>
<body>
<h2>
Adding JavaScript in HTML Document
</h2>
<button onclick="alert('Button Clicked!')">
Click Here
</button>
</body>
</html>
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.
<body>
<html> <h2>
<head> Add JavaScript Code
<script> inside Head Section
function myFun() { </h2>
document.getElementById("demo") <h3 id="demo" style="color:green;">
.innerHTML = "Content changed!"; Computer Multimedia and animation
} </h3>
</script> <button type="button" onclick="myFun()">
</head> Click Here
</button>
</body>
</html>
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.

<button type="button" onclick="myFun()">


Click Here
<html> </button>
<head></head> <script>
<body> function myFun() {
<h2> document.getElementById("demo")
Add JavaScript Code .innerHTML = "Content changed!";
inside Body Section }
</h2> </script>
<h3 id="demo" style="color:green;"> </body>
Computer Multimedia and animation </html>

</h3>
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>
<head> /* Filename: script.js*/
<script src="script.js"></script>
function myFun () {
</head> document.getElementById('demo')
<body> .innerHTML = 'Content Changed'
<h2> }
External JavaScript
</h2>
<h3 id="demo" style="color:green;">
Computer Multimedia and animation
</h3>
<button type="button" onclick="myFun()">
Click Here
</button>
</body>
</html>
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.
JavaScript Syntax

Syntax

console.log("Basic Print method in JavaScript");

// Variable declaration
let c, d, e;

// Assign value to the variable


c = 5;

// Computer value of variables


d = c; e = c / d;
JavaScript Values
There are two types of values defined in JavaScript Syntax:

•Fixed Values: These are known as the literals.


•Variable values: These are called variables

JavaScript Literals

Syntax Rules for the JavaScript fixed values are:


•JavaScript Numbers can be written with or without decimals.
•Javascript Strings are text that can be written in single or double quotes.
let num1 = 50
let num2 = 50.05

let str1 = “bca"


let str2 = ‘CMA'

console.log(num1)
Output:
console.log(num2)
console.log(str1) 50
50.05
console.log(str2) bca
CMA
Java Script Primitives
Primitive and Non-primitive data-types in JavaScript

Variables hold values, and every value has a specific


data type that defines the kind of information it
holds.
These data types are broadly categorized into two
groups:
Primitive Data Types and Non-Primitive Data Types.
1. Primitive Data Types
Primitive data types are the built-in data types provided by
JavaScript. They represent single values and are not
mutable. JavaScript supports the following primitive data
types:
Number:
Number data type in JavaScript can be used to hold
decimal values as well as values without decimals.
let x = 250;
let y = 40.5; Output
console.log("Value of x=" + x); Value of x=250
console.log("Value of y=" + y); Value of y=40.5
String:
The string data type in JavaScript represents a sequence of
characters that are surrounded by single or double quotes.

let str = 'Hello All';


let str1 = "Welcome to my new house";
console.log("Value of str=" + str);
console.log("Value of str1=" + str1);

output
Value of str=Hello All
Value of str1=Welcome to my new house
Undefined:
This means that a variable has been declared but has not been assigned a
value, or it has been explicitly set to the value `undefined`.

let x;
console.log(x); // Outputs: undefined

Boolean:
The boolean data type can accept only two values i.e. true and
false.

let x;
console.log(x); // Outputs: undefined
Null:
This data type can hold only one possible value that is null.

let x = null;
console.log("Value of x=" + x); Output
Value of x=null

BigInt:
BigInt data type can represent numbers greater than 253-1 which helps to perform
operations on large numbers. The number is specified by writing ‘n’ at the end of
the value
let bigNum = 123422222222222222222222222222222222222n
console.log(bigNum)

Output
123422222222222222222222222222222222222n
Symbol:

Symbol data type is used to create objects which will always be


unique. these objects can be created using Symbol constructor.

let sym = Symbol("Hello")


console.log(typeof(sym));
console.log(sym);

Output
symbol Symbol(Hello)
2.Non-primitive Data Types
Non-primitive data types, also known as reference types,
are objects and derived data types. They can store
collections of values or more complex entities. The two
key non-primitive data types in JavaScript are:
Below is a list of Non-primitive data types.

Object:
An object in Javascript is an entity having properties and methods.
Everything is an object in javascript.
How to create an object in javascript:
•Using Constructor Function to define an object:
// Create an empty generic object
let obj = new Object();

// Create a user defined object


let mycar = new Car();
•Using Literal notations to define an object:
// An empty object
let square = {};

// Here a and b are keys and


// 20 and 30 are values
let circle = {a: 20, b: 30};
// Creating object with the name person
let person = {
firstName: “Shiv",
lastName: “Shankar",
};

// Print the value of object on console


console.log(person.firstName
+ " " + person.lastName);

Output
Shiv Shankar
Array:
With the help of an array, we can store more than one
element under a single name.
Ways to declare a single-dimensional array:
// Call it with no arguments
let a = new Array();

// Call it with single numeric argument


let b = new Array(10);

// Explicitly specify two or


// more array elements
let d = new Array(1, 2, 3, "Hello");
Difference Between Primitive vs Non-Primitive

Primitive Non-Primitive
Non-Primitive data types
Primitive Data types are
are created by the
predefined.
programmer

Primitive Data types will Non-Primitive data types


have certain values. can be NULL.

Size depends on the type


Size is not fixed
of data structure.

Examples are numbers Examples are Array and


and strings. Linked List.

It can start with a It can start with


lowercase. uppercase.
Mouse events:
Window/Document events
length
The length Property
The length property returns the length of an array:
4
The toString() Method
The toString() method returns an array as a comma separated
string:
Banana,Orange,Apple,Mango
The at() method returns an indexed element from an array.
The at() method returns the same as [].

The at() Method


The at() method returns an indexed element from an array:
Apple

You might also like