0% found this document useful (0 votes)
36 views26 pages

Understanding JavaScript Basics

JavaScript is a scripting language that enables interactive and dynamic web content, functioning alongside HTML and CSS. Key concepts include variables, scope, hoisting, data types, operators, conditional statements, loops, functions, arrays, and strings. Understanding these elements is essential for effective programming in JavaScript.

Uploaded by

parthivajith40
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)
36 views26 pages

Understanding JavaScript Basics

JavaScript is a scripting language that enables interactive and dynamic web content, functioning alongside HTML and CSS. Key concepts include variables, scope, hoisting, data types, operators, conditional statements, loops, functions, arrays, and strings. Understanding these elements is essential for effective programming in JavaScript.

Uploaded by

parthivajith40
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

JavaScript

JavaScript is a scripting language that allows you to create interactive and dynamic content on
websites. Think of it like a set of instructions that tells the web page how to behave. While
HTML handles the structure (like the bones of a page) and CSS handles the style (like the skin
and clothes), JavaScript handles the actions (like the muscles and movements).

Simple Analogy

Imagine a house:

• HTML is the blueprint for the house, defining where the walls, doors, and windows are.
• CSS is the paint, furniture, and decorations that make the house look good.
• JavaScript is the electrical wiring, the doorbell that rings when you press a button, and the
lights that turn on and off. It adds the functionality that makes the house useful and interactive.

What it does:

JavaScript is used for many things, including:

• Form validation: Checking if a user has filled out a form correctly before they submit it.
• Interactive maps: Letting users zoom in, zoom out, and click on different locations.
• Animations: Making elements on a page move or change over time.
• Creating pop-up boxes or alerts: Displaying messages to the user.
• Updating content without reloading the page: For example, when you "like" a post on social
media, the like count updates without the entire page refreshing.

Essentially, JavaScript runs directly in your web browser and is a fundamental part of almost
every modern website, making them more engaging and responsive for the user.

[Link]
A variable is like a container or a box that holds a piece of information. In JavaScript, you use a
variable to store data that you can use or change later in your program

How to use a variable


In JavaScript, you create a variable using the let or const keyword.
let is for a variable that can be changed later
let age = 25; // The variable "age" now holds the number 25.
age = 26; // You can change its value later.

const is for a variable that should not be changed. It is "constant."


const name = "John"; // The variable "name" holds the text "John".
// You cannot change its value later. Trying to do so will cause an error.

var is the original keyword used to declare a variable in JavaScript. It was the only way to create
variables before let and const were introduced in 2015. While it works similarly to let in that it
allows you to change the value of the variable

scope
Scope is a fundamental concept in programming that defines the accessibility of variables and
functions in your code. It determines where a variable can be used and where it cannot. Think of
it as a set of rules that governs a variable's visibility.

Key Types of Scope in JavaScript


Global Scope: Variables declared outside of any function or block have a global scope. They
can be accessed from anywhere in your code.

let globalVar = "I'm global";


// globalVar can be used here.

Function Scope: Variables declared inside a function are only accessible within that function.

function myFunction() {
let functionVar = "I'm in a function";
}
// functionVar cannot be used here.

Block Scope: Variables declared inside a block (defined by curly braces {}), such as an if
statement or a for loop, are only accessible within that block.

if (true) {
let blockVar = "I'm in a block";
}
// blockVar cannot be used here.

var
var has function scope and global scope. It does not have block scope.
Function Scope: A variable declared with var inside a function is only accessible within that
function.
Global Scope: A variable declared with var outside of any function is accessible anywhere in
your code.
No Block Scope: This is the key difference. A var variable declared inside a block of code (like
an if statement or a for loop) can still be accessed outside that block. This can be a source of
bugs.

let & const


If you declare let or const outside of any function or block, they have a global scope. They are
accessible everywhere in your code.

If you declare them inside a function, they have a function scope. They are accessible only
within that function.

If you declare them inside a block (like an if statement or a loop), they have a block scope.
They are only accessible within that specific block.

The key difference from var is that var does not have block scope. So, if you declare var
inside a block, its scope is not limited to that block, which can lead to unexpected behavior. let
and const were created to solve this problem by providing true block scope, which makes your
code more predictable.

Hoisting

Hoisting is a behavior in JavaScript where variable and function declarations are "lifted" to the
top of their scope before the code is executed. This means you can use a variable or call a
function before you've actually declared it in your code.

How it Works
When JavaScript runs your code, it has two main phases:
Creation Phase: The JavaScript engine scans the code and finds all the variable and function
declarations. It then "hoists" these declarations to the top of their respective scopes.
Execution Phase: The code is then run line by line.
Hoisting with var
With var, only the declaration is hoisted, not the assignment. This means the variable exists,
but it has a value of undefined until the line where it's assigned a value is reached.

[Link](myCar); // Outputs: undefined


var myCar = "Honda";
[Link](myCar); // Outputs: "Honda"

The code above is read by the engine as if it were written like this:

var myCar; // The declaration is hoisted to the top.


[Link](myCar); // It exists, but has a value of undefined.
myCar = "Honda"; // The assignment happens here.
[Link](myCar); // Now it has its value.

Hoisting with let and const


While let and const are also hoisted, they behave differently. Their declarations are hoisted, but
they are not initialized with a value. If you try to access a let or const variable before it's
declared, you'll get a ReferenceError. This period between the start of the scope and the
declaration is called the Temporal Dead Zone.

[Link](myBike); // Throws a ReferenceError!


let myBike = "Yamaha";

This behavior is generally preferred because it helps catch mistakes in your code and leads to
fewer bugs.

let and const and Hoisting


let and const are also hoisted, but with a crucial difference: they are placed into what's called a
Temporal Dead Zone (TDZ). This is a special area where the variable exists but cannot be
accessed. If you try to use a let or const variable before its declaration is reached, you will get a
ReferenceError.

Data Types in Java


In Java, a data type is a classification that specifies which type of value a variable can hold. It
determines the size and type of values that can be stored and the set of operations that can be
performed on the variable.
Java has two main categories of data types:

Primitive Data Types: These are predefined by Java and are single, simple values. There are
eight primitive data types.
Non-Primitive (Reference) Data Types: These are created by the programmer and are used to
store more complex values, like objects. Examples include Strings, Arrays, and Classes.

Primitive Data Types


There are eight primitive data types in Java. They are all fixed sizes and do not have any extra
methods.

byte (8 bits): For storing small integer numbers.


short (16 bits): For storing slightly larger integer numbers.
int (32 bits): The most commonly used data type for integers.
long (64 bits): For very large integer numbers. The L at the end of a value indicates it's a long.
float (32 bits): For single-precision decimal numbers. The f at the end of a value is required.
double (64 bits): The most commonly used data type for decimal numbers.
boolean (1 bit): For logical values, either true or false.
char (16 bits): For storing a single character. It's enclosed in single quotes.

Non-Primitive Data Types


These are also called reference types because they don't store the actual value in the variable;
instead, they store a reference (or an address) to the object's location in memory.
String: A sequence of characters. It is not a primitive type. It's an object.
Example: String name = "Java Programmer";

Array: A collection of similar types of data.


Example: int[] numbers = {1, 2, 3, 4};

Classes and Interfaces: A class is a blueprint for creating objects, and an interface is a
contract that a class can follow.
Example: MyClass myObject = new MyClass();
What are Operators?
In Java, operators are special symbols that perform specific operations on one or more
variables or values. The variables or values that an operator works on are called operands.
Think of an operator as an instruction to the computer to do something.

For example, in the expression 5 + 3, the numbers 5 and 3 are the operands, and the +
symbol is the operator that tells the program to add them together.

Types of Operators
Java has several types of operators, grouped by the kind of operation they perform.

1. Arithmetic Operators

These are used to perform basic mathematical operations.


=== Identical

== is for loose equality. It checks if the values are the same after converting them to a
common type. This is often called "type coercion." For example, 5 == '5' would be true
because JavaScript converts the string '5' to the number 5 before comparing.
=== is for strict equality. It checks if the values are the same without any type conversion. It
first checks if the types are the same, and if they are not, it immediately returns false. If the
types match, it then checks if the values are equal. For example, 5 === '5' would be false
because a number (5) and a string ('5') are different types.

Conditional Statements
1. if Statement
The if statement is the most basic. It runs a block of code only if a specified condition is true.

Example:

JavaScript
let age = 19;
if (age >= 18) {
[Link]("You are an adult."); // This code runs because the condition is true
}

2. if...else Statement
The if...else statement provides an alternative path. It runs a block of code if the condition
is true, and a different block of code if the condition is false.

Example:

JavaScript
let temperature = 25;
if (temperature > 30) {
[Link]("It's a hot day!");
} else {
[Link]("It's a nice day."); // This code runs because the condition is false
}

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


This is used for checking multiple conditions in sequence. The code runs the first block where
the condition is true and then stops. If none of the conditions are true, the final else block runs.

Example:

JavaScript
let score = 85;
if (score >= 90) {
[Link]("You got an A.");
} else if (score >= 80) {
[Link]("You got a B."); // This code runs
} else {
[Link]("You got a C or lower.");
}

4. switch Statement
A switch statement is a cleaner way to handle many different conditions based on a single
value. It's often used as a more readable alternative to a long if...else if...else chain.

Example:

JavaScript
let day = "Monday";
switch (day) {
case "Monday":
[Link]("Start of the work week.");
break; // Stops the switch statement from checking other cases
case "Friday":
[Link]("Almost the weekend!");
break;
default:
[Link]("It's a regular day.");
}

● The break keyword is important; without it, the code will continue to run the next cases
after a match is found.
● The default case is optional and runs if no other case matches.

Types of Loops
There are a few main types of loops in JavaScript, each good for slightly different situations.

1. for loop
A for loop is the most common type. You use it when you know exactly how many times you
want the loop to run. It has three main parts:

1. Start: Where the loop begins.


2. Condition: The rule that must be true for the loop to keep running.
3. Step: What to do after each run, usually to move closer to the end.

Example:

JavaScript
for (let i = 0; i < 3; i++) {
[Link]("hello");
}

In this example:

● let i = 0 is the start. We create a counter variable i and set it to 0.


● i < 3 is the condition. The loop will continue as long as i is less than 3.
● i++ is the step. We add 1 to i after each time the code runs.

This loop will run three times, printing "hello" to the console.

2. while loop

A while loop is used when you don't know exactly how many times the loop will run, but you
have a condition that must be met. The loop continues as long as a specified condition is true.

Example:
JavaScript
let count = 0;
while (count < 3) {
[Link]("hello");
count++;
}

Here, the loop will run as long as the variable count is less than 3. We must remember to
update count inside the loop, otherwise, it would run forever!

3. do...while loop

A do...while loop is similar to a while loop, but with one key difference: it always runs at
least once. The condition is checked at the end of the loop, not the beginning.

Example:

JavaScript
let count = 0;
do {
[Link]("hello");
count++;
} while (count < 0);

Even though the condition count < 0 is false from the start, the loop will run once and print
"hello" because the do block is executed before the while condition is checked.

What is a Function?
Think of a function as a small, specialized machine in your workshop.

1. You give it some materials (called arguments).


2. It does a specific job (the code inside the function).
3. It gives you a finished product (called a return value).

In JavaScript, a function is a reusable block of code that performs a specific task. We use them
for two main reasons:

● To avoid repeating yourself: Instead of writing the same lines of code over and over,
you can write them once inside a function and "call" that function whenever you need to
perform the task.
● To organize your code: Functions help break down a large, complicated program into
smaller, more manageable pieces that are easier to read and understand.

A Simple Example
Here is a basic function that adds two numbers.

JavaScript
function addNumbers(number1, number2) {
// This is the "task" the function performs
let sum = number1 + number2;

// This is the "finished product" it gives back


return sum;
}

// Now let's use our function, or "machine"


let result1 = addNumbers(5, 3);
[Link](result1); // This will print 8

let result2 = addNumbers(10, 20);


[Link](result2); // This will print 30
What is a JavaScript Array?
Imagine you have a flexible backpack. .

1. It's not a rigid box with a fixed number of slots. You can put as many or as few items in it
as you want. It stretches to fit.
2. You can put any kind of item in it. You could have a notebook, a sandwich, a water
bottle, and your keys all in the same backpack.

In JavaScript, an array is exactly like this flexible backpack. It's a single variable that can store
an ordered list of values. The most important things to remember are:

● Dynamic Size: You don't have to decide its size when you create it. You can add more
items later.
● Mixed Data Types: You can store a string, a number, a boolean, or even another
array all inside the same array.

Here is a super simple code snippet you can even type directly into your browser's developer
console to see how it works.

When we say an array is an "ordered list of values," it means two things:

1. Sequence Matters: The items are stored one after another in a specific, fixed
sequence.
2. Numbered Positions: Every item has a numbered position, called an index.

Think of it like a line of people waiting for a bus. .

● The person at the front is in position 0.


● The second person is in position 1.
● The third person is in position 2, and so on.

The order never changes unless you specifically move someone. You can always find a person
by their position in the line. You don't have to guess or search for them.

What is a String?
In JavaScript, a string is just that: a sequence of characters. It's used to store and work with
text. It can be a single letter, a word, a sentence, a paragraph, or even a whole book.
The most important thing to remember is that you create a string by wrapping the text in either:

● Single quotes: 'hello'


● Double quotes: "world"
● Backticks: `hello world

Common String Methods (Tools)

1. length (It's a property, but acts like a tool)


○ Job: To count the number of characters in the string.
○ Analogy: Like counting the beads on your necklace.
○ How to use: [Link] (Notice there are no parentheses () here
because it's a property, not a method).
2. toUpperCase() and toLowerCase()
○ Job: To change the entire string to all capital letters or all lowercase letters.
○ Analogy: Putting the whole necklace in a machine that changes the shape of all
the beads.
○ How to use: [Link]()
3. indexOf()
○ Job: To find the first position (index) of a specific character or sequence of
characters. If it can't find it, it returns -1.
○ Analogy: Finding the first blue bead in your necklace.
○ How to use: [Link]("text")
4. slice()
○ Job: To get a part of the string. You tell it where to start and where to end.
○ Analogy: Cutting a piece of your necklace to use for a bracelet.
○ How to use: [Link](startIndex, endIndex)

// --- STEP 1: Our string (our toolbox) ---

let message = "Hello, World!";

// --- STEP 2: Using the `length` property ---

[Link]("Original string:", message);

[Link]("1. The length is:", [Link]); // Outputs: 13

// --- STEP 3: Using `toUpperCase()` ---

let loudMessage = [Link]();


[Link]("2. The loud message is:", loudMessage); // Outputs: HELLO,
WORLD!

// --- STEP 4: Using `indexOf()` ---

let position = [Link]("World");

[Link]("3. The word 'World' starts at index:", position); // Outputs:


7

// --- STEP 5: Using `slice()` ---

let smallPiece = [Link](7, 12);

[Link]("4. A small piece of the string is:", smallPiece); // Outputs:


World
[Link]()

[Link]

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

</head>
<body>

<h1 id="head1">Hello</h1>

<script src="[Link]"></script>

</body>

</html>

[Link]

//get Elements By Id name

var a = [Link]("head1"); // in order to get the


attributes by the attributes id, here we use a html element.

[Link](a);

[Link] = "Java" //the [Link] is used to change the property of


html element

[Link] = "red"

Out

[Link]()

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1 class="head1">Hello</h1>
<p class="head1">Paragraph</p>
<h2 class="head1">Learn Java Script</h2>

<script src="[Link]"></script>

</body>
</html>

[Link]
var a = [Link]("head1")
[Link](a)

Out 1

Html attribute index, we can access each attributes by using index number
[Link]
var a = [Link]("head1")
[Link](a);
a[0].innerHTML = "Hai"
a[1].innerHTML = "paragraph modified"
a[2].[Link] = "red"

Out 2

[Link]

A tag in HTML is a special keyword used to mark the beginning and end of an HTML element.
These tags tell a web browser how to display the content on a webpage. Think of them as labels
or instructions.

Here's a breakdown of how they work:

● Structure: Most HTML tags come in pairs: an opening tag and a closing tag.
○ The opening tag looks like <tagname>.
○ The closing tag looks like </tagname>.
○ The content you want to display goes between the two tags.
For example, to make a paragraph, you would use the <p> tag:
HTML
<p>This is a paragraph of text.</p>


● Self-Closing Tags: Some tags are "self-closing" because they don't need a separate
closing tag. This is usually for elements that don't wrap around any content, like an
image or a line break.
○ An image tag looks like this: <img src="[Link]">.
○ A line break tag looks like this: <br>.

HTML tags are the fundamental building blocks of every webpage. They define the structure
and meaning of your content.

[Link]

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

</head>

<body>

<h1 class="head1">Hello</h1>

<p class="head1">Paragraph1</p>

<p class="head1">Paragraph2</p>

<h2 class="head1">Learn Java Script</h2>

<script src="[Link]"></script>
</body>

</html>

[Link]

var a = [Link]("h1")

[Link](a);

Out1
We can access each elements by their Tag Name

Html attribute index, we can access each attributes by using index number

[Link]

var a = [Link]("h1")

[Link](a);

a[0].innerHTML = "Hai"

a[0].[Link] = "red"

var b = [Link]("p")

[Link](b)

b[0].innerHTML = "Paragraph1 modified"

b[0].[Link] = "green"
Out2

[Link]

[Link]
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>

<body>
<input type="text" name="text">
<input type="button" value="Click Here" onclick="message()">
<h1 id="head1"></h1>
<script src="[Link]"></script>

</body>
</html>

[Link]
var a = [Link]("text")[0]
var b = [Link]("head1")

function message(){
[Link]("Hello " + [Link])
}

You might also like