Javascript
Javascript
Output possibilities
2. alert: This is used to display the output in a separate pop up box on the browser.
It does not require us to open the console like in previous method.
- The disadvantage for alert is that it halts the execution of the program
until the confirmation of alert.
3. document.write: This is used to display the output of the JS code on the webpage
itself. The output can even be displayed in the form of HTML elements.
1. In the head section: The JS code in the script tag will start its execution before HTML
elements are loaded.
-Due to this, if we want to work with any HTML element, we
won't be able to do it and will get error.
- It there is any code in this script tag which is lengthy and
might take time, it will affect the performance of our page.
The page will be displayed properly only after that code is finished
2. At the end of body section: When the script tag is written in the end of body section,
it will get the necessary HTML elements for its operation.
If there is any lengthy code in this script tag, it won't
hamper the performance of the HTML page.
1. External JS: It is the typew of JS which is written in a separate file having '.js'
extension and connected to the HTML document using <script> tag.
2. Internal JS: When we write the JS code in the same HTML document usnig <script> tag,
it is called Internal JS.
3. Inline JS: When the JS code is written in the body of the opening tag of any
elmement, it is called inline JS
1. In VS Code:
JS Code is written in the VS code in a new file when we want to use the
code as functionality and make it permanent
Comments:
It is additonal line
*/
Variables :
Variables are the containers which are used to store some data which can be later
used for processing.
The variables are made up of two parts:
1. Declarator
2. Identifier
Declarators
These are the keyowrds which specify the scope of any variable
Scope is the area where the variable should be applicable.
If the scope is improperly defined then the variable may get access to
other parts of code where it can cause issues.
var:
This is a declarator from older JS
This is a global scope declarator
It can be redeclared and re-assigned
let:
It is a feature from ModernJS(ES6)
It is a block scope declarator
It cannot be redeclared but it can be re-assigned
const:
It a feature from ModernJS(ES6)
It is also used for creating a block scope declarator
It cannot be redeclared nor re-assigned
1. Declare:
In this phase we only create a container/variable having declarator and identifier.
We do not store any data in this yet.
2. Initialize:
In this phase, we actually store some data into the container/variable
3. Use:
In this phase, we use the variable with data stored in it for some processing.
Identifier
The identifier is the name given to a variable which can be used for uniquely
identifying the given variable
1. The name of the variable should not be any reserved keywords (if, while, for, let, var,
const, do, new, in)
2. The name of the variable should not contain any spaces
3. Instead of spaces we can use PascalCasing or camelCasing
4. We cannot use any other symbol than '$' or '_' in our variable name
5. The variable name cannot be a number or it cannot start with a number
Hoisting :
• It is the default behaviour of Javascript
• It allows us to declare our variable later on after intializing and using it first.
• When we declare our variable after intialization and use, Javascript internally takes
• the variable to the top of the code.
• Because of this, the variable comes in the original flow of the variable lifecycle and
• thus gets executed properly
• At times, the developer can also forget declaring the variable due to the
• hoisting behaviour of Javascript.
• This can create problems in the execution and troubleshooting of the JS code.
•
• The concept of declaration is only applicable on var.
use strict :
• It is a rule/pragma which tells our browser how to execute the javascript code.
• It puts our browser on 'strict mode'
• Because of this, the use of undeclared variables is prevented.
• This helps the developer to write cleaner codes which will be better for execution
and for troubleshooting
•
• 'use strict' can be used in blockn scope as well as on the global scope.
string:
It is a collection of characters which is stored between two double
quotes.
boolean:
It is used to give 'true' or 'false' values
undefined:
It is given when we create a variable but do not store any value in it.
Since JS is a dyanmically written langauge, it detects the datatype of the
variable at the time of execution.
If there is no value stored in the variable, JS cannot determine the datatype of
the variable.
Thats why it gives us undefined
null:
When we do not get any object in the variable it returns null.
null itself has datatype 'object'.
It denoted empty colletion/object.
bigInt:
It is used to store very large numbers in the integer format(without decimal
point) To make a number bigInt, we need to insert 'n' at the end of the number.
Symbol:
It is a datatype from ModernJS(ES6)
It is used to generate unique values.
Never two keys will be be the same.
The Symbol can be used as the unique key for any object.
Basic Operators
Arithmetic operators:
+,-,*,/,%
Assignment operators
Comparison operators
Logical operators
!, &&, ||
Incr/Decr operators
++, --
Equality operators
ModernJS operators :
1. typeof:
This operator helps us to find the datatype of the variable
2. nullish coelscheing:
It provides some default value for the variable to work properly.
Otherwise the variable shows 'undefined' output.
Syntax:
var_name??"Default_value"
3. ternary operator:
This reduces the efforts for writing the if-else block
Syntax:
condition ? [If the condition is true] : [If the condition is false]
4. exponential operator:
This operator is used to raise a number to the power of other number
Syntax:
number ** power
5. concatenation operator:
It is given by '+' sign and it is used to join together string
or strings with variables.
TEMPLATE LITERAL
Because of this appraoch, we need to write multiple lines of code just to get a
simple output with multiple variables in it.
• This method helps us to write our output in a single line but in this we need
to use multiple inverted quotes ad concatenation operators.
• Even if we miss one of the quotes or operators, our entire output can go wrong.
3. Template Literal:
Typecasting
It is the process of converting the datatype from one form into another.
It is required so that we can use the data appropriately.
2. Number():
• This method helps us to convert our string into a number including the decimal values.
• Because of this method, we can convert the decimal strings into decimal numbers.
3. parseInt():
• This method helps us to convert our string into a number while ignoring the decimal
values.
• This method stops the conversion of the string as soon as it finds any non-numeric
character.
Conditional statement
##
Iterative Loops
In this, we exeute our code miltiple times until the given condition is valid.
Once the condition is invalid the execution of code stops.
1. A variable(Conditional variable)
2. Initializtion of the conditional variable
3. OPeration of conditional variable
• do-while
syntax
do{
Code block
}while(Condition)
• Disadvantage:
1. The syntax can get problematic at the times of debugging
2. The code gets executed at least once even if the condition is invalid
• while
syntax
while(Condition){
Code block
Advantage:
1. The syntax is more developer friendly while debugging
2. The code does not get executed at all if the condition is found invalid.
• for
syntax
Advantage:
1. It helps the developer by keeping the conditional variable declaration,
condition, and operation together.
Function
It is a non-primitive datatype in JS
It is used to create reusable code blocks which can be used whnever and wherever
necessary
It prevents the code from getting lengthy and errors from re-writing the same code lines.
The function works in two stages:
1. Declaration: We write the code block to be executed in this phase.
2. Calling: We exeute the given block using the name of the function
Syntax:
Declaration
function function_name(){
Code block
}
Calling
function_name()
Component of a function
2. Arguments: This is the actual data that we pass in function call and which
is used in paramters to perform the given operation
Extra arguments:
In rest params, all the extra arguements are stored in a collection which can later be
used for any desired purpose.
For this, we use rest operator.
3. Anonymous functions:
It is somewhat similar to a variable named function, only the difference is that the
function
stored in the variable does not have any name.
For calling this function, we need to call the variable in which the function is stored.
This type is commonly used in callback functions.
Return keyword :
When we calculate any value inside a function, it stays valid only until the function is being
called
The moment function call ends, the values inside function lose their existance.
If we want to use any value from inside the function on the outside, we won't be able to
do that.
For this, return keyword is useful.
Using return keyword, we can send a value from within the function to the outside of
function.
This value can be stored in a variable or displayed directly.
Using this return keyword, we can use our function to calculate values and use them
anywhere as per
the requirement
Callback function:
Nested functions:
These are the functions which are declared within a main function and are used only
within that function.
Such functions are mostly made up of logic which is limited to that particular main function
itself
Object
1. Literal method:
• We simply create a variable and store an object in the variable.
• This method is useful to create standalone objects.
2. Instance method:
• This method is used to create an object using "new" keyword and then
store the data in the object.
• This method can be used on other datatypes as well to create their objects.
This method is useful while creating multiple objects.
3. Constructor method:
• In this we use a constructor to create multiple objects of similar type.
• Constructor is a speacial type of function which is used to intialize
values to an object.
• This constructor is useful when we want to create multiple instances of same object
type.
Methods
These are the functions which are stored within an object and use the
data in the obejct to generate some output
The objects are entities made up of properties and methods which are used
to store very large amounts of data in form of key value pairs
Object Processing :
Key referencing :
This is used when we directly want to access the key from any object.
In this, the key is referred using the '.'
// myObj1.location = "Pune";
// console.log(myObj1);
Variable referencing :
This is used when we have the name of key stored in a variable and we need to
use that variable to access the obejct key
For this, we write the variable in '[var_name]' to find the key within the object.
*/
// myObj1[userKey] = newData;
// console.log(myObj1);
Object methods :
• Object.keys():
• It returns a collection of all the keys from the object
• Object.values():
• It returns all the values frmo the objects in form of a collection
• Object.entries():
• It returns a coleection of arrays made of the key value pairs in the given
object.
• Object.getOwnPropertyNames():
• It returns a colelction of all the enumerable and non-enumerable properties in
the object.
• Object.is():
• It checks whether both the arguments passed are exactly or not
• isFinite():
• This method check whether given value is Finite or not
•
• inNaN():
• It checks whether the given value is Not a number.
• Object.freeze():
• This method prevents modification of the values and also
• it does not allow adding any new keys to the object
•
• Object.isFrozen():
• It checks whether the object is frozen or not.
•
• seal():
• This method prevents adding any new keys to the object but we can
• modify the values of existing keys
• Object.isSealed():
• It checks whether the object is sealed or not.
Array
The datatype of an array is 'object'. To check whether the variable contains an array, we
use Array.isArray()
1. Literal method
2. Instance method
• length:
• It returns the no of elements in the array
• push:
It adds a new element at the end of the array
It returns the modified length of the array
• pop:
It removes one element from the end of the array
It returns the removed element from the end of the array
• unshift:
It adds an element to the beginning of the array
It returns the new length of the array after adding a new element in the
beginning
• shift:
It removes one element from the beginning of the array.
It returns the element which was removed from the beginning of the array
• splice:
• splice(starting_index, 0, replacement_elements):
It does not remove any elements from the array but it
keeps the replacement elements in the given starting index
• indexOf():
This method returns the index position of the first occurenace of the element.
• lastIndexOf():
This method returns the index position of the last occurence of the element.
• Array.isArray():
This method check whether the object passed is actually an object or an array.
• includes():
This method checkn sfor the presence of the given element within the array.
• fill():
THis method replaces the array elements with the static data(The data is constant).
It modifies the original array
• slice(starting_index, ending_index):
This method extracts a portion of our array and returns it.
It does not modify the original array
It supports negative values
• reverse():
This method reverses the array and it modifies the original array.
• sort():
This method arranges our array elements in alphabetical or numerical order.
• toString():
This method converts the array into a string.
It is a universal method, i.e. it is applicable for all datatypes.
• join(seperatorCharacter):
This method joins all the elements of array together
using the provided seperator character. It coverts the output to a string.
• concat():
It joins together arrays.
• flat():
It merges the nested array within an array in to the main array.
• valueOf():
It is used to return the as it is value of the given array.
• from():
It converts a string into an array
• filter(callback):
This method uses a callback function to check the elements and return only
those elements which match the given condition.
This method filters the array elements as per the given codition.
• some(callback):
This method uses a callback function to check every element with a condition. If
any of elements matches the condition it returns true.
This method returns false only when none of the elements matches the
condition.
• every(callback):
This method uses a callback to check whether all the elements match the
condition.
It will return true only when all the elements are matching the condition.
If a single element does not match the condition, the answer will be false.
• reduce(callback):
This method uses a callback function to process eacch and every element from the
array and return a single value
• Splice
• 1. It replaces, removes or adds the elements into the array
2. It takes starting index, no of elements and replacement elements as arguments
3. It modifies the original array
String :
• length:
It returns the count of characters in the string.
• slice(strating_index, ending_index):
It extracts a portion of string from the starting index
till before ending index. It supports the negative indices.
• substring(straing_index, ending_index):
It extracts a portion of string stating from the
given starting index till before the ending index. It does not support negative
indices.
The output with negative index positions is illogical.
• concat():
This method concatenates strings together.
• indexOf():
It returns the index position of first occurence of the given character
• lastIndexof():
It returns the index position of last occurence of the given character.
**The above two methods will return -1 in case the element is found in the given string. This is
because
the string has positive index positions starting from 0. If the return is negative, that means no
such index
position is present and it symbolizes that the element is not present in string
• split('separator character'):
This method divides our string into array elements from
the given separator character.
• trim()/trimStart()/trimEnd():
These methods helps us to remove the whitespace from
the starting or ending of the string
• includes():
It check whether the given character/string is present in the string or not.
It is case sensitive.
• replace():
This method replaces the first occurence of the given character/string with
the replacement string/character.
• pad()/padStart()/padEnd():
These methods increase the length of the string to the desired
length by adding some character to start or end of the string.
Events :
The actions that are performed on a website using the inputs devices(mouse, keyboard),
window or forms
are called events
Javascript is an event driven language, i.e. it can respond to these actions by performing
some or
other task
1. Mouse events
2. Keyboard events
3. Window events
4. Form events
Mouse events :
The actions performed using the mouse are called mouse events.
1. onclick: This event occurs when we click the left mouse button
2. ondblclick: This event occurs when we double click the left mouse button
3. oncontextmenu: This event occurs when the mouse right button is clicked
4. onmouseover: This event occurs when the mouse pointer enters the element area
5. onmouseout: This event occurs when the mouse pointer leaves the element area.
6. onmousewheel: This event occurs when the mouse scroll wheel has been rotated
7. onmousedown: This event occurs when any mouse button is pressed down
8. onmouseup: THis event occurs when any mouse button that has been pressed in is left.
Keybaord events :
1. onkeypress: This event occurs when we press any printable key on the keyboard
(alphabets, symbols, space, enter, etc). This is deprecated event,
instead of this we use keydown event
2. onkeydown: This event occurs when any key of the keyboard is pressed.
This event is now used to identify the key combination in various platforms
3. onkeyup: This event occurs when any keyboard key that has been pressed in is
un-pressed
Window Events :
2. onscroll: This event occurs only when the scrollable content gets scrolled.
This event will not occur if there is no scrollable content and still
the mouse wheel is rotated.
3. onresize: This event occurs when the size of the element is changed.
Form Events :
Form is used to collet the data from user using input tags and submit the
data to the backend for further processing
1. onfocus: Focussing means clicking on the input field. The onfocus event occurs
when we focus onto any input field.
2. onblur: This event occurs when we click out from anyu input field and de-select it.
3. onchange: This event occurs when the data in the input field has been changed.
4. onselect: This event occurs when the data in the input field gets selected.
DOM
Using this DOM, we can access and modify the HTML elements through JS code.
1. getElementById:
Returns the particular element having the given id
2. getElementsByClassName:
It returns a collection of all elements having the given class
3. getElementsByTagName:
It returns a collection of all elements of the given tag name
4. getElementsByName:
It returns a collection of all elements having the given name
----------------------------------
1. innerHTML
Returns: It returns all the HTML content inside the given element.
Setting: It changes the HTML content inside the given element. It supports the
HTML tags.
2. outerHTML
Returns: It returns the HTML content from the element alonf with the element itself.
Setting: It replaces the entire element with the new given HTML content. It also
supports the HTML tags
3. innerText:
Returns: It ignores the HTML elements and returns only the text content from the
given element.
Settings: It changes the text content of the element and prints the HTML tags as it
is. It does not support the HTML tags
4. outerText:
Setting: It replaces the entire element with the given plain text content.
It does not apply the HTML tags.
5. textContent:
It returns the text content of the element with all the HTML indentations.
BOM
1. alert
2. prompt
3. confirm
Objects in BOM:
3. navigator: This gives us information about the browser and the user environment
(our device)
4. screen: This returns all the information about the screen of the device.
BOM methods:
Math Object :
JS gives us the math object which has many constant from mathematics and some
methods to perform mathematical operations.
pre-built
1. min():
This method returns the smallest number from given arguements.
It does not directly work with collection.
To implement this and max() on a collection we need to use spread operator.
2. max():
This method returns the largest number from the given arguments.
3. floor():
This method rounds off our decimal value to the previous integer.
4. ceil():
This method rounds off our decimal number to the next integer.
5. round():
This method rounds off our decimal avlue to an integer value based on the decimal
place
DP > 0.5 -> Next integer
DP < 0.5 -> Previous integer
DP == 0.5 -> Next integer
6. trunc():
This method removes the decimal value from the number and returns a pure integer
7. random():
This method returns a random number between 0 and 1
8. sqrt():
This method returns the square root of any given number
9. cbrt():
This method returns the cube root of any given number
10. pow():
Spread operator :
Because of this the time taking functions can perform in their own time while the
other function carry out their work
This asynchrnous behaviour can be implemented using:
1. callbacks
2. async and await
3. promises
4. setInterval
5. setTimeout
setInterval(callback, time_interval):
This method takes two arguments, i.e. a callback function and time interval in milliseconds
It executes the given callback function repeatedly after the given interval.
If their is any function performing its task, it will continue its work without being
interrupted by this ssetInterval.
This is how the setINterval will perform its task asynchronously.
setTimeout(callback, time_interval):
This method also takes two arguments, i.e. a callback function and time interval in
milliseconds
It will start the execution of the callback function after the given time interval.
But it executes the callback function only once.
after execution the setTimeout will stop