[Go to site: main page, start]

0% found this document useful (0 votes)
15 views9 pages

Introduction to JavaScript Basics

Uploaded by

kumpatlachinna22
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)
15 views9 pages

Introduction to JavaScript Basics

Uploaded by

kumpatlachinna22
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

JAVA SCRIPT

What is JavaScript?

JavaScript (JS) is a high-level, interpreted programming language used to make web pages interactive.
It is one of the core technologies of the web, along with HTML (structure) and CSS (style).

Key Features of JavaScript

✔ Client-Side Scripting – Runs in the browser, making websites dynamic.


✔ Interpreted Language – Does not need compilation; browsers execute it directly.
✔ Lightweight & Fast – Designed for quick execution in web applications.
✔ Object-Oriented – Uses objects for flexibility and code reusability.
✔ Event-Driven & Asynchronous – Handles user actions and supports APIs like AJAX for real-time
updates.
✔ Cross-Platform – Works on all major browsers (Chrome, Firefox, Edge, etc.).

How JavaScript Works in a Web Page

When a web page loads, the browser’s JavaScript engine executes the JS code. It can:
Manipulate HTML and CSS
Handle user events (clicks, input, scrolling, etc.)
Communicate with servers (fetch data, send requests)
Store data locally (cookies, local storage)

Basic HTML instructions

1️. alert() Function


• The alert() function displays a pop-up message (alert box) in the browser.
• It is used to show important notifications or warnings to the user.
EX: alert("Hello, welcome to JavaScript!"); ⏎

2. Math Operations
• It performs the basic mathematical operations
EX: 2+2 ⏎

3. [Link] = 'text'; ⏎
• [Link] modifies the entire HTML content inside the <body> tag.
• It overwrites everything currently in the body of the webpage.

4. prompt() (Taking User Input)


• prompt() displays a dialog box asking the user to enter a value.
• Returns the input as a string.
EX: prompt("Enter your name:"); ⏎

5. confirm() (Getting User Confirmation)


shows a dialog box with "OK" and "Cancel".
Returns:
• true → If the user clicks OK
• false → If the user clicks Cancel
EX: confirm("Do you want to continue?"); ⏎

6. [Link]() (Writing Directly to the Page)


• [Link]() directly writes content into the webpage.
• It replaces everything in the <body> if called after the page loads.
EX: [Link]("Hello, World!"); ⏎

Feature [Link] [Link]()


When Used After the page loads Before/during page load
Replaces entire document after
Effect Modifies existing HTML
load
Preserves Other No (erases everything if used after
Yes (modifies body only)
Elements? load)
Update part of the webpage
Use Case Write static content when loading
dynamically

USING THE JAVA SCRIPT WITH HTML

Ways to Use JavaScript in HTML


JavaScript can be added to an HTML document in three main ways:
1️.Inline JavaScript (Inside HTML elements)
[Link] JavaScript (Inside <script> tag in the HTML file)
3️.External JavaScript (Using a separate .js file and linking it to HTML)

1️.Inline JavaScript (Inside HTML Elements)


JavaScript code is written directly inside an HTML tag using event attributes such as onclick,
onmouseover, etc.
Suitable for small actions like handling button clicks, alerts, etc.
Syntax:
<element event="JavaScript code">

• <element> → Any HTML tag (e.g., <button>, <a>, <p>)


• event → JavaScript event (e.g., onclick, onmouseover, onload)
• JavaScript code → The JavaScript action that executes when the event occurs

[Link] JavaScript (Inside <script> Tag in HTML)


JavaScript is written inside a <script> tag within the same HTML document.
Ideal for page-specific scripts where JavaScript interacts with multiple elements on the same page.
Syntax:
<script>
// JavaScript code here
</script>

• <script> → Defines a JavaScript block inside the HTML document.


• JavaScript code → Any valid JavaScript statements, functions, or variables.

Example Placement:
<head>
<script>
// JavaScript function that runs when called
function showMessage() {
alert("Hello from JavaScript!");
}
</script>
</head>
<body>
<button Me</button>
</body>

[Link] JavaScript (Using a .js File)


JavaScript is written in a separate file with a .js extension and linked to an HTML file.
Best for large scripts, reusability, and cleaner HTML structure.

Step 1️: Create an External JavaScript File (file name : [Link])


// JavaScript function
function showMessage() {
alert("Hello from an external JavaScript file!");
}

Step 2: Link the JavaScript File in HTML


<!DOCTYPE html>
<html>
<head>
<title>External JavaScript Example</title>
<script src="[Link]"></script> <!-- Linking external JS file -->
</head>
<body>
<button Me</button>
</body>
</html>

• <script> → Defines JavaScript inclusion in HTML.


• src="[Link]" → Specifies the external JavaScript file to be loaded.

JavaScript Variables: (let, var, and const)


• JavaScript provides three ways to declare variables:
1️.var – The old way (function-scoped, can be re-declared).
[Link] – The modern way (block-scoped, cannot be re-declared).
3️.const – For constant values (block-scoped, cannot be changed).
Feature var let const

Scope Function-scoped Block-scoped Block-scoped

Can Be Re-
Yes No No
declared?

Can Be Updated? Yes Yes No

Avoid using in modern Preferred for variables that Preferred for


Use Case
JS change constants

1️. var (Function-Scoped, Can Be Re-declared)

• Declares a variable that can be re-declared and updated.


• Function-scoped → Accessible only inside the function where it is declared.
• Does NOT have block scope → Accessible outside {} blocks (e.g., if, for).
• Avoid var in modern JavaScript due to unpredictable behavior.
Syntax:

var variable_name = "str"; // Declaring a variable


var variable_name = "str"; // Re-declaring (Allowed)
name = "str"; // Updating (Allowed)

Function Scope Example:


function test() {
var x = 1️0;
[Link](x); // Output: 1️0
}
[Link](x); // Error: x is not defined (because var is function-scoped)

No Block Scope Example:


if (true) {
var y = 20;
}
[Link](y); // Output: 20 (var is not limited to the if block)

2. let (Block-Scoped, Cannot Be Re-declared)


• Declares a variable that can be updated but NOT re-declared.
• Block-scoped → Only accessible inside {} where it is defined.
• Use let instead of var for better control over variable scope.
let variable_name = value; // Declaring a variable
variable_name = value; // Updating (Allowed)
let variable_name = value; // Error: Cannot re-declare in the same scope

Block Scope Example:


if (true) {
let a = 50;
[Link](a); // Output: 50
}
[Link](a); // Error: a is not defined (because let is block-scoped)

3️. const (Block-Scoped, Cannot Be Changed)


• Declares a constant that cannot be updated or re-declared.
• Block-scoped → Like let, it is only accessible inside {}.
• Must be assigned a value when declared.

Syntax:
const PI = 3️.1️4; // Declaring a constant
PI = 3️.1️41️5; // Error: Cannot reassign a constant
const PI = 3️.1️5; // Error: Cannot re-declare a constant

Block Scope Example:


if (true) {
const b = 1️00;
[Link](b); // Output: 1️00
}
[Link](b); // Error: b is not defined (because const is block-scoped)

Objects and Arrays with const


• const prevents reassignment, but objects and arrays can still be modified.
const person = { name: "John" };
[Link] = "Doe"; // Allowed (modifying property)
person = { age: 3️0 }; // Error (cannot reassign a new object)

When to Use What?


Use let → When a variable needs to be updated later.
Use const → For values that should never change (e.g., API keys, Pi, etc.).
Avoid var → Unless maintaining older code.

Numbers and Math functions

Function Description Example Output


[Link]() Absolute value [Link](-1️0) 1️0
[Link]() Rounds to nearest integer [Link](4.7) 5
[Link]() Rounds up [Link](4.2) 5
[Link]() Rounds down [Link](4.8) 4
[Link]() Square root [Link](1️6) 4
[Link]() Power [Link](2, 3️) 8
[Link]() Smallest number [Link](1️0, 5, 20) 5
[Link]() Largest number [Link](1️0, 5, 20) 20
[Link]() Random number (0-1️) [Link]() 0.1️23️4...
Function Description Example Output
[Link]() Removes decimal part [Link](4.8) 4
[Link]() Sine value [Link]([Link] / 2) 1️
[Link]() Cosine value [Link](0) 1️
[Link]() Tangent value [Link]([Link] / 4) 1️
[Link]() Natural logarithm [Link](1️0) 2.3️02
[Link]() Exponential (e^x) [Link](2) 7.3️89
[Link]() Cube root [Link](27) 3️
[Link]() Sign of number [Link](-1️0) -1️

JavaScript Operator Precedence Table


Operator precedence determines the order in which operations are performed. Higher precedence
operators are executed first.

Precedence Operator Type Associativity Example


1️ (Highest) () Grouping N/A (2 + 3️) * 4 → 20
2 ** Exponentiation Right to Left 2 ** 3️ → 8
Multiplication, Division,
3 *, /, % Left to Right 1️0 / 2 * 5 → 25
Modulus
4 +, - Addition, Subtraction Left to Right 1️0 - 5 + 3️ → 8
x = y = 5 (Assigns 5 to y, then
5 (Lowest) = Assignment Right to Left
x)

Handling The Floating Points Errors


Procedure to Handle Floating-Point Precision Using Multiply & Divide Method
1️. Identify the highest decimal places in the given numbers.
2. Multiply each number by 1️0^n (where n is the maximum decimal places) to convert them
into whole numbers.
3️. Perform the mathematical operation (addition, subtraction, multiplication, or division).
4. Divide the result by 1️0^n to restore the correct scale.

Examples of All Four Operations Using Different Floating-Point Numbers


Incorrect Calculation
Operation Correct Calculation (Multiply & Divide Method)
(Floating-Point Issue)
Addition (2.3️ + 2.3️ + 3️.45 =
(2.3️ * 1️00 + 3️.45 * 1️00) / 1️00 = 5.75
3️.45) 5.750000000000001️
Subtraction (3️4.56 3️4.56 - 6.43️2 =
(3️4.56 * 1️000 - 6.43️2 * 1️000) / 1️000 = 28.1️28
- 6.43️2) 28.1️27999999999997
Multiplication (2.3️ 2.3️ * 3️.45 = (2.3️ * 1️00) * (3️.45 * 1️00) / (1️00 * 1️00) = 7.93️5
* 3️.45) 7.93️4999999999999
Incorrect Calculation
Operation Correct Calculation (Multiply & Divide Method)
(Floating-Point Issue)
((3️4.56 * 1️000) / (6.43️2 * 1️000)) =
Division (3️4.56 / 3️4.56 / 6.43️2 =
5.3️72023️809523️81️ (Same result, but without
6.43️2) 5.3️72023️809523️81️
precision errors)

typeof()

typeof is an operator that tells you what kind of data a variable holds. You can think of it as a tool to
check the “label” on your variable.
For example:
• If you have a number:
let num = 42;
[Link](typeof num); // "number"
Here, typeof num returns "number" because 42 is a number.

Datatypes:

Data Type Category Description Example & Code Snippet


"Hello, World!"
String Primitive Represents textual data
let greeting = "Hello, World!";
Represents numeric values (integers and 42
Number Primitive
decimals) let age = 42;
Represents a logical value, either true or true
Boolean Primitive
false let isActive = true;
Indicates a variable declared without an undefined
Undefined Primitive
assigned value let x; // x is undefined
Represents an explicitly empty or non- null
Null Primitive
existent value let y = null;
Creates a unique and immutable identifier, Symbol("id")
Symbol Primitive
often used as object keys let sym = Symbol("id");
1️23️45678901️23️4567890n
Represents integers with arbitrary
BigInt Primitive let bigNum =
precision, useful for large numbers
1️23️45678901️23️4567890n;
{ name: "Alice", age: 25 }
Used to store collections of data and more
Object Object let person = { name: "Alice", age:
complex entities
25 };
A special type of object for storing ordered [1️, 2, 3️]
Array Object
collections of values let numbers = [1️, 2, 3️];
A callable block of code (functions are also
Function Object function greet() { return "Hi"; }
objects)
Each data type serves a specific purpose in JavaScript, helping you manage different kinds of values
in your code.
Operators
In programming, an operator is a symbol or keyword that tells the computer to perform a specific
operation on one or more operands (values or variables). Think of operators as instructions for tasks
such as arithmetic calculations, comparisons, and logical operations.

Operator
Operators Description Example
Category
Perform mathematical operations: addition,
+, -, *, /, %, 5 + 3️ // returns 8
Arithmetic subtraction, multiplication, division,
** 2 ** 3️ // returns 8
modulus (remainder), and exponentiation.
Assign values to variables, with compound
=, +=, -=, *=, let x = 5;
Assignment operators that combine arithmetic and
/=, %= x += 3️; // x becomes 8
assignment.
Compare two values. The double equals
==, ===, !=,
(==) and not equals (!=) perform type 5 == "5" // true
Comparison !==, >, <, >=,
conversion, while triple equals (===) and 5 === "5" // false
<=
not equals (!==) check for strict equality.
Logical &&, ` , !`
Operate on the binary
Bitwise &, ` , ^, ~, <<, >>, >>>` representations of
numbers at the bit level.
Operate on a single operand. Examples
typeof, void, include getting the type of a value, deleting typeof "hello" // returns
Unary
delete, +, - a property, or converting a value to a "string"
number.
A shorthand for an if-else statement. It
Ternary evaluates a condition and returns one of let result = (age >= 1️8) ?
?:
(Conditional) two values depending on whether the "adult" : "minor";
condition is true or false.

Typecasting
Type casting (or type conversion) in JavaScript is the process of converting a value from one data type
to another. There are two main forms of type conversion:
1️. Implicit Conversion:
JavaScript automatically converts types when needed. For example, when adding a number
to a string, the number is implicitly converted to a string.

let result = "The number is " + 5; // "The number is 5"


2. Explicit Conversion:
You can manually convert values using built-in functions. For example, converting a string to
a number using the Number() function:

let str = "42";


let num = Number(str); // num is now the number 42
[Link](num + 8); // Outputs: 50
predefined functions for explicit conversions
Conversion
Description Example Code
Function
String() Converts a value to a string. String(1️23️) returns "1️23️"
Number() Converts a value to a number. Number("456") returns 456
Boolean() Converts a value to a boolean. Boolean(0) returns false
Parses a string and returns an
parseInt() integer. You can also specify the radix parseInt("1️0", 1️0) returns 1️0
(base).
Parses a string and returns a floating-
parseFloat() parseFloat("1️0.5") returns 1️0.5
point number.
Converts a value to a BigInt for
BigInt("1️23️45678901️23️4567890") returns
BigInt() representing whole numbers with
1️23️45678901️23️4567890n
arbitrary precision.

Taking input from the user:


1️. Using prompt() (for simple text input)

let name = prompt("Enter your name:");


[Link]("Hello, " + name);
• prompt() opens a dialog box where the user can enter text.
• The input is always returned as a string.

2. Using confirm() (for Yes/No confirmation)

let isConfirmed = confirm("Do you want to proceed?");


[Link](isConfirmed ? "User clicked OK" : "User clicked Cancel");
• Returns true if the user clicks "OK" and false if they click "Cancel."

Create the forms using the html


Adding 2 number by taking the user input

You might also like