JavaScript Basics and Syntax Guide
JavaScript Basics and Syntax Guide
JavaScript Output:
1. Writing into an HTML element, using innerHTML.
2. Writing into the HTML output using [Link]().
** Using [Link]() after an HTML document is loaded, will delete all existing HTML:
3. Writing into an alert box, using [Link]().
4. Writing into the browser console, using [Link]().
JavaScript Statements:
1. JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
JavaScript Syntax
A. JavaScript Values: The JavaScript syntax defines two types of values:
1. Fixed values (Literal)
Numbers are written with or without decimals: ---------- 10, 10.58
Strings are text, written within double or single quotes. ---------- “shuvo”
2. Variable values (Variables)
variables are used to store data values.
JavaScript uses the keywords var, let and const to declare variables.
An equal sign is used to assign values to variables
All JavaScript identifiers are case sensitive.
Hyphens are not allowed in JavaScript. They are reserved for subtractions.
B. JavaScript Operators: JavaScript uses arithmetic operators ( + - * / ) to compute values.
C. JavaScript Expressions: An expression is a combination of values, variables, and operators,
which computes to a value.
D. JavaScript Keywords: JavaScript keywords are used to identify actions to be performed
E. JavaScript Comments: Code after double slashes // or between /* and */ is treated as a
comment.
F. JavaScript Character Set: JavaScript uses the Unicode character set.
JavaScript Variables
1. Variables are containers for storing data (storing data values).
2. All JavaScript variables must be identified with unique names.
3. These unique names are called identifiers.
4. JavaScript identifiers are case-sensitive.
5. It's a good programming practice to declare all variables at the beginning of a script.
1. var
2. let
3. const
4. nothing
Let:
1. If you think the value of the variable can change, use let.
2. Variables defined with let cannot be re-declared in same block.
3. Variables defined with let must be declared before use.
4. Variables defined with let have Block Scope.
Code:
let x = 5;
let y = 6;
let z = x + y;
Const:
1. If you want a general rule: always declare variables with const
2. Variables defined with const cannot be Re-declared.
3. Variables defined with const cannot be reassigned.
4. Variables defined with const have Block Scope.
5. JavaScript const variables must be assigned a value when they are declared:
6. Use const when you declare:
1. A new Array
2. A new Object
3. A new Function
4. A new RegExp
The keyword const is a little misleading. It does not define a constant value. It defines a constant
reference to a value.
You CAN:
1. Change the elements of constant array
2. Change the properties of constant object
Value = undefined:
Variables are often declared without a value. The value can be something that has to be calculated,
or something that will be provided later, like user input. A variable declared without a value will have
the value undefined.
JavaScript Operators
Operato Description
r
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator
Logical Operators:
Conditional/Ternary Operators: JavaScript also contains a conditional operator that assigns a value
to a variable based on some condition.
Type Operators:
Data Types
1. JavaScript variables can hold different data types: numbers, strings, objects.
2. JavaScript evaluates expressions from left to right. Different sequences can produce
different results:
3. JavaScript has dynamic types. This means that the same variable can be used to hold
different data types.
1. Number
2. String
3. Boolean
4. Object
5. Undefined
6. Function
7. bigInt
8. Symbol
Type Conversion:
JavaScript Events
1. HTML events are "things" that happen to HTML elements.
2. When JavaScript is used in HTML pages, JavaScript can "react" on these events.
3. An HTML event can be something the browser does, or something a user does.
Strings
1. A JavaScript string is zero or more characters written inside quotes.
2. You can use single or double quotes
3. You can use quotes inside a string, if they don't match the quotes surrounding the string
4. JavaScript strings are primitive values, created from literals:
5. Strings can also be defined as objects with the keyword new. Do not create Strings objects.
6. Comparing two JavaScript objects always returns false.
Escape Character:
1. \’ ' Single quote
2. \" “ Double quote
3. \\ \ Backslash
4. \b Backspace
5. \f Form Feed
6. \n New Line
7. \r Carriage Return
8. \t Horizontal Tabulator
9. \v Vertical Tabulator
String Methods:
1. All string methods return a new string. They don't modify the original string.
2. Strings are immutable: Strings cannot be changed, only replaced.
Code:
let text = “Pythonworld";
let s = [Link](/wo/gi , "red");
if( s = “Py” ){
[Link](s);
}
Ans: Py
9. trim (): The trim() method removes whitespace from both sides of a string:
10. trimStart(): removes whitespace only from the start of a string.
11. trimEnd() : removes whitespace only from the end of a string.
12. padEnd(): pads a string with another string:
13. charAt(): The charAt() method returns the character at a specified index (position) in a string.
Code :
let text = "HELLO WORLD";
let letter = [Link](1);
14. split() : A string can be converted to an array with the split() method:
code:
let text = "hello world ";
const myArray = [Link](“ ”);
[Link](myArray[0]);
15. repeat(): The repeat() method returns a string with several copies of a string.
Syntax : [Link](count)
Code :
let text = "Hello world!";
let result = [Link](4)
16. indexOf()
17. lastIndexOf()
18. search ()
19. match ()
20. matchAll()
21. includes ()
22. startsWith()
23. endsWith()
RegX
1. A regular expression is a sequence of characters that forms a search pattern.
2. regular expressions are often used with the two string methods: search() and replace().
Create a RegEx: There are two ways you can create a regular expression in JavaScript.
1. Using a regular expression literal: The regular expression consists of a pattern enclosed
between slashes /…/
cost regularExp = /abc/;
2. Using the RegExp() constructor function: You can also create a regular expression by calling
the RegExp() constructor function. For
const reguarExp = new RegExp('abc', “m”);
Modifiers:
1. i - Perform case-insensitive matching
2. g - Perform a global match (find all matches rather than stopping after the first match)
3. m - Perform multiline matching
Code:
Var x = “abc hellowqorl”;
Var reg = /[abc]/;
Var y = [Link](x);
1. [a-e] = specify a range of character using – inside square bracket.
2. [^a-g] = with all string expect the character in square bracket.
Template Literals
A. Back-Tics Syntax: Template Literals use back-ticks (``) rather than the quotes ("") to define a
string:
let text = `He's often called "Johnny"`;
let text =`The quick
brown fox
jumps over
the lazy dog`;
B. Interpolation: Template literals provide an easy way to interpolate variables and expressions
into strings.
The syntax is: ${...}
let firstName = "John";
let lastName = "Doe";
let text = `Welcome ${firstName}, ${lastName}!` ;
Syntax:
TYPICAL FUNCTION
function greet (string, …values) {
// do something
};
TAG FUNCTION
greet ` I 'm ${name} . I'm ${age} years old. `
Example:
function myTag(strings, personExp, ageExp) {
const str0 = strings[0]; // "That "
const str1 = strings[1]; // " is a "
const str2 = strings[2]; // "."
const ageStr = ageExp > 99 ? "Centenarian”: "youngster";
}
const output = myTag `That ${person} is a ${age}. `;
JavaScript Numbers
1. JavaScript Numbers are Always 64-bit Floating Point
2. Integers (numbers without a period or exponent notation) are accurate up to 15 digits.
Number Methods
1. toString() : Returns a number as a string.
let x = 123;
[Link]();
(123).toString();
(100 + 23).toString()
Date Objects
1. new Date() creates a new date object with the current date and time:
new Date()
new Date(date string)
new Date(year, month)
new Date(year, month, day)
new Date(year, month, day, hours)
new Date(year, month, day, hours, minutes)
new Date(year, month, day, hours, minutes, seconds)
new Date(year, month, day, hours, minutes, seconds, ms)
new Date(milliseconds)
7. You cannot omit month. If you supply only one parameter it will be treated as milliseconds.
const d = new Date(2018);
Displaying Dates:
1. toString() : convert date in string.
const d = new Date();
[Link]();
2. toDateString() : converts a date to a more readable format:
const d = new Date();
[Link]();
3. toUTCString(): method converts a date to a string using the UTC standard:
const d = new Date();
[Link]();
Date Input:
1. ISO Date "2015-03-25" (The International Standard)
2. Short Date "03/25/2015"
3. Long Date "Mar 25 2015" or "25 Mar 2015"
Parsing Dates :
Parse() method to convert it to milliseconds.
let msec = [Link]("March 21, 2012");
[Link]():
1. [Link]() returns a random number between 0 (inclusive), and 1 (exclusive):
2. [Link]() always returns a number lower than 1
3. [Link]() used with [Link]() can be used to return random integers.
[Link] ([Link] () * 10);
Random Function:
1. Returns a random number between min (included) and max (excluded):
Code:
function getRndInteger(min, max) {
return [Link]([Link]() * (max - min)) + min;
}
2. Returns a random number between min and max (both included):
Code:
function getRndInteger(min, max) {
return [Link]([Link]() * (max - min + 1)) + min;
}
Conditional statements
A. If statement:
Use if to specify a block of code to be executed, if a specified condition is true.
if (condition) {
………………..
}
Use else to specify a block of code to be executed, if the same condition is false.
if (condition) {
………………….
} else {
……………………
}
Use else if to specify a new condition to test, if the first condition is false.
if (condition1) {
………………………….
} else if (condition2) {
…………………
} else {
…………………
}
B. Ternary Operator: JavaScript also contains a conditional operator that assigns a value to a
variable based on some condition.
Code : let voteable = (age < 18) ? "Too young" : "Old enough" ;
C. for: if you want to run the same code repeatedly, each time with a different value.
code :
for (let i = 0; i < [Link]; i++) {
text += cars[i] + "<br>";
}
D. for( x in y ) loop:
code :
const numbers = [45, 4, 9, 16, 25];
let txt = "";
for (let x in numbers) {
txt += numbers[x];
}
*** Do not use for in over an Array if the index order is important.
E. for/of: JavaScript for of statement loops through the values of an iterate object.
const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
text += x;
}
F. while:
G. do/while:
H. Switch statement:
The continue statement (with or without a label reference) can only be used to skip one loop
iteration. the break statement "jumps out" of a loop.
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Array
1. An array is a special variable, which can hold more than one value:
2. JavaScript, arrays use numbered indexes.
3. Last array index is [ [Link] - 1];
4. Arrays are a special type of objects.
5. Array indexes start with 0.
6. JavaScript does not support associative arrays.
Create array:
Method-1:
const array_name = [item1, item2, ...., ….];
Method-2:
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
Method-3:
Const car = new Array(“shuvo”,26); // no need to use new array method
Array is object:
1. Arrays are a special type of objects.
C. Instanceof (): The instanceof operator returns true if an object is created by a given constructor
cars instanceof Array;
E. join() : method also joins all array elements into a string. But we can specify the separator;
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link](" * ");
F. pop() : removes the last element from an array.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]();
H. shift (): removes the first array element and "shifts" all other elements to a lower index.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]();
I. unshift (): adds a new element to an array at the beginning , and "unshifts" older elements:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]("Lemon");
J. delete():
1. Array elements can be deleted using the JavaScript operator delete.
2. Using delete leaves undefined holes in the array.
K. find():
1. find() method returns the value of the first element that passes a test.
2. find() method executes a function for each array element.
3. find() method returns undefined if no elements are found.
4. find() method does not execute the function for empty elements.
5. find() method does not change the original array.
Syntax:
[Link]( function(currentValue, index, arr), thisValue)
find((element) => { /* … */ })
find((element, index) => { /* … */ })
find((element, index, array) => { /* … */ })
Code:
var array = [10, 20, 30, 40, 50];
var found = [Link](function (element) {
return element > 20;
});
L. findIndex():
1. The findIndex() method executes a function for each array element.
2. The findIndex() method returns the index (position) of the first element that passes a
test.
3. The findIndex() method returns -1 if no match is found.
4. The findIndex() method does not execute the function for empty array elements.
5. The findIndex() method does not change the original array.
Syntax
M. includes () :
1. The includes() method returns true if an array contains a specified value.
2. The includes() method returns false if the value is not found.
3. The includes() method is case sensitive.
N. concat(): creates a new array by merging (concatenating) existing arrays. The concat() method
can also take strings as arguments.
const G = ["Cecilie", "Lone"];
const B = ["Emil", "Tobias", "Linus"];
const C = [Link](B);
P. slice(removed):
1. The slice() method slices out a piece of an array into a new array.
2. The slice() method creates a new array.
3. The slice() method does not remove any elements from the source array.
4. The method then selects elements from the start argument, and up to (but not
including) the end argument.
Q. sort ():
Syntax:
sort()
sort((a, b) => { /* … */ } )
sort( compareFn )
sort( function compareFn( a, b) { ..… })
Specifies a function that defines the sort order. If omitted, the array elements are converted to
strings, then sorted according to each character's Unicode code point value.
Code:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]();
2. Numeric Sort:
By default, the sort() function sorts values as strings.
Because of this the sort() method will produce incorrect result when sorting numbers.
Code :
Ascending :
const points = [40, 100, 1, 5, 25, 10];
[Link](function(a, b){return a - b});
Descending:
const points = [40, 100, 1, 5, 25, 10];
[Link](function(a, b){return b - a});
3. Random Order:
const points = [40, 100, 1, 5, 25, 10];
[Link](function(){return 0.5 – [Link]()});
4. Sorting Object:
Code:
const cars = [
{ type:"Volvo", year:2016 },
{ type:"Saab", year:2001 },
{ type:"BMW", year:2010 }
];
[Link](function(a, b){return [Link] - [Link]});
map():
a. The map() method creates a new array by performing a function on each array element.
b. The map() method does not execute the function for array elements without values.
c. The map() method does not change the original array.
filter():
The [Link]() method is used to create a new array from a given array consisting of only those
elements from the given array which satisfy a condition set by the argument method.
const numbers = [45, 4, 9, 16, 25];
const over18 = [Link](myFunction);
1. callback: This parameter holds the function to be called for each element of the array.
2. element: The parameter holds the value of the elements being processed currently.
3. index: is optional, it holds the index of the current Value element in the array starting
from 0.
4. arr: This parameter is optional; it holds the complete array on which Array.
5. thisValue: This parameter is optional, it holds the context to be passed as this to be used
while executing the callback function. If the context is passed, it will be used like this for
each invocation of the callback function, otherwise undefined is used as default.
the callback function does not use the index and array parameters, so they can be omitted:
const numbers = [45, 4, 9, 16, 25];
const over18 = [Link](myFunction);
function myFunction(value) {
return value > 18;
}
reduce()--- ES6
1. The reduce() method runs a function on each array element to produce (reduce it to) a
single value.
2. The reduce() method works from left-to-right in the array.
3. The reduce() method does not reduce the original array.
Syntax:
// Arrow function
reduce( (accumulator, currentValue) => { … } ,initvalue)
reduce( (accumulator, currentValue, currentIndex) => { … } )
reduce( (accumulator, currentValue, currentIndex, array) => { /* … */ } )
reduce( (accumulator, currentValue) => { /* … */ }, initialValue)
reduce( (accumulator, currentValue, currentIndex) => { /* … */ }, initialValue )
reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }, initialValue)
// Callback function
reduce(callbackFn)
reduce(callbackFn, initialValue)
// Inline callback function
reduce(function (accumulator, currentValue) { /* … */ })
reduce(function (accumulator, currentValue, currentIndex) { /* … */ })
reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ })
reduce(function (accumulator, currentValue) { /* … */ }, initialValue)
reduce(function (accumulator, currentValue, currentIndex) { /* … */ }, initialValue)
reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }, initialValue)
Parameter:
1. function(accumulator, currentValue, index, arr) = It is the required parameter and is used to
run for each element of the array. It contains four parameters which are listed below:
a. accumulator: It is a required parameter and used to specify the initialValue or the
previously returned value of the function.
b. currentValue: It is a required parameter and is used to specify the value of the
current element.
c. currentIndex: It is an optional parameter and is used to specify the array index of
the current element.
d. array: It is an optional parameter and is used to specify the array object the current
element belongs to.
2. InitialValue = A value to which accumulator is initialized the first time the callback is called.
Create map
1. Instance of Object: we can create map object with new keyword.
Syntax: new Map()
code: const name = new Map();
2. With Constructor : If we want to initialize it directly from its constructor, we can pass an
array of “key-value” arrays:
Code:
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
Method of Maps :
A. set() method: Adding elements to a Map with the set() method:
const fruits = new Map ();
[Link]("apples", 500);
[Link]("bananas", 300);
B. get() Method: we can access Map elements using the get() method.
[Link]("apples");
C. size Property: You can get the number of elements in a Map using the size property.
[Link];
D. delete () Method: the delete() method to remove elements from a Map.
[Link]("apples");
E. has() Method : we can use the has() method to check if the element is in a Map
[Link]("apples");
F. forEach() Method: This method calls a function for each key/value pair in a Map:
let text = "";
[Link] (function(value, key) {
text += key + ' = ' + value;
})
G. entries() Method: this method returns an iterator object with the [key, values] in a Map:
Sets
Syntax :
const [a, b] = array;
const { a, b } = obj;
Destructing Arrays:
In JavaScript we access the array with index. We declared the array and then access the individual
value with help of index.
Code:
const person = [‘shuvo’, ‘karim’, ‘rahim’];
const x = person[0];
const y = person[1];
const z = person[2];
But in ES6 we can access the array with help of destructing assignment. we can use brackets [] for
array destructing. that the square brackets [ ] look like the array syntax but they are
not.
Code:
const person = [‘shuvo’, ‘karim’, ‘rahim’];
const [x, y, z] = person;
[Link](x);
Swapping Variables:
We can swap the variable using destructuring assignment.
Code:
let x = 4;
let y = 7;
[x, y] = [y, x];
[Link](x); // 7
[Link](y); // 4
Skip Items:
The array elements can be skipped as well using a comma separator. We can skip unwanted items in
an array without assigning them to local variables.
Object Destructuring:
In JavaScript, we access the object property by dot(.) operator.
Code:
const user = {
name = “shuvo”;
}
const person= [Link];
But in ES6 we can access the object property with help of destructing assignment.
Syntax:
Code:
var employee = {
name: 'Jon',
id: 12345,
};
var {name, id} = employee;
Error Handing:
If we return a null object in destructing, then JavaScript throw an error. To avoid this, you can use
the OR operator (||) to fallback the null object to an empty object:
Code:
let arrValue = [10];
let [x = 5, y = 7] = arrValue;
[Link](x) ; // 10
[Link](y) ; // 7
2. Object: we can also set default value in object destructing.
Code:
const person = {
name: 'Jack',
}
const { name, age = 26} = person;
[Link](name); // Jack
[Link](age); // 26
Nested Destructuring :
1. Array: You can perform nested destructuring for array elements.
const { a, ...others } = { a: 1, b: 2, c: 3 };
[Link](others); // { b: 2, c: 3 }
1. The spread operator is a tool that lets you spread out all the elements of an array or object
2. In JavaScript spread operator are added in ES6 version.
3. Spread operator are three dots (…) .
4. The spread operator (...) is used to expand or spread an iterable or an array.
5. It is mostly used in the variable array where there are more than 1 values are expected.
Syntax:
var variablename1 = [...value];
2. Expand Array: You can also create a shallow copy of an array with the spread syntax.
const arr1 = ['one', 'two'];
const arr2 = [...arr1, 'three', 'four', 'five'];
3. Clone Array: In JavaScript, objects are assigned by reference and not by values. Here change
in one variable results in the change in both variables.
let arr1 = [ 1, 2, 3];
let arr2 = arr1;
[Link](arr2); // [1, 2, 3]
// append an item to the array
[Link](4);
[Link](arr1); // [1, 2, 3, 4]
[Link](arr2); // [1, 2, 3, 4]
if you want to copy arrays so that they do not refer to the same array, you can use the
spread operator. This way, the change in one array is not reflected in the other.
let arr1 = [ 1, 2, 3];
let arr2 = [...arr1];
[Link](arr2); // [1, 2, 3]
[Link](4);
[Link](arr1); // [1, 2, 3, 4]
[Link](arr2); // [1, 2, 3]
4. concatenate arrays:
2. concatenate object:
const user1 = {
name: 'Jen',
age: 22,
};
const user2 = {
name: "Andrew",
location: "Philadelphia"
};
const concatUsers = {...user1, ...user2};
[Link](concatUsers)
Modules ------ES6
1. JavaScript modules rely on the import and export statements.
2. JavaScript modules allow you to break up your code into separate files.
A. Export:
You can export a function or variable from any file. You can create named exports two ways
1. In-line individually:
export const name = "Jesse";
export const age = 40;
2. All at once at the bottom:
const name = "Jesse"
const age = 40
export { name, age }
3. Default Exports
const message = () => {
const name = "Jesse";
const age = 40;
return name + ' is ' + age + 'years old.';
};
export default message;
B. Import:
You can import modules into a file in two ways, based on if they are named exports or default
exports.
1. Import from named exports
import { name, age } from "./[Link]";
2. Import from default exports
import message from "./[Link]";
Errors
B. throw Statement:
When an error occurs, JavaScript will normally stop and generate an error message. The throw
Statement allows you to create a custom error. The technical term for this is: JavaScript will throw
an exception (throw an error).
try {
If (x == "") {
throw "empty";
}
If (isNaN(x)) throw "not a number";
}
catch(err) {
[Link] = "Input is " + err;
}
C. finally, Statement:
The finally statement defines a code block to run regardless of the result.
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {
Block of code of the try / catch result
}
Scope
Scope determines the accessibility of variables, objects, and functions from different parts of the
code
Block scope:
1. Variables declared inside a { } block cannot be accessed from outside the block:
2. Variables declared with the var keyword can NOT have block scope.
{
let x = 2;
}
// x can NOT be used here
Function scope:
1. Variables declared within a JavaScript function, become LOCAL to the function.
2. Since local variables are only recognized inside their functions, variables with the same name
can be used in different functions.
3. Local variables are created when a function starts, and deleted when the function is
completed.
function myFunction() {
let carName = "Volvo";
}
Global scope:
1. A variable declared outside a function, becomes GLOBAL.
2. A global variable has Global Scope:
3. All scripts and functions on a web page can access it.
4. JavaScript, the global scope is the JavaScript environment.
5. In HTML, the global scope is the window object.
6. Global variables defined with the var keyword belong to the window object.
7. Global variables defined with the let keyword do not belong to the window object:
let carName = "Volvo";
function myFunction() {
// code here can also use carName
}
******
1. In "Strict Mode", undeclared variables are not automatically global.
2. Do NOT create global variables unless you intend to.
Hoisting
1. Hoisting is JavaScript's default behavior of moving declarations to the top.
2. a variable can be used before it has been declared.
x = 5; // Assign 5 to x
var x; // Declare x
LET:
1. Variables defined with let is hoisted to the top of the block, but not initialized as undefined.
2. Using a let variable before it is declared will result in a ReferenceError.
3. The variable is in a "temporal dead zone" from the start of the block until it is declared:
Const :
1. Using a const variable before it is declared, is a syntax errror, so the code will simply not run.
This keyword:
1. In an object method, this refers to the object.
2. Alone, this refers to the global object.
3. In a function, this refers to the global object.
4. In a function, in strict mode, this is undefined.
5. In an event, this refers to the element that received the event.
6. Methods like call(), apply(), and bind() can refer this to any object
Object
A javaScript object is an entity having state and behavior (properties and method). JavaScript is an
object-based language. Everything is an object in JavaScript.
Objects are variables too that allows you to store multiple collections of data.
JavaScript is template based not class based. We do not need to create classes in order to create
objects.
An object literal is a list of property key:values inside curly braces { }.
Syntax:
const object_name = {
key1: value1,
key2: value2
}
Code:
const person = {
firstName: "John",
lastName: "Doe",
};
A. Using Object Literal : we can create an object using an object literal. An object literal uses { } to
create an object directly.
Syntax:
Object = {
property1:value1,
property2:value2
...............
}
Code :
const person = {
Age: 50,
eyeColor : "blue"
};
Code :
const person = {};
[Link] = 50;
[Link] = "blue";
B. Using Instance of Object : Create a single object, with the new keyword. the new keyword is
used with the Object() instance to create an object.
Syntax:
const objectName = new Object();
Code:
const person = new Object ();
[Link] = 50;
[Link] = "blue";
Code :
function emp( id, name, salary){
[Link] = id;
[Link] = name;
[Link] = salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
Syntax:
[Link](prototype , [properties-Object])
prototype : It is the prototype object from which a new object must be created.
Properties-Object : It is optional parameter. It specifies the enumerable properties to be
added to the newly created object.
const city = {
name: "dhaka",
age : 36
}
const mym = [Link](city); // no result
const mym = [Link](city, name)
***** Objects are mutable: They are addressed by reference, not by value.
Object Properties:
A. Accessing property:
1. Using dot Notation:
Syntax: [Link]
Code:
const person = {
name: 'John',
age: 20,
};
[Link]([Link]); // John
2. Using bracket Notation:
Syntax : objectName["property"]
Code :
const person = {
name: 'John',
age: 20,
};
[Link](person["name"]); // John
B. Adding Property : we can add a property in an object by dot(.) notation.
Code:
const person = {
name: 'John',
age: 20,
};
[Link] = "English";
[Link]( person );
C. Deleting Property:
The delete keyword deletes a property from an object.
The delete keyword deletes both the value of the property and the property itself.
After deletion, the property cannot be used before it is added back again.
The delete operator is designed to be used on object properties. It has no effect on variables
or functions.
The delete operator should not be used on predefined JavaScript object properties. It can
crash your application.
Code:
const person = {
name: 'John',
age: 20,
};
delete [Link];
delete person["age"];
D. Checking Property : To check if a property exists in an object, you use the in operator.
The in operator returns true if the propertyName exists in the objectName.
Syntax:
propertyName in objectName
Code:
let employee = {
name: 'Peter',
roll: 'Doe',
};
[Link]('roll' in employee);
Objects Methods
A. Accessing Method:
1. When we add a function as a value of property, we called it method of object. We can
access an object method using a dot notation by calling object method name. For invoked
method we use bracket ().
syntax:
[Link]()
code:
const person = {
firstName: "John",
id: 5566,
fullName: function() {
return [Link] ;
}
};
name = [Link]();
2. If you access the Object method name without (), it will return the function definition:
Code:
name = [Link];
B. Adding Method: We can add a method with dot(.) notation and pass function as value.
Code:
const person = {
firstName: "John",
id: 5566,
};
[Link] = function(){
[Link](“this is method add”);
}
B. In a Loop:
Code:
const person = {
name: "John",
age: 30,
city: "New York"
};
C. [Link](): Any JavaScript object can be converted to an array using this method.
Code:
const person = {
name: "John",
age: 30,
city: "New York"
};
const myArray = [Link](person);
D. [Link](): Any JavaScript object can be stringified (converted to a string) with the
JavaScript function.
const person = {
name: "John",
age: 30,
city: "New York"
};
let myString = [Link](person);
1. A constructor is a special function that creates and initializes an object instance of a class.
2. In JavaScript, a constructor gets called when an object is created using the new keyword.
Without parameter:
function User () {
[Link] = 'Bob';
}
var user = new User ();
With parameter:
function Person (first, last, age, eye) {
[Link] = first;
[Link] = last;
}
const ob1 = new Person ("John", "Doe");
const ob2 = new Person ("Sally", "Rally");
[Link];
[Link];
function Person () {
[Link] = 'Sam'
}
let person1 = new Person();
let person2 = new Person();
Data properties : when access the property of object directly with dot(.)
Accessor properties: accessor properties are methods that get/set the value of an object with get
and set keyword.
1. get - to define a getter method to get the property value
2. set - to define a setter method to set the property value
JavaScript Getter:
1. getter() methods are used to access the properties of an object.
2. To create a getter method, the get keyword is used.
const student = {
firstName: 'Monica',
get getName() {
return [Link];
}
};
[Link]([Link]);
JavaScript Setter:
1. In JavaScript, setter methods are used to change the values of an object.
2. To create a setter method, the set keyword is used.
const student = {
firstName: 'Monica',
set changeName(newName) {
[Link] = newName;
}
};
[Link]([Link]);
[Link] = 'Sarah';
[Link]([Link]);
Object Prototypes
1. JavaScript is a prototype-based language.
2. Whenever we create a function using JavaScript, JavaScript engine adds a prototype property
inside a function.
3. Prototype property is basically an object (also known as Prototype object).
4. We can attach methods and properties in a prototype object
5. Which enables all the other objects to inherit these methods and properties.
6. All JavaScript objects inherit properties and methods from a prototype.
<script>
function Person(name, job){
[Link] = name;
[Link] = job;
}
const shuvo = new Person(“shuvo” , ”job”)
</script>
Property add: The JavaScript prototype property allows you to add new properties to object
constructors:
function Person(first, last) {
[Link] = first;
[Link] = last;
}
[Link] = "English";
Method add: The JavaScript prototype property also allows you to add new methods to objects
constructors:
function Person(first, last) {
[Link] = first;
[Link] = last;
}
[Link] = function() {
return [Link] + " " + [Link];
};
Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects.
Function
function myFunction(a, b) {
return a * b;
}
myFunction();
Function as Variable:
1. Function can be store in variable.
2. After a function expression has been stored in a variable, the variable can be used as a function.
3. Functions stored in variables do not need function names. They are always invoked (called) using
the variable name.
4. The function above ends with a semicolon because it is a part of an executable statement.
Syntax:
new Function( functionBody)
new Function(arg0, functionBody)
new Function(arg0, arg1, functionBody)
Function(functionBody)
Function(arg0, functionBody)
Function(arg0, arg1, functionBody)
Code :
const adder = new Function('a', 'b', 'return a + b');
Self-Invoking Functions
1. A self-invoking expression is invoked (started) automatically, without being called.
2. Function expressions will execute automatically if the expression is followed by ().
3. Function not necessary any name.
( Function () {
let x = "Hello!!”; // I will invoke myself
}) ();
Function Parameters
Parameter: When a value is passed when declaring a function, it is called parameter.
Argument: when the function is called, the value passed is called argument.
Anonymous functions
1. An anonymous function is a function without a name.
2. Anonymous function should write inside () bracket, if it is not assigning the variable.
Method- 1 :
function() {
// Function Body
}
Method-2 :
( function () {
………………………
});
3. if you want to create a function and execute it immediately after the declaration, you can
declare an anonymous function like this:
( function() {
[Link]('IIFE');
} )();
4. the anonymous function has no name between the function keyword and parentheses ().
Syntax:
let show = function() {
[Link]('Anonymous function');
};
show();
// ES6
const x = (x, y) => x * y;
const x = (x, y) => { return x * y };
Advanced syntax:
1. To return an object literal expression requires parentheses around expression:
(params) => ( { foo: "a" } )
2. Rest parameters are supported, and always require parentheses:
(a, b, ...r) => expression
3. Default parameters are supported, and always require parentheses:
(a=400, b=20, c) => expression
Code:
const obj = {
name : “shuvo”,
show : () => [Link]([Link]);
entry(value) {
[Link]=value;
},
}
[Link]();
[Link](“shuvo”);
Function Methods
1. call (),
2. apply (),
3. bind ()
call() method :
1. In JavaScript all functions are object.
2. The call() method takes arguments separately.
3. With the call() method, you can write a method that can be used on different objects.
Code–1:
const person = {
fullName: function() {
return [Link] + " " + [Link];
}
}
const person1 = {
firstName:"John",
lastName: "Doe"
}
[Link](person1);
Code-2:
const person = {
fullName: function(city, country) {
return [Link] + " " + [Link] + "," + city ;
}
}
const person1 = {
firstName : "John",
lastName : "Doe"
}
[Link](person1, "Oslo");
apply() Method:
1. The apply() method is like the call()
2. With the apply() method, you can write a method that can be used on different objects.
3. The apply() method takes arguments as an array.
Code :
const person = {
fullName: function(city, country) {
return [Link]+"," + city + "," + country;
}
}
const person1 = {
firstName:"John",
}
[Link](person1, ["Oslo", "Norway"]); // array in apply()
bind() method :
With the bind() method, an object can borrow a method from another object.
const person = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return [Link] + " " + [Link];
}
}
const member = {
firstName : "Hege",
lastName : "Nilsen",
}
let fullName = [Link](member);
Closures:
A) Nested Function: a function can also contain another function. This is called a nested
function.
Code:
function greet(name) {
function displayName() {
[Link]('Hi' + ' ' + name);
}
displayName();
}
greet('John'); // Hi John
B) Returning a Function: In JavaScript, you can also return a function within a function.
Code:
function greet(name) {
function displayName() {
[Link]('Hi' + ' ' + name);
}
return displayName;
}
const g1 = greet('John');
C) Closure:
A closure is created when a function is defined inside another function and the inner
function remembers variables from the outer function’s scope — even after the outer
function has finished executing.
Closures help us keep variables private (not directly accessible from outside).
They’re often used for data privacy and encapsulation in JavaScript.
Code:
function greet() {
let name = 'John';
function displayName() {
return 'Hi' + ' ' + name;
}
return displayName;
}
const g1 = greet();
[Link](g1);
[Link](g1());
Asynchronous
1. JavaScript functions are executed in the sequence they are called.
2. Not in the sequence they are defined.
function myFirst() {
myDisplayer("Hello");
}
function mySecond() {
myDisplayer("Goodbye");
}
myFirst();
mySecond();
mySecond();
myFirst();
Sometimes you would like to have better control over when to execute a function.
Suppose you want to do a calculation, and then display the result.
Example:
function myDisplayer(some) {
[Link]("demo").innerHTML = some;
}
function myCalculator(num1, num2) {
let sum = num1 + num2;
return sum;
}
let result = myCalculator(5, 5);
myDisplayer(result);
The problem of example above, is that you have to call two functions to display the result.
Other Way:
function myDisplayer(some) {
[Link]("demo").innerHTML = some;
}
function myCalculator(num1, num2) {
let sum = num1 + num2;
myDisplayer(sum);
}
myCalculator(5, 5);
The problem of example, is that you cannot prevent the calculator function from displaying the
result.
1. runtime
2. engine
A. Runtime:
Runtime is the environment in which a programming language executes. JavaScript’s runtime
majorly constitutes three things namely JavaScript Engine, Web API, Call stack. JavaScript can work
with asynchronous code as well as synchronous code.
The unique feature of JavaScript’s runtime is that even though JavaScript’s interpreter is single-
threaded, it can execute multiple codes at a time using concurrent fashion in a non-blocking way.
This enables asynchronous behavior. As the interpreter is not multithreaded, it rules out parallelism.
B. JavaScript Engine:
JavaScript engine can be considered as the heart of the runtime. It is the place where each code is
executed. JavaScript engine constitutes of Heap storage and call stack. Let’s understand each of
those. JavaScript is a single-threaded language. This means it has only one call stack and one
memory heap. Hence, it can only execute one code at a time. In other words, the code is executed in
an orderly fashion. It must execute one code in the call stack before moving to the next code to be
executed. There are two types of code tasks in JavaScript, asynchronous code which runs and gets
executed after certain loading, synchronous, which gets executed instantaneously.
1. Heap : It is the place where all the objects and data are stored. This is similar to the heap storage
we see on various other languages like C++, Java, etc. It contains the store of the data related to
all the objects, arrays, etc. that we create in the code.
2. Call Stack: It is the place where the code is stacked before the execution. It has the properties of
a basic stack (first in last out). Once a coding task is stacked into the call stack, it will be
executed. There is an event loop that takes place and this is the one that makes the JavaScript
interpreter smart. It is responsible for concurrent behavior.
3. Web API: JavaScript has the access to different web API’s and it adds a lot of functionality. For
example, JavaScript has the access to the DOM API, which gives access to the DOM tree to
JavaScript. Using this, we can make changes to the HTML elements present on the browser. Also,
you can think of the timer, which gives it access to the time-related functions, etc. Also, the
geolocation API which gives it access to the location of the browser. Like this, JavaScript has the
access to various other APIs.
4. Callback Queue: This is the place where asynchronous code is queued before passing to the call
stack. The passing of the code task from the callback queue to the call stack is taken care of by
the event loop. In addition to this, there is also a micro tasks queue.
JavaScript Callbacks
A function passed as an argument to another function is called callbacks. Callbacks are just the name
of a convention.
When doing a complex task, we break that task down into smaller steps. To help us establish a
relationship between these steps according to time (optional) and order, we use callbacks.
function myDisplayer(some) {
[Link]("demo").innerHTML = some;
}
function myCalculator (num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);
}
myCalculator (5, 5, myDisplayer);
**** When you pass a function as an argument, remember not to use parenthesis.
Right: myCalculator(5, 5, myDisplayer);
Wrong : myCalculator(5,5, MyDisplayer);
Callback Hell:
When multiple nested callback is called, callback hell occurred.
const makeBurger = () => {
getBeef(function(beef) {
cookBeef(beef, function(cookedBeef) {
getBuns(function(buns) {
putBeefBetweenBuns(buns, beef, function(burger) {
// Serve the burger
});
});
});
});
};
Asynchronous
1. Functions running in parallel with other functions are called asynchronous
2. In the real world, callbacks are most often used with asynchronous functions.
Asynchronous function:
1. setTImeout()
2. setInterval()
Promises
You write a function A() that fetch all the data from other website. After fetch data you show all the
data in a table. If data not fetch then table not show.
Here we learn two terms –
producing code: That do something and takes time. Here A() is producing code.
consuming code: That wants the result of the “producing code” once it’s ready. Here when data
fetch is complete table will show.
1. promise is a special JavaScript object that links the “producing code” and the “consuming code”
together.
2. Promises is an object which is invented to solve the problem of callback hell and to better handle
our tasks.
3. You must use a Promise method to handle promises.
Syntax Promise:
let promise = new Promise (function (resolve, reject) {
// executor (the producing code, "A ()")
});
1. The function passed to new Promise is called the executor. When new Promise is created, the
executor runs automatically. It contains the producing code which should eventually produce
the result
2. Its arguments resolve and reject are callbacks provided by JavaScript itself. Our code is only
inside the executor.
3. When the executor obtains the result, be it soon or late, doesn’t matter, it should call one of
these callbacks:
a. resolve(value) — if the job is finished successfully, with result value.
b. reject(error) — if an error has occurred, error is the error object.
Resolve called:
let promise = new Promise(function(resolve, reject) {
setTimeout(() => resolve("done"), 1000);
});
After one second of “processing”, the executor calls resolve("done") to produce the result. This
changes the state of the promise object:
Reject called:
let promise = new Promise(function(resolve, reject) {
setTimeout(() => reject(new Error("Whoops!")), 1000);
});
The call to reject(...) moves the promise object to "rejected" state:
Promise Consumers:
A Promise object serves as a link between the executor (the “producing code”) and the consuming
functions, which will receive the result or error.
1. Param_1: It is a function. First function is executed if promise is resolved and a result is received.
2. Parram_2: It is also a Function. Second function is executed if promise is rejected.
If we’re interested only in successful completions, then we can provide only one function argument
to .then:
catch() :
catch() is invoked when a promise is either rejected or some error has occurred in execution. It is
used as an Error Handler whenever at any step there is a chance of getting an error
.catch( param_1 )
Param_1: it is a function. Function to handle errors or promise rejections.
Finally() :
1. The .finally() handler performs cleanups like stopping a loader, closing a live connection, and so
on.
2. The finally() method will be called irrespective of whether a promise resolves or rejects.
3. It passes through the result or error to the next handler which can call a .then() or .catch() again.
4. A finally handler has no arguments. In finally we don’t know whether the promise is successful or
not.
5. A finally handler also shouldn’t return anything. If it does, the returned value is silently ignored.
promise = getPromise(ALL_POKEMONS_URL);
[Link](() => {
loading = false;
[Link](`Promise Settled and loading is ${loading}`);
}).then((result) => {
[Link]({result});
}).catch((error) => {
[Link](error)
});
Promise Chain
The [Link]() call always returns a promise. This promise will have the state as pending and
result as undefined. It allows us to call the next .then method on the new promise.
1. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]
6. [Link]
JavaScript Async
1. "async and await make promises easier to write"
2. async makes a function return a Promise
3. await makes a function wait for a Promise
Async Syntax:
async function myFunction() {
return "Hello";
}
myFunction().then(
function(value) {myDisplayer(value);},
function(error) {myDisplayer(error);}
);
Await Syntax:
1. The await keyword can only be used inside an async function.
2. The await keyword makes the function pause the execution and wait for a resolved promise
before it continues:
JSON
JSON Example:
{
"employees": [
{ "firstName":"John", "lastName":"Doe" },
{ "firstName":"Anna", "lastName":"Smith" },
{ "firstName":"Peter", "lastName":"Jones" }
]
}
JSON Syntax Rules:
Use the JavaScript built-in function [Link]() to convert the string into a JavaScript object:
Use the JavaScript built-in function [Link]() to convert object into a JSON string
Class
1. Use the keyword class to create a class.
2. Always add a method named constructor():
3. Then add any number of methods.
Syntax:
class ClassName {
constructor() { ... }
method_1() { ... }
method_2() { ... }
}
Code:
class Car {
constructor(name, year) {
[Link] = name;
[Link] = year;
}
age() {
let date = new Date();
return [Link]() - [Link];
}
}
let myCar1 = new Car("Ford", 2014);
let myCar2 = new Car("Audi", 2019);
Class Inheritance:
To create a class inheritance, use the extends keyword.
class Car {
constructor(brand) {
[Link] = brand;
}
present() {
return 'I have a ' + [Link];
}
}
class Model extends Car {
constructor(brand, mod) {
super(brand);
[Link] = mod;
}
show() {
return [Link]() + ', it is a ' + [Link];
}
}
To add getters and setters in the class, use the get and set keywords.
class Car {
constructor(brand) {
[Link] = brand;
}
get cnam() {
return [Link];
}
set cnam(x) {
[Link] = x;
}
}
even if the getter is a method, you do not use parentheses when you want to get the property value.
Web API
1. It can extend the functionality of the browser
2. It can greatly simplify complex functions
3. It can provide easy syntax to complex code
Geolocation API
The Geolocation API allows the web application to access your location if you agree to share it.
Method:
1. [Link]():
getCurrentPosition(function )
getCurrentPosition(success, error)
getCurrentPosition(success, error, options)
code:
[Link]( show , onError);
function show( e ){
[Link](e)
}
2. [Link]()
3. [Link]()
Example:
<input id="id1" type="number" >
<button > <p id="demo"></p>
<script>
function myFunction() {
const m = [Link]("id1");
if (! [Link]() ) {
[Link]("demo").innerHTML = [Link];
}
}
</script>
Validity Properties:
Example-1:
<input id="id1" type="number" max="100">
<button > <p id="demo"></p>
<script>
function myFunction() {
let text = "Value OK";
if ([Link]("id1").[Link]) {
text = "Value too large";
}
}
</script>
History API
The Web History API provides easy methods to access the [Link] object.
Code:
<button Back</button>
<script>
function myFunction() {
[Link]();
}
</script>
Method && Properties:
1. length: Returns the number of URLs in the history list
2. back(): Loads the previous URL in the history list
3. forward(): Loads the next URL in the history list
4. go(): Loads a specific URL from the history list
Storage API
The Web Storage API is a simple syntax for storing and retrieving data in the browser. There are two
types of storage:
A) localStorage Object:
1. The localStorage object provides access to a local storage for a particular Web Site. It allows
you to store, read, add, modify, and delete data items for that domain.
2. The data is stored with no expiration date, and will not be deleted when the browser is
closed.
3. The data will be available for days, weeks, and years.
code:
[Link]("name", "John Doe");
[Link]("name");
B) sessionStorage Object:
1. The sessionStorage object is identical to the localStorage object.
2. The difference is that the sessionStorage object stores data for one session.
3. The data is deleted when the browser is closed.
Code:
[Link]("name", "John Doe");
[Link]("name");
Method and Property:
1. key(n): Returns the name of the nth key in the storage
2. length: Returns the number of data items stored in the Storage object
3. getItem(keyname): Returns the value of the specified key name
4. setItem(keyname, value): Adds a key to the storage, or updates a key value (if it already
exists)
5. removeItem(keyname): Removes that key from the storage
6. clear (): Empty all key out of the storage
C) cookie:
An HTTP cookie is a piece of data that a server sends to a web browser. Then, the web browser
stores the HTTP cookie on the user’s computer and sends it back to the same server in the later
requests.
Workers API
A web worker is a JavaScript running in the background, without affecting the performance of the
page.
Worker: Web Workers are a simple means for web content to run scripts in background threads.
The worker thread can perform tasks without interfering with the user interface.
1. Check worker:
if (typeof(Worker) !== "undefined") {
} else {
2. Create worker:
w = new Worker("demo_workers.js");
3. Method:
a) postMessage(message : Object, [transfer : Array]) :
b) onmessage:
[Link] = ()=>{
}
c) onerror:
[Link]=()=>{
}
d) terminate() :
[Link]();
Fetch: The fetch () method in JavaScript is used to request data from a server. The request can be of
any type of API that return the data in JSON or XML.
Syntax:
fetch (param_1, param_2)
. then ( response => [Link]() )
. then ( data => [Link](data) );
Param_1: the URL to access.
Param_2: It is an array of properties. It is an optional parameter.
Code:
const data = { username: 'example' };
let options = {
method: 'POST',
headers: {
'Content-Type': 'application/json ;
charset=utf-8'
},
body: [Link](data)
}
let req = fetch ( "[Link] , options );
[Link](res => res. json () )
. then ( d => { [Link](d) })
Async Await: With Async Await method with fetch() method to make promises in a more concise
way. Async functions are supported in all modern browsers.
Syntax:
async function funcName(url){
const response = await fetch(url);
var data = await [Link]();
}
BOM
Window Location
1. The [Link] object can be used to get the current page address (URL)
2. We can redirect the browser to a new page.
3. The [Link] object can be written without the window prefix.
Property :
a. [Link] - returns the href (URL) of the current page
b. [Link] - returns the domain name of the web host
c. [Link] - returns the path and filename of the current page
d. [Link] - returns the web protocol used (http: or https:)
e. [Link]() - loads a new document
code :
[Link]("demo").innerHTML = [Link];
[Link]("demo").innerHTML = [Link];
DOM – 65 (yahoo)
GET :
1. innerText: it return all text only inside the tag.
Code :
<div>
<p>The text content of the button element is </p>
<p id="demo"> </p>
<p>The innerText property and earlier.</p>
</div>
var x = [Link](“main”).innerText;
Output:
The text content of the button element is.
The innerText property and earlier
SET
1. innerText: we can change text inside tag.
[Link](“main”).innerText=”hello world”;
CSS style
style :
1. with this we can get element style.
2. We can change CSS of element.
3. To set value for CSS property we use camel case.
<p id=”main” style=” border:1px solid red; color:black; ”> hello world </p>
[Link](“#main”).[Link]=”blue”;
className:
1. We can get class attribute value of an element.
2. we can set class in an element .
3. it return string.
<p style=” border:1px solid red; color: black; ”> hello world </p>
[Link](“#main”).className =”blue”;
classList:
1. We can get class attribute value of an element.
2. we can set class in an element .
3. it return array of class.
<p style=” border:1px solid red; color: black; ”> hello world </p>
[Link](“#main”).classList =”blue”
method of classList:
a. add(): we add class in element by it.
<p style=” border:1px solid red; color: black; ”> hello world </p>
[Link](“#main”).[Link](“xyz”) ;
b. remove(): we can remove class attribute .
<p style=” border:1px solid red; color: black; ”> hello world </p>
[Link](“#main”).[Link](“xyz”) ;
c. Length: we can count how many class in element.
d. toggle : we toggle class attribute by this method.
EVENT --66
1. Click (onclick)
2. Double click ( ondbclick)
3. Right click (onContextMenu)
4. Mouse hover (onmouseenter)
5. Mouse Out (onmouseout)
6. Mouse Down (onmousedown)
7. Mouse up (onmouseup)
8. Key press (onkeypress)
9. Key Up (onkeyup)
10. Load (onload)
11. Unload (onunload)
12. Resize (onresize)
13. Scroll (onscroll)
addEventListener:
1. With this we can add an event handler to an element.
2. Here in event on not add
Traversal Method
1. parentNode
2. parentElement
3. Children
4. childNOdes
5. firstChild
6. firstElementChild
7. lastChild
8. lastElementChild
9. nextElementSibling
10. nextSibling
11. previousElementSibling
12. previousSibling