[Go to site: main page, start]

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

Introduction To JavaScript

JavaScript is a versatile programming language essential for web development, enabling interactivity, dynamic content, and a rich ecosystem of libraries. It features a variety of syntax elements including variables, data types, functions, and control structures like loops and conditional statements. JavaScript's advantages include client-side execution, ease of learning, and support for asynchronous programming, making it widely used for both front-end and back-end development.

Uploaded by

thalabezubaan
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)
3 views18 pages

Introduction To JavaScript

JavaScript is a versatile programming language essential for web development, enabling interactivity, dynamic content, and a rich ecosystem of libraries. It features a variety of syntax elements including variables, data types, functions, and control structures like loops and conditional statements. JavaScript's advantages include client-side execution, ease of learning, and support for asynchronous programming, making it widely used for both front-end and back-end development.

Uploaded by

thalabezubaan
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

Introduction to JavaScript

JavaScript is a powerful and widely-used programming language that enables dynamic and
interactive content on web pages. It is an essential part of web development, alongside HTML
(HyperText Markup Language) and CSS (Cascading Style Sheets).

Why Learn JavaScript?

• Interactivity: JavaScript enables user interactions, such as clicking buttons, filling forms, and
animations.

• Dynamic Content: It can update web page content without reloading the page.

• Wide Usage: Used in front-end and back-end development (with [Link]).

• Rich Ecosystem: Large libraries and frameworks like React, Angular, Vue simplify web
development.

Basic JavaScript Syntax

1. Variables

Variables store data values. JavaScript has three ways to declare variables:

var name = "Alice"; // Older way, avoid using it

let age = 25; // Preferred for mutable variables

const PI = 3.14; // Constant value, cannot be reassigned

2. Data Types

JavaScript has different types of data:

let num = 10; // Number

let text = "Hello"; // String

let isTrue = true; // Boolean

let fruits = ["Apple", "Banana", "Mango"]; // Array

let person = { name: "John", age: 30 }; // Object

3. Functions

Functions are reusable blocks of code.

function greet(name) {

return "Hello, " + name + "!";

[Link](greet("Alice")); // Output: Hello, Alice!

4. Conditional Statements

1|Page
let num = 10;

if (num > 5) {

[Link]("Number is greater than 5");

} else {

[Link]("Number is 5 or less");

5. Loops

Loops help in executing code multiple times.

For Loop

for (let i = 0; i < 5; i++) {

[Link]("Iteration: " + i);

While Loop

let count = 0;

while (count < 3) {

[Link]("Count: " + count);

count++;

6. Event Handling

JavaScript is commonly used to handle user interactions.

<button Clicked!')">Click Me</button>

7. DOM Manipulation

JavaScript can change web page content dynamically.

[Link]("myText").innerHTML = "Hello, World!";

Operators and Expressions in JavaScript

JavaScript provides operators to perform operations on values and variables. An expression is a


combination of values, variables, and operators that produces a result.

1. Types of Operators in JavaScript

JavaScript has different types of operators:

2|Page
Operator Type Description

Arithmetic Perform mathematical operations

Assignment Assign values to variables

Comparison Compare values and return a boolean (true or false)

Logical Perform logical operations (AND, OR, NOT)

Bitwise Perform operations at the binary level

Ternary Shorthand for if-else

String Concatenate strings

Type Identify or convert data types

2. Arithmetic Operators

Used for performing mathematical operations.

Operator Description Example (let a = 10, b = 5) Output

+ Addition a+b 15

- Subtraction a-b 5

* Multiplication a*b 50

/ Division a/b 2

% Modulus (Remainder) a % b 0

** Exponentiation (ES6) a ** b 100000

Increment & Decrement Operators

Operator Description Example (let x = 5) Output

++x Pre-increment ++x 6

x++ Post-increment x++ 5 (then x=6)

--x Pre-decrement --x 4

x-- Post-decrement x-- 5 (then x=4)

3. Assignment Operators

Used to assign values to variables.

3|Page
Operator Description Example (let x = 10) Equivalent

= Assign x=5 x=5

+= Add and assign x += 3 x=x+3

-= Subtract and assign x -= 2 x=x-2

*= Multiply and assign x *= 4 x=x*4

/= Divide and assign x /= 2 x=x/2

%= Modulus and assign x %= 3 x=x%3

**= Exponent and assign x **= 2 x = x ** 2

4. Comparison Operators

Used to compare values and return a boolean (true or false).

Operator Description Example (let a = 10, b = 5) Output

== Equal to a == 10 true

=== Strict equal (checks type) a === "10" false

!= Not equal to a != b true

!== Strict not equal a !== "10" true

> Greater than a>b true

< Less than a<b false

>= Greater than or equal to a >= 10 true

<= Less than or equal to b <= 5 true

5. Logical Operators

Used for combining multiple conditions.

Operator Description Example (let x = 10, y = 5) Output

&& Logical AND (x > 5 && y < 10) true

` ` Logical OR

! Logical NOT !(x > 5) false

4|Page
6. Bitwise Operators

Perform operations at the binary level.

Example (a = 5 (0101 in binary), b = 3 (0011 Result Output


Operator Description
in binary)) (Binary) (Decimal)

& AND a&b 0001 1

` ` OR `a b`

^ XOR a^b 0110 6

~ NOT ~a 1111...1010 -6

<< Left Shift a << 1 1010 10

>> Right Shift a >> 1 0010 2

7. Ternary Operator

Shorthand for if-else.

Syntax:

condition ? expression_if_true : expression_if_false;

Example:

let age = 20;

let status = (age >= 18) ? "Adult" : "Minor";

[Link](status); // Output: Adult

8. String Operators

Used for string manipulation.

Operator Description Example Output

+ Concatenation "Hello" + " World" "Hello World"

+= Append let msg = "Hello"; msg += " World"; "Hello World"

9. Type Operators

Used to check or convert data types.

5|Page
Operator Description Example Output

Typeof Returns type of a variable typeof 10 "number"

instanceof Checks if an object belongs to a class [] instanceof Array true

10. Expressions in JavaScript

An expression is any valid unit of code that produces a value.

Types of Expressions

1. Arithmetic Expressions

let result = 10 + 5 * 2; // Output: 20

2. String Expressions

let message = "Hello, " + "World!"; // Output: "Hello, World!"

3. Logical Expressions

let isAdult = (age > 18) && (age < 60);

4. Function Expressions

let greet = function(name) {

return "Hello " + name;

};

[Link](greet("Alice")); // Output: Hello Alice

Conditional statements in JavaScript allow you to execute different blocks of code based on
conditions. Here are the main types:

1. if Statement

Executes a block of code if the condition is true.

let age = 18;

if (age >= 18) {

[Link]("You are an adult.");

2. if...else Statement

Executes one block if the condition is true and another if it is false.

let age = 16;

if (age >= 18) {

[Link]("You are an adult.");

6|Page
} else {

[Link]("You are a minor.");

3. if...else if...else Statement

Checks multiple conditions in sequence.

let score = 85;

if (score >= 90) {

[Link]("Grade: A");

} else if (score >= 80) {

[Link]("Grade: B");

} else if (score >= 70) {

[Link]("Grade: C");

} else {

[Link]("Grade: F");

4. Ternary Operator (? :)

A shorthand for if...else.

let age = 20;

let message = (age >= 18) ? "Adult" : "Minor";

[Link](message);

5. switch Statement

Used when comparing a variable against multiple possible values.

let day = "Monday";

switch (day) {

case "Monday":

[Link]("Start of the week.");

break;

case "Friday":

[Link]("Weekend is near.");

break;

case "Sunday":

7|Page
[Link]("It's the weekend!");

break;

default:

[Link]("Just another day.");

6. Logical Operators in Conditions

You can use && (AND), || (OR), and ! (NOT) to combine conditions.

let isMember = true;

let age = 22;

if (isMember && age >= 18) {

[Link]("You get a discount!");

if (!isMember) {

[Link]("Consider becoming a member.");

Use of javascript in web pages

JavaScript is essential for making web pages interactive and dynamic. Here are some key uses of
JavaScript in web development:

1. Making Web Pages Interactive

JavaScript allows users to interact with a webpage through clicks, mouse movements, keyboard
input, and more.

[Link]("btn").addEventListener("click", function() {

alert("Button clicked!");

});

2. Manipulating HTML & CSS (DOM Manipulation)

JavaScript can dynamically change HTML content and styles.

[Link]("text").innerHTML = "Hello, JavaScript!";

[Link]("text").[Link] = "blue";

3. Form Validation

JavaScript is used to validate user input before submitting a form.

8|Page
function validateForm() {

let name = [Link]("name").value;

if (name === "") {

alert("Name cannot be empty!");

return false;

4. Handling Events

JavaScript allows responding to user actions like clicks, key presses, and mouse movements.

[Link]("hoverMe"). {

[Link] = "yellow";

};

Advantages of javascript

JavaScript offers several advantages, making it one of the most popular programming languages for
web development. Here are some key benefits:

1. Client-Side Execution (Fast Performance)

• JavaScript runs in the browser, reducing the need for server requests and improving speed.

• No need to wait for server responses, leading to a better user experience.

2. Easy to Learn & Use

• JavaScript has a simple syntax similar to other programming languages like C and Java.

• Beginners can quickly start coding and see immediate results in a browser.

3. Interactivity & Dynamic Web Pages

• JavaScript enables features like animations, form validation, dropdown menus, and dynamic
content updates.

4. Rich Ecosystem & Libraries

• Huge libraries and frameworks (e.g., [Link], [Link], Angular, jQuery) make development
easier and faster.

• Many third-party APIs and tools integrate seamlessly with JavaScript.

5. Cross-Browser Compatibility

• JavaScript works on all modern browsers without additional installations.

• Ensures a consistent experience across different platforms.

6. Supports Asynchronous Programming

9|Page
• JavaScript can handle multiple tasks at once using Promises, async/await, and AJAX.

• Helps in fetching data from APIs without blocking the user interface.

7. Versatile (Frontend & Backend)

• JavaScript is not limited to the browser; with [Link], it can be used for server-side
development.

• Full-stack development is possible using JavaScript alone.

8. Massive Community Support

• Active developer community with extensive documentation, tutorials, and forums.

• Frequent updates and new features improve the language continuously.

9. Lightweight & Efficient

• JavaScript does not require heavy software installation or complex setups.

• Runs directly in the browser, making applications more efficient.

10. Integrates Well with Other Technologies

• Works alongside HTML, CSS, and backend languages like PHP, Python, and Java.

• Can be used to enhance existing websites without rewriting the entire codebase.

• Typecasting in JavaScript (Type Conversion)


• Typecasting (or type conversion) in JavaScript refers to converting a value from one
data type to another. This can happen implicitly (automatic conversion) or explicitly
(manual conversion).

1. Implicit Typecasting (Type Coercion)


JavaScript automatically converts data types when needed.

Example: String + Number → String


let result = "5" + 3; // "53" (number 3 is converted to string)
[Link](result, typeof result); // "53" string

Example: String * Number → Number


let result = "5" * 2; // 10 (string is converted to number)
[Link](result, typeof result); // 10 number

Example: Boolean + Number → Number


let result = true + 1; // 2 (true is converted to 1)
[Link](result, typeof result); // 2 number

10 | P a g e
2. Explicit Typecasting (Manual Conversion)
a) Convert to String

Using String() or toString()

let num = 123;


[Link](String(num)); // "123"
[Link]([Link]()); // "123"

b) Convert to Number

Using Number(), parseInt(), or parseFloat()

let str = "42";


[Link](Number(str)); // 42
[Link](parseInt("42px")); // 42 (ignores non-numeric part)
[Link](parseFloat("42.5px")); // 42.5

c) Convert to Boolean

Using Boolean()

[Link](Boolean(0)); // false
[Link](Boolean(1)); // true
[Link](Boolean("Hello")); // true
[Link](Boolean("")); // false

Truthy values: Any non-zero number, non-empty string, objects, true


Falsy values: 0, "" (empty string), null, undefined, NaN, false

3. Special Cases
NaN (Not a Number)
[Link](Number("abc")); // NaN
[Link](parseInt("abc123")); // NaN

Null vs Undefined
[Link](Number(null)); // 0
[Link](Number(undefined)); // NaN
JavaScript Data Type

1. Primitive Data Types

These types hold single values and are stored directly in memory.

11 | P a g e
a) String

Used for textual data. Enclosed in single ('), double ("), or template literals (` `).

let name = "Alice";

let greeting = 'Hello';

let message = `Welcome, ${name}!`; // Template literal

[Link](typeof name); // "string"

b) Number

Represents both integers and floating-point numbers.

let age = 25;

let price = 99.99;

let infinityValue = Infinity;

[Link](typeof age); // "number"

Special Cases:

• NaN (Not-a-Number) is also a number type!

[Link](typeof NaN); // "number"

c) Boolean

Holds true or false values.

let isJavaScriptFun = true;

let hasError = false;

[Link](typeof isJavaScriptFun); // "boolean"

d) Undefined

A variable declared but not assigned a value.

let x;

[Link](x); // undefined

[Link](typeof x); // "undefined"

e) Null

Represents an intentional empty value (not undefined).

let emptyValue = null;

[Link](typeof emptyValue); // "object" (JavaScript quirk)

12 | P a g e
Arrays in JavaScript

An array in JavaScript is a special object used to store multiple values in a single variable. Arrays are
ordered, zero-indexed, and can hold different data types.

1. Creating an Array

Using an Array Literal (Recommended)

let fruits = ["Apple", "Banana", "Mango"];

[Link](fruits); // ["Apple", "Banana", "Mango"]

Using new Array() (Less Common)

let colors = new Array("Red", "Green", "Blue");

[Link](colors); // ["Red", "Green", "Blue"]

Empty Array

let emptyArray = [];

[Link](emptyArray); // []

2. Accessing Array Elements

Arrays are zero-indexed, meaning the first element is at index 0.

let fruits = ["Apple", "Banana", "Mango"];

[Link](fruits[0]); // "Apple"

[Link](fruits[1]); // "Banana"

[Link]([Link]); // 3

3. Modifying an Array

Updating Elements

fruits[1] = "Orange";

[Link](fruits); // ["Apple", "Orange", "Mango"]

Adding Elements

[Link]("Grapes"); // Adds at the end

[Link](fruits); // ["Apple", "Orange", "Mango", "Grapes"]

[Link]("Pineapple"); // Adds at the beginning

13 | P a g e
[Link](fruits); // ["Pineapple", "Apple", "Orange", "Mango", "Grapes"]

Removing Elements

[Link](); // Removes last element

[Link](fruits); // ["Pineapple", "Apple", "Orange", "Mango"]

[Link](); // Removes first element

[Link](fruits); // ["Apple", "Orange", "Mango"]

4. Array Methods

JavaScript provides many built-in methods to manipulate arrays.

a) push() and pop() (Add/Remove Last Element)

let numbers = [1, 2, 3];

[Link](4); // [1, 2, 3, 4]

[Link](); // [1, 2, 3]

b) unshift() and shift() (Add/Remove First Element)

[Link](0); // [0, 1, 2, 3]

[Link](); // [1, 2, 3]

c) splice() (Insert, Replace, or Delete Elements)

let items = ["A", "B", "C", "D"];

[Link](1, 2, "X", "Y"); // Removes 2 elements from index 1 and adds "X" & "Y"

[Link](items); // ["A", "X", "Y", "D"]

d) slice() (Extracts a Portion)

let slicedItems = [Link](1, 3); // Extracts elements from index 1 to 2

[Link](slicedItems); // ["X", "Y"]

e) concat() (Merging Arrays)

let arr1 = [1, 2];

let arr2 = [3, 4];

let merged = [Link](arr2);

[Link](merged); // [1, 2, 3, 4]

f) indexOf() (Find Position of an Element)

let index = [Link]("X");

14 | P a g e
[Link](index); // 1

g) includes() (Check if an Element Exists)

[Link]([Link]("Y")); // true

[Link]([Link]("Z")); // false

h) join() (Convert to String)

let joinedString = [Link](" - ");

[Link](joinedString); // "A - X - Y - D"

i) reverse() (Reverse Array)

[Link]();

[Link](items); // ["D", "Y", "X", "A"]

j) sort() (Sort Array)

let numbers = [3, 1, 4, 2];

[Link]();

[Link](numbers); // [1, 2, 3, 4] (sorted numerically)

5. Looping Through an Array

a) for Loop

let fruits = ["Apple", "Banana", "Mango"];

for (let i = 0; i < [Link]; i++) {

[Link](fruits[i]);

b) forEach() (Recommended for Iteration)

[Link](fruit => [Link](fruit));

c) map() (Transform Each Element)

let numbers = [1, 2, 3];

let doubled = [Link](num => num * 2);

[Link](doubled); // [2, 4, 6]

d) filter() (Filter Elements)

let filtered = [Link](num => num > 1);

[Link](filtered); // [2, 3]

e) reduce() (Accumulate Values)

15 | P a g e
let sum = [Link]((total, num) => total + num, 0);

[Link](sum); // 6

6. Multi-Dimensional Arrays

Arrays can contain other arrays (nested arrays).

let matrix = [

[1, 2, 3],

[4, 5, 6],

[7, 8, 9]

];

[Link](matrix[1][2]); // 6 (row index 1, column index 2)

7. Checking if a Variable is an Array

[Link]([Link](fruits)); // true

[Link]([Link]({})); // false

8. Difference Between == and === with Arrays

• == compares references (not values)

• === checks both type and reference

let arr1 = [1, 2, 3];

let arr2 = [1, 2, 3];

[Link](arr1 == arr2); // false (different memory references)

[Link](arr1 === arr2); // false

Summary Table

Method Description

push() Add to the end

pop() Remove from the end

unshift() Add to the beginning

shift() Remove from the beginning

16 | P a g e
Method Description

splice() Add/remove elements at a specific index

slice() Extract part of an array

concat() Merge arrays

indexOf() Find the index of an element

includes() Check if an element exists

join() Convert to string

reverse() Reverse array

sort() Sort array

forEach() Loop through elements

map() Transform elements

filter() Select elements based on condition

reduce() Accumulate values

Functions in JavaScript

A function in JavaScript is a reusable block of code that performs a specific task. Functions help in
code organization, reusability, and modularity.

1. Declaring a Function

a) Function Declaration (Named Function)

function greet() {

[Link]("Hello, World!");

greet(); // Calling the function

b) Function Expression (Anonymous Function)

let greet = function() {

[Link]("Hello, World!");

};

greet();

Difference:

17 | P a g e
• Function declarations are hoisted (can be called before definition).

• Function expressions are not hoisted.

2. Parameters & Arguments

Functions can take parameters (inputs).

Single Parameter

function greet(name) {

[Link]("Hello, " + name + "!");

greet("Alice"); // Output: Hello, Alice!

Multiple Parameters

function add(a, b) {

return a + b;

[Link](add(5, 3)); // Output: 8

3. Default Parameters

If no argument is passed, JavaScript uses the default value.

function greet(name = "Guest") {

[Link]("Hello, " + name + "!");

greet(); // Output: Hello, Guest!

4. Return Statement

A function can return a value.

function multiply(a, b) {

return a * b;

let result = multiply(4, 5);

[Link](result); // Output: 20

If there is no return statement, the function returns undefined.

18 | P a g e

You might also like