Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

JavaScript Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

Untitled

___________-: JavaScript Notes :-_________


Data Types
THERE ARE MANY KIND OF VARIABLES WHICH
ARE ACTUALLY DATA TYPES
RULES :
1. VARIABLE NAME MUST START WITH A LETTER ,
AN UNDERSCORE (_) OR A DOLLAR SIGN
2. VARIABLE CANNOT BE THE SAME AS
RESERBVED KEYWORDS SUCH AS IF OR CONST
3. VARIABLE NAMES CANNOT CONTAIN SPACES
4. VARIABLE NAMES ARE CASE SENSITIVE
5. VARIABLE NAMES ARE CASE SENSITIVE
6. VARIABLENAMES CAN BE AS LONG AS YOU
NEED
> // Values: a value is a piece of information that
a programme can work with. It can be number ,
text , boolean or many other complex Data
// variables : A variable is a container that holds a
value. It has a name and can be used to store and
manipulate Data in Programme
Question!

• Numbers : represents numeric value which


include integers and floating point
numebers.">
• String : represents a sequence of character
enclosed in single or double quotes.
• boolean : represnts a logical entity with two
values : true or 1 and false or 0.
• undefined : represents the absence of value or
an uninitialized variable .
• Null: Represnts the absence of value . it is
often used to explictly indicate that a variable
7H 23M 57S Page 1
often used to explictly indicate that a variable
or object property has no assigned value .
• BigInt: represents intigers that contain a
enourmus number .
To know twhat is the type of data we use
"typeof" operator.

*** In Java Script when we use the operator


typeof there is a very bad bug that if try to
find out the Data type of 'Null' it will show us
object.
To Convert a string to number data types in Java
script we use these two syntax ----

On teh other side to convert a number to string


we use the syntax below ----

• truth & falsy : *In java Script , values are either


considered "truthy" or "falsy" when evaluated
a boolean context.
Features of Truthy and falsy : ****truthy:: 1.
True. 2. Any non-empty string ("hello"). 3. Any
non-zero numbers . 4. Arrays and Objects , even if
they are not empty. ****falsy:: 1. false 2. 0 3. null
4. undefined. 5. not a number 6. An empty string.
• To check a string empty or not in JavaScript
we can use If statement directly in Script.

7H 23M 57S Page 2


Output:

• Parseint & Parsefloat : ** Parseint and


parsefloat are both function using in
JavaScript for converting Strings to Numbers
but they have different use cases.
1. Parse Int : **parse int is used to parse a string
and convert it to an integer (Whole Number).
2. Parse float : **Parse floats is used to parse a
string and convert a floating point number
(Decimal-point Number).

**Sometime a number can return us Boolean


values also . There is a Function in JavaScript
"isNaN" where if we use this function operator
and with as perspective with the given condition
it return us Boolean Values .

INTERVIEW Question : 'NaN == Nan', the


statement is false.

JUST THINK =>

7H 23M 57S Page 3


JUST THINK =>

Output

Operators
• There are 8 kind of operators in java script.
Which are ----
1. Assignment Operators
2. ArithMetic Operators .
3. Comparision Operators .
4. Logical Operators .
5. String Operators .
6. Unary Operators .
7. Ternary Operators .
8. Type Operators .
Example:

There is a Bug also in JavaScript which is ----

Output:
7H 23M 57S Page 4
Output:

But there is a way to fix that bug which is using a


function ".toFixed( )"

Output:

• There is a few way to concatenate in


JavaScript . The most common way to use the
Operator '+' . For example, To concatenate the
String "hello" and "World" , You would use the
following code ---

Comparison Operator : This is a kind of Operator


which returns Boolean Value in Output.
There are 7 kinds of Comparisons Operators ----
1. Equal To (==)
2. Strict Equal(===)
3. Not Equal (!=)
4. Greater than (>)
5. Less Than (< )
6. Greater than or Equal To (>=)
7. Less Than or Equal To (<=)
example:

Output:

Q. What is the difference of Equal To and Strict


Equal.
Ans : The normal Equal To checks only the Value
of the Comparing Subjects but Strict Equal To also
checks the data Types among the comparing
Subjects and if the Data Types are not equal so it
will return Boolean 0.

Output:

Logical Operator :
First watch a Example and try to understand how
7H 23M 57S Page 5
First watch a Example and try to understand how
it works.

**Note : Here the operator '&&' is actually a


Boolean Logical Gate Operator named And Gate
Logical Or(||):Returns True if at least one
Operand is True otherwise, it returns False.

OUTPUT:

Logical NOT:
Returns True if the oprands is false, and false if
the operand is true.
Q1. Write a Programme that determines if a
person is eligible to drive based on their age
greater than or equal to 18 and having a valid
Driving License ?
CODE:

OUTPUT:

• Ternary(conditional) Operator :
1. Syntax : Condition? expressionIfTrue :
expressionIfFalse
7H 23M 57S Page 6
expressionIfFalse
Q. !! Write a programme to check if the
candidates isEligibleForDrive or Not?
**age must be equal or greater than 18.
Question Summary : actually we need to use
ternary or conditional operators instead of using
if-else statement.
code:

OUTPUT:
Q. Let say you have a variable score representing
a student's exam score. If the score is greater
than or equal to 60, the student passes;
otherwise they fail. Use the ternary operator to
determine the result and store it in variable called
result. Log the result to the console.
CODE:

Control Statement & Loops :


1. If..Else Statement
2. Switch statement
3. While Loop
4. Do-While Loop
5. For-loop
6. For-in / For Of Loops (Later in arrays )
If..Else Statement:
Syntax:

Eg.1

Interview Question
Project Materials :
• if the person is 18 years older, a citizen, and
registered to vote, display a massage saying
they are eligible to vote.
• if the person is younger than 18, not a citizen,
7H 23M 57S Page 7
• if the person is younger than 18, not a citizen,
not registered to vote, display a massage
saying they are not eligible for vote .
• if the person is 18 or older bot not a citizen,
display a massage they are not eligible due to
citizenship status.
• if the person is 18 years older and a citizen bit
not registered to vote, show a massage saying
you are not eligible due to registration status.
• extend voting eligibility checker with
additional conditions.
CODE:

================================
Switch Statement :
================================
Switch Statement: The switch statement is used
to perform different actions based on different
conditions.
Important Question :
Write a java Script switch statement that takes a
variable areaOfShape representing different
shape, and based on its value, calculating and log
the area of the corresponding shape. consider the
three shapes : 'rectangle, 'circle', and 'square'. For
rectangle use variable a & b the sides; for circle
use a variable r as the radius; and for square use
variable as the side length. If the provided shape
is not recognized, log a massage saying, "Sorry,
The shape is not available." Test your switch
statement with areaOfShape set to Square and
sides a and b set to 5 and 10, Respectively. Ensure
that the correct area (25 in this case.) is logged to

7H 23M 57S Page 8


that the correct area (25 in this case.) is logged to
the console.
Code:

Output:
================================
While-Loop:
================================
While-Loop:
A while loop in JavaScript is a control structure
that repeatedly executes a block of code as long
as specified conditions remains true. The loop
continues iterating while the condition is true.
And it terminates when the condition becomes
false.
Q.
Write the Syntax of While-loop.
Syntax:

Q. Show the different between While-Loop and


Do-While-Loop.
ANS: In While Loop the programme starts with
Loop but in Do-Wile-loop the code with run Once
the it will enter in the loop.

7H 23M 57S Page 9


For-Loop: It is nothing but a combination of
While-loop_Syntax.

While-Loop Eg1 :

Q. Write a Script to print the table of 189.

Q Write the common use Causes of Do-While


Loop.
Ans:
1. When you want to guarantee the execution of
the loop body at least once.
2. When the number of iteration is not known
beforehand, and you want to validate the
condition after the first iteration.
Fun Time withFor-loop:
1. Programme to check if a year is Leap year,
2. If a year is divisible with 4 and not divisible
with 100.
3. If a year is divisible with 400 then it is a Leap-
year.
Otherwise, it's not a leap year.
• Programme to check if a year is Leap year.

• Programme to check If a year is divisable with


4 and not divisable with 100.

Q. Calculate the sum of the numbers between 1


7H 23M 57S Page 10
Q. Calculate the sum of the numbers between 1
to 10 using for loop..

Q.Print the pattern.


*
**
***
****
*****
Code:

-: JavaScript Functions :-

Syntax:

Eg1:

On the code above we can see that we have to


code for a long so letr's make it easy and
reuseable.

7H 23M 57S Page 11


Topics:-

• Function • Function • Return keyword.


Declaration Argument.
.
• Function • Function • Immediately
Invocation. Expression. invoked Function
expression.
• Function • Annouymou • Advance Topics .
Parameter. s Function.

-: Function Declaration :-

-: Function Invocation :-
=> It is nothing but calling any function is called
function invocation.
On previous image the line ---
console.log(greet()); is called function invocation.

-: Function Parameter :-

-: Function Argument :-

Practice Time :
Q. Write javaScript programme that defines a
function called greet to welcome individual to the
Thapa Technical JS Course. The function should
7H 23M 57S Page 12
Thapa Technical JS Course. The function should
take a name parameter and output the massage
"Hello [Name], Welcome to Thapa Technical JS
Course." Call the function twice, Once with the
first argument "Vinod" and once with the
argument "Ram".

-: Function Expression :-
Function Expression :- Function Expression is a
way to define a function as a part of an
expression. It can be either named or
anonymous.. If it's named , it becomes a names
function expression.

-: Anonymous Function :-
Anonymous Function :- An anonymous function is
a function without a name. It can be created
using either a function or a function declaration
without a specified name.

-: Return Keyword :-
Return Keyword :- In JavaScript, The return
statement is used with in a function to specify the
value that he function should produce or provide
back to the code called it. The return statement
stops the execution of a function and sends a
value back to the caller.

***After using return key word no code will run


in the function.

-: IIFE(Immediately invoked Function expression):-


IIFE(Immediately invoked Function expression):-
An IIFE, or Immediately Invoked Function
Expression, is a javaScript function that is defined

7H 23M 57S Page 13


Expression, is a javaScript function that is defined
and executed immediately after it's creation. It is
a way to create a self-contained block of code
that doesn't interfere with the surrounding Code
and executes immediately.

Q. make a calculator using JavaScript.


Code:

-: EcmaScript Timeline :-

2015 EcmaScript
Let :- The let keyword is used to declare variable
with block scope. Variable declared with let are
mutable, meaning their values can be reassigned.
Const :- The const keyword is used to declare
variable with block scope, but once the value is
assigned to a const variable, it cannot be
reassigned. Const variable are immutable.

7H 23M 57S Page 14


***On the code there are many problems. To
identify the problem read the definition of Const.

Slice()

Q.Write a function to reverse a given string using


built in reverse method.
Code :

-: JavaScript Arrays :-

EcmaScript 2022 also introduces new .at()


method in Arrays for javaScript.

Most importent topics :-


Creating Array/ Accessing Array Traversal /
Elements /Modifying Iterating Over
Elements Array
How to Insert , Add & delete Search in an Array
7H 23M 57S Page 15
How to Insert , Add & delete Search in an Array
elements in Array.
Filter in an Array How to Sort &
Compare an Array
Array in advance
Q. Why Array is called Object ?
=> Any arguments with length property and the
indexes to access items. Array has both qualities
that is why Array is called object.

-: Creating Array :-

-: Array Constructor :-
Code :-

Output :-

-: Array Literal :-

-: Array Traversal / Iterating over Arrays :-

***Array traversal is a special kind of For loop in


Arrays.
• For...of Loop :- The For...of Loop is used to
iterate over the values of an iterable object,
such as Arrays, or others iterable objects.
• For...in Loop :- The For...in Loop is used to
iterate over the properties of an object.
• For...Each method :- The arr.forEach() method
calls the provided function once for each
element of array. The provided function may
perform any kind of operation on the element
of the given Array.
• Map-Function :- map() creates a new array
from calling a function for every Array
element. map() fucntion dosen't change the
original Array.
-: For...of Loop :-

7H 23M 57S Page 16


-: For...in Loop :-

-: For Each Loop :-


Syntax :-

On the picture above you can see many unknown


terms. Let's us know about them ---
• .array : The array on which the forEach
method is called.
• Callback : A Function that will be called once
for each element in ARRAY.
• CurrentValue : The current element being
processed in the array.
• index(optional) : The index of the current
element being processed.
• thisValue : A value to use as this when
executing the callback function.
***For short we can write this too--

Eg:-

Q. Write a programme to multiply each element


with 2.
Code :

7H 23M 57S Page 17


Output :
[ 12, 196, 166, 10.8 ]

Push Method : The push method is a method that


adds one or more elements.
Pop Method : The pop method is a method to
eliminate the last element from an Array .

Output :

Unshift( ) : Method that adds one or more


elements at the beginning of the Array.
Shift( ) : Method that removes the first element
of the Array.

Output :

Splice( ): It is used to show the array elements


after the given element index.

Eg1 :

Output :

Adding Elements with Splice() :-

Output :-
-: Searchhing in arrays :-
7H 23M 57S Page 18
-: Searchhing in arrays :-
IndexOf method : The indexOf method returns
the first index at which a given element can be
found in Array. And if it can't find the element it
will return -1;
Code :

Output :

Includes( ) method :- This is a method which


returns Boolean value to the output. If the
element is existing element so it will return true
otherwise it will return false.
Code :

Output :

LastIndexOf( ) Method : The LastIndexOf( )


Method of Array instances return the last index at
which a given element can be found in the Array,
or -1 if it is not present. The Array is Searched
backwards, starting from Index .
Code :

Output :

Practice Question :-
Q.

• Add "Dec" at the end of the Array.


• What is return value of Splice Method.
• Update "march" to "March".
• Delete June from the Array.
Code :

7H 23M 57S Page 19


Output :

-: Search - Filter :-
• The find() Method is used to find the first
element in an Array that satisfies a provided
testing function. it returns the first matching
element or undefined is no element is found.

• The findindex () Method of a Array instances


returns the index of the first element in a
Array that satisfies the provided testing
function. If no elements satisfy the testing
function then -1 is returned.

• The filter() method creates a new Array with


all elements that pass the implemented by the
provided function.

-----------------------------------------------------
Sorting In Array Objects
-----------------------------------------------------
Sorting an Array : The sort method sorts the
elements of an Array in place in returns the
sorted Array defaults, it sorts element as string.
7H 23M 57S Page 20
sorted Array defaults, it sorts element as string.

Output:

-----------------------------------------------------
-: String :-
-----------------------------------------------------
String And its Properties Escape Charecters
String Search Method Extracting String Parts
Extracting String Replace String
Charecters Charecters
Other Useful Methods

Q. What is a String ?
Ans: String in JavaScript are fundamental data
type that represents a sequence of characters.

Note : 1. String created with single or double


courts works the same.

Q. What is String length ?


Ans: It is a property of string that returns the
length of the String (Number of characters)
Note : The length number starts always with 0
means if the String is "Ankit" so the string Length
is (Actual Character Number - 1) = (5 - 1) = 4

-: Escape Characters :-

Escape Character : In JavaScript, The backslash \ is


used as an escape character. It allows you to
7H 23M 57S Page 21
used as an escape character. It allows you to
include special characters in String.

*** On the above code we can see that we used


courts in side of courts. In text1 we can see when
we put double courts in double courts it gives us
syntax error but if we put double courts under
single courts like text2, it will not give us syntax
error.

But if there a case comes that in a string we want


single courts and double courts both. For that see
below---

Output:-

-: String Search Method :-

IndexOf method : This method returns the


index(position) of the first occurrence of a String
in a String, or it returns -1 if the string is not
found.

Output:-

LastIndexOf( ): The lastIndexOf( ) method returns


the index of the last occurrence of a specified text
in a String.

Code:-

***There is a Method to convert a String object


into an Array object. To do that we must use a
7H 23M 57S Page 22
into an Array object. To do that we must use a
function named Array.Form.

Code :

Output :

*** After this we can do anything related Array


with this String like Array Mapping.

Code:

Output:

Search( ): The Search Method searches a String


for a String and returns the position of the match.
________________________________________
***Q. Show a deference between indexOf and
lastIndexOf method in String in JavaScript with
help of a programme.

Ans:
Code :

Output :

________________________________________

7H 23M 57S Page 23


Search( ) : The Search method searches a String
for a String and returns the Positions of the
match. It also returns -1 is no match is found.

Code :

***But there is a problem there, The system is


very Case sensitive means "Good" and "good"
Are not the same. To overcome it watch the
code below.

*** If we use escape character (using slash '/'


instead of courts) and fly and 'i' after them, it
will ignore case sensitivity.

Match( ): It returns an Array of the matched of


the matched value or null if it's not found.

Code:

Output :

**But if we need the information instead of


index number as Array so we can fly "g" instead
of "i" after using escape character.

Code:

7H 23M 57S Page 24


Output:

***But one thing is noticeable that if we fly "g"


here so the system becomes case sensitive. To
solve this problem we must fly "gi" here.

matchAll( ) : this method returns an iterator of


all matches, providing detailed information
about each match. Returns an empty iterator
(Array) if no match is found.

Code:

Output:

Includes( ): Returns true if the String contains


the specified value, and false otherwise.

Part 2 coming soon…

7H 23M 57S Page 25


7H 23M 57S Page 26

You might also like