JavaScript Is The1
JavaScript Is The1
specified index (or indices). The difference between slice() & substring() is
that start and end values less than 0 are treated as 0 in substring().
If end parameter is omitted, substring() extracts characters to the end of the string.
OUTPUT
'bai'
1. (3). substr() :
returns a portion of the string, starting at the specified index and extending for a given number
of characters (length) afterwards. The difference between slice() & substr() is that
the second parameter specifies the length of the extracted part.
If length is omitted or undefined, or if start + length >= [Link], substr() extracts
characters to the end of the string.
OUTPUT
'New'
2. (4). replace() :
returns a new string with one, some, or all matches of a pattern replaced by a replacement.
The pattern can be a string or a RegExp, and the replacement can be a string or a
function called for each match. If pattern is a string, only the first occurrence will be
replaced. The original string is left unchanged. By default, the replace() method is case
sensitive.
OUTPUT
'Skillzam => Learn without limits!'
OUTPUT
Messi is the GOAT in football!
3. (5). replaceAll() :
let whatIfeel = 'I love cricket. Cricket is a team sport. Most popular sport
is "cricket".'
OUTPUT
I love football. Football is a team sport. Most popular sport is "football".
4. (6). toUpperCase() :
returns the calling string value converted to uppercase (the value will be converted to a string
if it isn't one). This method does not affect the value of the string itself since JavaScript strings
are immutable.
SYNTAX : toUpperCase()
OUTPUT
'SKILLZAM - LEARN WITHOUT LIMITS!'
5. (7). toLowerCase() :
returns the value of the string converted to lower case. toLowerCase() does not affect the
value of the original string itself.
SYNTAX : toLowerCase()
// toLowerCase() - make string lower-case
const pangram = "The quick brown FOX jumps over the lazy DOG."
const lowerPangram = [Link]()
[Link](lowerPangram)
OUTPUT
the quick brown fox jumps over the lazy dog.
removes whitespace from both sides of a string and returns a new string, without modifying
the original string. To return a new string with whitespace trimmed from just one end,
use trimStart() or trimEnd().
SYNTAX :
trim()
trimStart()
trimEnd()
let fastestBird = " Peregrine Falcon is the fastest bird in the world. "
OUTPUT
Peregrine Falcon is the fastest bird in the world.
Peregrine Falcon is the fastest bird in the world.
'Peregrine Falcon is the fastest bird in the world. '
SYNTAX :
padStart(targetLength [, padString])
padEnd(targetLength [, padString])
// Demo1 : padStart()
const numStart = '7';
[Link]([Link](3, '0')); // string output: 007
// Demo2 : padStart()
const cardNumber = '4321987612346789';
const lastFour = [Link](-4);
const cardMask = [Link]([Link], '*');
[Link](cardMask); // string output: ************6789
OUTPUT
007
************6789
// Demo1 : padEnd()
const numEnd = '7';
[Link]([Link](3, '0')); // string output: 700
// Demo2 : padEnd()
const cellNumber = '7173334444';
const firstThree = [Link](0,3);
const cellMask = [Link]([Link], '*');
[Link](cellMask); // string output: 717*******
OUTPUT
700
717*******
8. (10). at() :
returns the character at a specified index (position) in a string. This method allows for
positive and negative integers as parameters. Negative integers count back from the last string
character.
SYNTAX : at(index)
OUTPUT
Country Code is : 1
9. (11). charCodeAt() :
returns the unicode of the character at a specified index in a string. The return value is
a integer between 0 and 65535 representing the UTF-16 code unit
SYNTAX : charCodeAt(index)
OUTPUT
65
method takes a pattern and divides a String into an ordered list of substrings by searching for
the pattern, puts these substrings into an array, and returns the array.
There are two arguments separator and limit. separatoris a pattern describing where each
split should occur. limit is a non-negative integer specifying a limit on the number of
substrings to be included in the array.
OUTPUT
['She', 'sells', 'seashells', 'on', 'the', 'seashore.']
seashells
OUTPUT
['S', 'h', 'e', ' ', 's', 'e', 'l', 'l', 's', ' ', 's', 'e', 'a', 's', 'h',
'e', 'l', 'l', 's', ' ', 'o', 'n', ' ', 't', 'h', 'e', ' ', 's', 'e', 'a',
's', 'h', 'o', 'r', 'e', '.']
h
OUTPUT
['She sells seashells on the seashore.']
searches the entire calling string, and returns the index of the first occurrence of the specified
substring. If the searchString not found, then the method returns -1. The second
argument position is a number, the method returns the first occurrence of the specified
substring at an index greater than or equal to the specified number.
The difference between search() and indexOf() is search() does not have
second position argument whereas indexOf() cannot take regular expressions as search
values.
SYNTAX :
indexOf(searchString [, position])
lastIndexOf(searchString [, position])
OUTPUT
Index position where 'indigo' was found is 7
Index position where 'brown' was found is -1
let searchWhale = "The biggest whale in the world is Antarctic blue whale."
OUTPUT
Index position where 'whale' was found is 12
Index position where 'whale' was found is 49
let searchWhale = "The biggest whale in the world is Antarctic blue whale."
const lastWhale = [Link]('whale', [Link])
[Link]("Index position of last occurance of 'whale' is " + lastWhale)
OUTPUT
Index position of last occurance of 'whale' is 49
executes a search for a match between a regular expression and String object i.e. this
method searches a string or a regular expression in a String Object and returns the position
of the match. If not match found, then the method will return -1.
The difference between search() and indexOf() is search() does not have
second position argument whereas indexOf() cannot take regular expressions as search
values.
SYNTAX :
search(searchString)
search(regex)
OUTPUT
The first match for searchString occurs at index position 11
performs a case-sensitive search to determine whether one string may be found within another
string, returning boolean values true or false as appropriate.
const rhyme = "Baa, baa, black sheep, have you any wool?"
const isExists = [Link]('baa') // 'baa' exits and returns true
[Link](isExists)
OUTPUT
true
const rhyme = "Baa, baa, black sheep, have you any wool?"
OUTPUT
false
determines whether a string begins with the characters of a specified string, returning boolean
values of either true or false as appropriate. If the position argument is not specified, then it
will default to 0
OUTPUT
true
OUTPUT
false
determines whether a string ends with the characters of a specified string, returning boolean
values of either true or false as appropriate. If the position argument is not specified, then it
will default to 0
OUTPUT
true
OUTPUT
true
static method is a tag function of template literals. This is similar to the r prefix in Python, or
the @ prefix in C# for string literals. It's used to get the raw string form of template literals —
that is, substitutions (e.g. ${amount}) are processed, but escape sequences (e.g. \n) are not.
SYNTAX :
raw(strings, ...substitutions)
raw`templateString`
OUTPUT
C:[Link]
JavaScript file is located at C:\Users\Skillzam\Desktop\code\[Link]
Notice the first argument is an object with a raw property, whose value is an array-like object
(with a length property and integer indexes) representing the separated strings in the template
literal. The rest of the arguments are the substitutions. Since the raw value can be any array-like
object, it can even be a string!
For example, 'ABCD' is treated as ['A', 'B', 'C', 'D']. The following is equivalent to
`A${0}B${1}C${2}D`
constructs and returns a new string which contains the specified number of copies of the
string on which it was called, concatenated together. The argument count indicating the number
of times to repeat the string.
SYNTAX : repeat(count)
OUTPUT
buzzzzzz
OUTPUT
[Link]
OUTPUT
Skillzam Skillzam Skillzam
18. (19). toString() :
SYNTAX : toString()
OUTPUT
String {'Skillzam'}
Skillzam
SYNTAX : valueOf()
OUTPUT
String {'JavaScript is everywhere.'}
JavaScript is everywhere.
method retrieves the result of matching a string against a regular expression i.e it returns
an array containing the results of matching a string against a string or a regular
expression. If a regular expression does not include the g modifier (global
search), match() will return only the first match in the string.
SYNTAX :
match(searchString)
match(regex)
OUTPUT
['butter']
OUTPUT
['butter', 'butter', 'butter', 'butter']
OUTPUT
['A', 'B', 'C', 'D', 'a', 'b', 'c', 'd']
21. (22). matchAll() :
returns an iterator of all results matching a string against a "string or regular expression"
including capturing groups. If the parameter is a regular expression, the global flag g must be
set, otherwise a TypeError is thrown.
SYNTAX :
matchAll(searchString)
matchAll(regex)
OUTPUT
[object RegExp String Iterator]
[['butter'], ['butter'], ['butter'], ['butter']]
OUTPUT
[object RegExp String Iterator]
[['butter'], ['butter'], ['butter'], ['butter']]
boolean
boolean is a built-in primitive data type in JavaScript.
Booleans represent one of two values: true or false.
When you compare two values, the expression is evaluated and JavaScript returns
the Boolean answer
Booleans can also be constructed using the Boolean() object constructor.
Do not use the Boolean() constructor with new to convert a non-boolean value to a boolean
value — use Boolean as a function or a double NOT !! instead.
Booleans are often used in conditional testing.
Any numeric type is false if equal to zero or null, and true otherwise:
// Boolean values numeric type
Boolean(2017) // true
Boolean(-123) // true
Boolean(2.728281) // true
Boolean(Infinity) // true
Boolean(-Infinity) // true
Boolean(0) // false
Boolean(NaN) // false
For strings, Boolean() is false for empty strings and true otherwise:
// Boolean values for string type
Boolean("Workzam") // true
Boolean("2023") // true
Boolean('') // false
Boolean(true) // true
Boolean([12,24,36]) // true
Boolean({name: 'Brendan'}) // true
Boolean([]) // true
Boolean({}) // true
Boolean() // false
Boolean(false) // false
Boolean(null) // false
Boolean(undefined) // false
In JavaScript, a nullish value is the value which is either null or undefined. Nullish
values are always falsy.
// Falsy values
Boolean(false) // false
Boolean(0) // false
Boolean(NaN) // false
Boolean('') // false
Boolean(null) // false
Boolean(undefined) // false
Boolean Methods
1. (1). toString() :
returns a string of either true or false depending upon the value of the object.
SYNTAX : toString()
OUTPUT
Boolean {true}
true
string
2. (2). valueOf() :
returns the primitive value of a Boolean object.
SYNTAX : valueOf()
OUTPUT
Boolean {true}
true
boolean
undefined
undefined is a built-in primitive data type in JavaScript.
In JavaScript, a variable without a value, has the value undefined. The type is
also undefined.
It is a property of the global object. That is, it is a variable in global scope.
Any variable can be emptied, by setting the value to undefined.
An empty value has nothing to do with undefined. An empty string has both a legal value
and a type string
Boolean value of undefinedis false.
// undefined datatype
let studentCount;
typeof(studentCount)
OUTPUT
'undefined'
let btc
Boolean(btc)
OUTPUT
false
// undefined datatype used in "if"
let premium;
if (typeof(premium) === "undefined") {
[Link]("Premium value not assigned.")
}
typeof(premium)
OUTPUT
Premium value not assigned.
'undefined'
OUTPUT
Premium value not assigned.
'undefined'
null
null is a built-in primitive data type in JavaScript.
null is a special value which represents “nothing”, “empty” or “value unknown”.
null is not the same as 0, false, or an empty string. null is a data type of its own.
null value represents the intentional absence of any object value. It is treated as falsy for
boolean operations.
null is not an identifier for a property of the global object, like undefined can be.
Instead, null expresses a lack of identification, indicating that a variable points to no
object.
// null Datatype
OUTPUT
null
object
false
Difference between null and undefined
bigint
bigint is a built-in primitive data type in JavaScript.
bigint values represent numeric values which are too large to be represented by
the number primitive.
bigint is created by appending n to the end of an integer literal, or by calling
the BigInt() function (without the new operator) and giving it an integer value or string value.
bigint variables can also be created using the BigInt() object constructor method. BigInt()
can only be called without new. Attempting to construct it with new throws a TypeError.
Syntax : BigInt(value)
bigint value cannot be used with methods in the built-in Math object like
the number datatype.
bigint value cannot be mixed with a number value in operations.
0n is falsy, everything else is truthy.
bigint value is not strictly equal to a number value. Example : 1n !== 1 , this is true
bigint values and number values may be mixed in arrays and sorted.
bigint value follows the same conversion rules as number when:
// typeof Operator
typeof(999n) === 'bigint' // true
typeof(Object(999n)) === 'object' // true
// Operators
let bigNum = BigInt(9007199254740992) // BigInt() : 9007199254740992n
const bigNumPlus = bigNum + 7n // Addition : 9007199254740999n
const bigNumMinus = bigNum - 7n // Substract : 9007199254740992n
const bigNumProd = bigNum * 2n // Multiply : 18014398509481984n
const bigNumBy = 10n / 3n // Divide : 3n (decimal places are
truncated)
const bigNumMod = bigNum % 10n // Mod : 2n
const bigNumPow = 2n ** 53n // Power : 9007199254740992n
// Comparisons
9n === 9 // false
9n == 9 // true
9n > 99 // false
9n <= 9 // true
// Conditionals
!9n // false
!0n // true
// Array
mixedArray = [8, 2n, 0, -6n, 10, 0n] // BigInt & Number values may be mixed
Bigint Methods
1. (1). toString() :
returns a string representing this BigInt value in the specified radix (base).
SYNTAX : toString(radix)
OUTPUT
hugeNumber value is 1.2345678901234568e+39 and datatype is number
bigintNumObj value is 1234567890123456846996462118072609669120 and datatype is
bigint
largeNumber value is 1234567890123456846996462118072609669120 and datatype is
string
1. (2). valueOf() :
SYNTAX : [Link]()
[Link](largeNumValue) //
1234567890123456789012345678901234567890n
[Link](typeof(largeNumValue)) // bigint
[Link](bigNumValue) // 9007199254740992n
[Link](typeof(bigNumValue)) // bigint
OUTPUT
1234567890123456789012345678901234567890n
bigint
9007199254740992n
bigint
symbol
symbol is a built-in primitive data type in JavaScript.
symbol represents a unique "hidden" identifier that no other code can accidentally access.
All seven primitive types contain only a single value, whereas object are used to store
collections of data. The symbol type is used to create unique identifiers for objects.
symbol type doesn't have a literal form. To create a new symbol, you use the
global Symbol() method/[Link]() function creates a new unique value each time you
call it. The function accepts a description as an optional argument.
The description argument will make your symbol more descriptive. Attempting to construct it
with new throws a TypeError.
Syntax : Symbol(description)
// symbol DataType creation using Symbol() method
// with 'description' argument as 'pid'
const player = {
fname: "Leo",
lname: "Messi",
position: "Forward" }
OUTPUT
Player pid using Symbol: 98765
typeof(pid) is symbol
Player pid using Object: undefined
In the above example using the Symbol() function will create a Symbol pid whose value
(98765) remains unique throughout the lifetime of the program.
ECMAScript provides you with a global symbol registry that allows you to share symbols
globally.
Note that the "global Symbol registry" is only a fictitious concept and may not correspond
to any internal data structurein the JavaScript engine — and even if such a registry exists, its
content is not available to the JavaScript code, except through the for() and keyFor() methods.
[Link](key)
1. (1). [Link](key) method takes a string key as argument and returns a symbol
value from the registry.
2. (2). To create a symbol that will be shared, use the [Link]() method instead of calling
the Symbol() function.
3. (3). [Link](key) method accepts a single parameter that can be used for symbol's
description.
4. (4). [Link](key) method first searches for the symbol with the key in the global symbol
registry. It returns the existing symbol if there is one. Otherwise,
the [Link](key) method creates a new symbol, registers it to the global symbol registry
with the specified key, and returns the symbol.
[Link](symbol)
// [Link]() method
[Link](aadhar) // Symbol(aadhar)
[Link](citizenID) // Symbol(aadhar)
[Link](aadhar === citizenID) // true
[Link](typeof aadhar) // symbol
[Link](typeof citizenID) // symbol
// [Link]() method
[Link](keyAadhar) // aadhar
[Link](keyCitizenID) // aadhar
Symbol Methods
1. (1). toString() :
SYNTAX : toString()
Symbol('skill').toString() // "Symbol(skill)"
[Link]() // "Symbol([Link])
[Link]('zam').toString() // "Symbol(zam)"
1. (2). valueOf() :
SYNTAX : valueOf()
Arrays
Arrays are simple data structures.
Arrays are Ordered collections of values.
Arrays are generally described as "list-like objects"; they are basically single objects that
contain multiple values stored in a list.
It is a common practice to declare arrays with the const keyword. It does NOT define a
constant array. It defines a constant reference to an array.
Arrays are mutable by default i.e. their properties and elements can be changed without
reassigning a new value.
Arrays are resizable and can contain a mix of different data types.
Arrays are zero-indexed i.e. the first element of an array is at index 0, the second is at
index 1, and so on .
the length property will determine the length of an array.
Arrays have no fixed size, meaning we don't have to specify how big a array will be.
SYNTAX:
const arrayName = [item1, item2, item2, ...];
OUTPUT
type of academy array is object
Length of academy array is 8
The element at the '0' index is S
// Create array of English Vowels (string)
// using array literals
OUTPUT
['a', 'e', 'i', 'o', 'u']
OUTPUT
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
[Link](mixData)
OUTPUT
['One', 2, 'Three', [4, 'five', 6], 7.8, {key: 9}]
Creating array
Using a pair of square brackets to denote the empty array and then add items by indexing: [ ]
Using array literals i.e. square brackets, separating items with commas: [a], [a, b, c]
Using a string method split(): 'SKILLZAM'.split('') returns ['S', 'K', 'I', 'L',
'L', 'Z', 'A', 'M']
Using the array constructor function Array(item1, item2,
item2,...) or Array(arrayLength)
Array() can be called with or without new keyword. Both create a new Array instance.
The constructor builds a array whose items are the same and in the same order as iterable's items.
For example
Array('a','b','c') returns ['a', 'b', 'c']
If the only argument passed to the Array() constructor, is an integer between 0 and 232 - 1
(inclusive), this returns a new JavaScript array with its length property.
Array(3) returns [,,]
[Link](arrayOne)
OUTPUT
[6, 28, 496, 8128]
OUTPUT
[[1],[2,3],[4,5,6]]
['WORKZAM']
[,,,,,,,,]
['ಅ', 'ಆ', 'ಇ', 'ಈ']
OUTPUT
['tea', 'coffee', 'milk', 'eggs', 'honey']
OUTPUT
['tea', 'coffee', 'milk', 'eggs', 'bread']
OUTPUT
['tea', 'coffee', 'milk', 'eggs']
undefined
5
OUTPUT
A,B,C1,2,3
type of 'result' is string
Nested array
OUTPUT
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrixOne[0]
OUTPUT
[1, 2, 3]
matrixOne[0][0]
OUTPUT
1
(1) pop()
removes (pops) the last element from an array and returns that element.
pop() is a mutating method i.e. it changes length of the array.
SYNTAX : pop()
OUTPUT
Rahul
['Sachin', 'Dhoni', 'Virat', 'Zaheer']
(2) push()
OUTPUT
4
['NewDelhi', 'NewYork', 'London', 'Istanbul']
OUTPUT
7
[12, 24, 45, 67, 78, 89, 91]
(3) shift()
removes first element from an array & returns the removed element.
pop() method has similar behavior to shift(), but applied to the last element in an array.
shift() is a mutating method i.e. it changes length of the array.
shift() method is often used in condition inside while loop.
SYNTAX : shift()
OUTPUT
Sachin
['Dhoni', 'Virat', 'Zaheer', 'Rahul']
// every iteration will remove next element from an array, until it is empty
while (typeof (player = [Link]()) !== "undefined") {
[Link](player)
}
OUTPUT
Messi
Neymar
Ronaldo
Benzema
The 'players' array contains []
(4) unshift()
unshift() adds one or more elements to the beginning of an array and returns the new
length of an array.
If multiple elements are passed as arguments, they are inserted in the exact same order they
were passed.
OUTPUT
6
['Spinach', 'Kale', 'Collard', 'Avocado', 'Kiwi', 'Moringa']
(5) includes()
OUTPUT
true
OUTPUT
true
(6) indexOf()
returns the first index at which a given element can be found in the array, or -1 if it is not
present.
indexOf() method compares element to items of the array using strict equality ===.
The optional argument fromIndex will specify from which index position should the
search start.
For NaN values in the array, the indexOf() method will return -1.
OUTPUT
0
OUTPUT
4
(7) concat()
OUTPUT
symThree = ['INR', 'USD', 'EUR', 'JPY', 'CNY']
symOne = ['INR', 'USD', 'EUR']
symTwo = ['JPY', 'CNY']
OUTPUT
array3 = [2, 4, 6, 1, 3, 5, 7, 8]
array1 = [2, 4, 6]
array2 = [1, 3, 5]
// concat() merge two or more arrays and returns a new array
// concat() with no arguments
OUTPUT
newArray = ['apples', 'oranges', 'kiwi']
(8) join()
returns a new string by concatenating all of the elements in an array (or an array-like
object), separated by commas or a specified separator string.
If the array has only one item, then that item will be returned without using the separator.
The optional argument separator specifies a string to separate each pair of adjacent
elements of the array. The separator is converted to a string if necessary. If omitted, the array
elements are separated with a comma ,.
SYNTAX : join([separator])
[Link]() // 'Tea,Milk,Sugar'
[Link](", ") // 'Tea, Milk, Sugar'
[Link](" + ") // 'Tea + Milk + Sugar'
[Link]("") // 'TeaMilkSugar'
(9) reverse()
method reverses an array in place and returns the reference to the same array.
The elements order in the array will be turned towards the direction opposite to that
previously stated.
reverse() method does not have any arguments.
reverse() is a mutating method i.e. it changes order of the array. reverse() method returns
reference to the original array, so mutating the returned array will mutate the original array
as well.
In case you want reverse() to NOT mutate the original array, but return a shallow copy
array, then before calling reverse(), using the spread(...) operator syntax or [Link]()
SYNTAX : reverse()
OUTPUT
['cyan', 'orange', 'blue', 'green', 'red']
OUTPUT
newFibo = [80, 55, 34, 21, 13, 8, 5, 3, 2, 1, 1, 0]
newFibo = [89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 1, 0]
fibonacci = [89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 1, 0]
(10) slice()
slice() method returns a shallow copy of a portion of the original array into a new array
object.
slice() method will NOT modifiy the original array.
The two optional arguments start and end will specify the starting and
ending (end index not included), index position of the array.
If start is ommited, then it will default to 0 value.
If end argument is ommitted, then [Link] is used, which means all elements until the
end of array, to be extracted.
OUTPUT
['Spinosaurus', 'Tyrannosaurus']
OUTPUT
['Brachiosaurus', 'Patagosaurus']
OUTPUT
['Brachiosaurus', 'Patagosaurus', 'Spinosaurus', 'Tyrannosaurus']
(11) splice()
OUTPUT
['Ape', 'Cat', 'Cow', 'Dog', 'Fox']
OUTPUT
['Ape', 'Cow', 'Dog', 'Elk', 'Kob', 'Yak']
OUTPUT
['Ape', 'Cow', 'Dog']
Objects
Object is a complex datatypes in JavaScript.
Objects are variables too. But objects can contain many values.
JavaScript objects are containers for named values called properties.
Objects are collections of properties. Object properties can be defined within curly
brackets { } and have a comma-separated key : value pairs (key and value separated by a
colon : ).
It is a common practice to declare objects with the const keyword.
The values in object properties can be of any data type.
Objects does not allow duplicate properties.
Objects are utable. They are addressed by reference, not by value.
const playersBio = {
name: "Leo Messi",
team: "Paris Saint-Germain",
position: "Forward",
height: 170,
weight: 159,
birthdate: "24/6/1987",
age: 35,
nationality: "Argentina",
careerHistory: ["Barcelona","PSG","Argentina"],
isRetired: false
}
OUTPUT
{Keyone: 2, Keythree: 3}
const students = {
fName: "Jasmine",
lName: "Dsouza",
gender: "Female", // value is string DataType
age: 20, // value is number(integer) DataType
isGraduate: true, // value is boolean DataType
cgpa: 8.4, // value is number(decimal) DataType
favSub: ["Physics","Computers"] // value is array
}
[Link](students)
OUTPUT
{fName: 'Jasmine', lName: 'Dsouza', gender: 'Female', age: 20, isGraduate:
true, cgpa: 8.4, favSub: ['Physics', 'Computers', 'History']}
Creating Object
Object Literal: use a comma-separated list of key : value pairs within braces.
Example: { uid: 4098, name: 'Ravi Patil' }
Using the new keyword with in-built Object constructor function. Example: const cars =
new Object()
Using new with user-defined constructor function.
Using [Link]() to create new objects.
Using [Link]() to create new objects.
Using ES6 class to create objects
// Creating Object: 'Object Literal'
OUTPUT
{apples: 123, oranges: 456}
[Link](car)
OUTPUT
{year: 2022, make: 'Mahindra', model: 'XUV700'}
OUTPUT
Cricketer {fullName: 'Virat Kohli', runsScored: 183}
183
// Object 'biography'
const biography = {
name: "Cristiano Ronaldo",
team: "Manchester United",
position: "Forward",
height: 187,
weight: 183,
birthdate: "5/2/1985",
age: 37
}
// Object 'playerHist'
const playerHist = {
nationality: "Portugal",
careerHistory: ["ManU","Juventus","Real Madrid"],
isRetired: false
}
[Link](PlayerBio)
[Link]([Link])
OUTPUT
{name: 'Cristiano Ronaldo', team: 'Manchester United', position: 'Forward',
height: 187, weight: 183, birthdate: "5/2/1985", age: 37, nationality:
"Portugal", careerHistory: ["ManU","Juventus","Real Madrid"], isRetired: false
}
Cristiano Ronaldo
[Link]([Link])
[Link]([Link])
[Link](empOne)
OUTPUT
Fred Silva
Rio de Janeiro
Employee {fullname: 'Fred Silva', city: 'Rio de Janeiro'}
Almost "everything" is an object in JavaScript. All values, except primitives, are objects.
Access the properties of an object by referring to its key, inside square brackets.
const students = {
fName: "Jasmine",
lName: "Dsouza",
gender: "Female",
age: 20,
isGraduate: true,
cgpa: 8.4,
favSub: ["Physics","Computers","History"]
}
firstname = students['fName']
favSubject = students['favSub'][0]
[Link](firstname + ' loves ' + favSubject + '!')
OUTPUT
Jasmine loves Physics!
firstname = [Link]
scoreCGPA = [Link]
[Link](firstname + ' scored ' + scoreCGPA + '!')
OUTPUT
Jasmine scored 8.4!
const vehicle = {
year: 2021,
make: 'Mahindra'
}
OUTPUT
{year: 2021, make: 'Mahindra', model: 'XUV700'}
Change/Modify the value of a specific property of an object, by referring to its key name.
const users = {
fname: 'Guido',
lname: 'van Rossum',
email: 'guido@[Link]'
}
// Change 'email' property value
users['email'] = 'guido@[Link]'
[Link](users)
OUTPUT
{fname: 'Guido', lname: 'van Rossum', email: 'guido@[Link]'}
const mobile = {
[brand]: 25000, // 'Samsung' property key is taken from variable 'brand'
year: 2022
}
[Link](mobile)
OUTPUT
{Samsung: 25000, year: 2022}
const vehicle = {
year: 2021,
make: 'Mahindra',
model: 'XUV700'
}
OUTPUT
{year: 2021, make: 'Mahindra'}
in Keyword is used to determine, if a specified key is present in an object. For any a non-
existing property, in operator just returns undefined.
const users = {
fname: 'Guido',
lname: 'van Rossum',
email: 'guido@[Link]'
}
OUTPUT
true
[Link]() returns an array containing all of the [key, value] pairs of a given
object's own enumerable string properties.
[Link]() returns an array containing the key names of all of the given object's own
enumerable string properties.
[Link]() returns an array containing the values that correspond to all of a given
object's own enumerable string properties.
// Object - static methods
// [Link](), [Link](), [Link]()
const employee = {
empName: "Javid Khan",
designation: "Software Developer",
city: "Paris",
zip: 70123
}
OUTPUT
[['empName', 'Javid Khan'], ['designation', 'Software Developer'], ['city',
'Paris'], ['zip', 70123] ]
['empName', 'designation', 'city', 'zip']
['Javid Khan', 'Software Developer', 'Paris', 70123]
Nested Objects
JavaScript data structures support nesting. This means we can have data structures within data
structures. For object, property values in an object can be another object. You can access nested
objects using the dot (.) notation or the bracket [] notation
For example: An object containing another object.
const team = {
player1: {
name: 'Leo Messi',
position: 'Forward'
},
player2: {
name: 'Andres Iniesta',
position: 'Midfield'
},
player3: {
name: 'Xavi Hernandez',
position: 'Midfield'
}
}
team['player1']['name']
OUTPUT
'Leo Messi'
const player1 = {
name: 'Leo Messi',
position: 'Forward'
}
const player2 = {
name: 'Andres Iniesta',
position: 'Midfield'
}
const player3 = {
name: 'Xavi Hernandez',
position: 'Midfield'
}
const team = {
player1 : player1,
player2 : player2,
player3 : player3
}
team['player1']
OUTPUT
{name: 'Leo Messi', position: 'Forward'}
Object Methods
1. (1). hasOwnProperty() :
method returns a boolean indicating whether the object has the specified property as its own
property, as opposed to inheriting it.
The argument property is the String name or Symbol of the property to test.
SYNTAX : hasOwnProperty(property)
const player = {
name: 'Leo Messi',
position: 'Forward'
}
OUTPUT
true
2. (2). toString() :
SYNTAX : toString()
// toString() returns string representing the object
[Link]([Link]())
OUTPUT
Leo Messi plays as Forward
3. (3). valueOf() :
method of Object converts the this value to an object. This method is meant to be overridden
by derived objects for custom type conversion logic.
SYNTAX : valueOf()
// valueOf() methods
// Example : Area of a circle
function SquareRad(num) {
[Link] = num * num
}
[Link] = function() {
return [Link];
}
OUTPUT
Area of circle = 78.55
1. [1]. if statement
2. [2]. else if statement
3. [3]. else statement
4. [4]. switch statement
Decision-making statements evaluate the Boolean expression and control the program
flow depending upon the result of the condition provided.
JavaScript adopts the if, else if and else statements. In these conditional clauses, else
if and else blocks are optional; additionally, you can optinally include as few or as many else
if statements as you would like.
Simple if statement
OUTPUT
num1(24) is greater than num2(12)
if...else statement
The if statement alone tells us that, if a condition is true, it will execute a block of
statements and if the condition is false it won't.
But what if we want to do something else, if the condition is false. Here comes
the else statement.
We can use the else statement with if statement to execute a block of code when the
condition is false.
// 'if...else' statement
OUTPUT
num1(36) is lesser than num2(48)
Nested if statement
let ranNum = 28
OUTPUT
ranNum is smaller than 30
OUTPUT
givenNum is 100
switch statement
const billRate = 40
switch (billRate) {
case 25:
[Link]("Salary paid per month = 80000");
break;
case 40:
case 45:
[Link]("Salary paid per month = 125000");
break;
case 60:
[Link]("Salary paid per month = 190000");
break;
case 90:
[Link]("Salary paid per month = 300000");
break;
default:
[Link]("He/She is unbillable resource.");
}
OUTPUT
Salary paid per month = 125000
Shorthand if statement
If you have only one statement to execute, you can put it on the same line as
the if statement, without curly brackets.
// Shorthand "if" statement
OUTPUT
weightOne is heavier
***End of Code***
If you have only one statement to execute, one for if, and one for else, you can put it all on
the same line, without curly brackets.
This technique is known as Ternary Operators, or Conditional Operators.
// Shorthand "if...else" statement
// “Question mark” or "Ternary" operator
OUTPUT
num2 is largest
Loops in JavaScript
Loops are basically a simple set of instructions that gets repeated until a condition is met.
The various loop mechanisms offer different ways to determine the start and end points of
the loop.
In JavaScript, we have different kind of looping statements:
1. (1). while loops through a block of code while a specified condition is true
2. (2). do while also loops through a block of code while a specified condition is true
3. (3). for loops through a block of code a number of times
4. (4). for...of loops through the values of an iterable object
5. (5). for...in loops through the properties of an object
[1]. while Loop
while loop is used to execute a block of statements repeatedly until a given condition is
satisfied (true).
When the condition becomes false, the line immediately after the loop in the program is
executed.
while loop falls under the category of indefinite iteration. Indefinite iteration means that the
number of times the loop is executed isn't specified explicitly in advance.
When a while loop is executed, expression is first evaluated in a Boolean context and if it
is true, the loop body is executed. Then the expression is checked again, if it is still true then
the body is executed again and this continues until the expression becomes false.
If you forget to increase the variable used in the condition, the loop will never end.
A nested while loop is a while loop inside a while loop.
// while loop to print numbers : 1 to 5
let i = 1
while (i < 6) {
[Link](i)
i += 1 // remember to increment i, or else loop will continue forever
}
OUTPUT
0
1
2
3
4
5
let j = 0,
i = 1,
str = '';
while (i <= 5) {
j = 1
while (j <= i) {
str += (j + ' ')
j += 1
}
str += "\n";
i += 1
}
[Link](str)
OUTPUT
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
do while also loops through a block of code while a specified condition is true.
Unlike the while loop, the do while loop always executes the statement at least
once before evaluating the expression.
In the below Syntax of do while loop :
SYNTAX:
do {
// Block of code to be executed
}
while (condition);
let counter = 1
do {
[Link](counter)
counter++
} while (counter <= 3)
OUTPUT
1
2
3
for loop repeats until a specified condition evaluates to false. The JavaScript for loop is
similar to the Java and C for loop.
A nested for loop is a for loop inside a for loop.
In the below Syntax of for loop :
o expression1 = initial Expression Eg: let i = 0;
o expression2 = Condition Eg: i <= 10;
o expression3 = increment Expression Eg: i++
SYNTAX:
1. (1). Initializing expression expression1, if any, is executed. This expression usually initializes
one or more loop counters, but the syntax allows an expression of any degree of complexity.
This expression can also declare variables.
2. (2). Condition expression expression2 is evaluated. If the value of condition is true, the loop
statements execute. Otherwise, the for loop terminates. (If the condition expression
is omitted entirely, the condition is assumed to be true.)
3. (3). Block of code within curly braces {} executes multiple statements.
4. (4). Increment expression expression3, if any, is executed.
5. (5). Control returns to Step (2) i.e. condition expression expression2 is evaluated.
// for loop
// Example : Adding all single digit numbers as elements of an array
/****************************************************/
// Tracing 'for' loop in the above example
//
// 1st: singleDigit=0; true; o/p: 0 added to the array
// 2nd: singleDigit=1; true; o/p: 1 added to the array
// 3rd: singleDigit=2; true; o/p: 2 added to the array
// ....
// .... continue adding to the array
// ....
// 9th: singleDigit=8; true; o/p: 8 added to the array
// 10th:singleDigit=9; true: o/p: 9 added to the array
// 11th:singleDigit=10; false; exit the for loop
//
// The "numArray" contains = [0,1,2,3,4,5,6,7,8,9]
/*****************************************************/
OUTPUT
The "numArray" contains = [0,1,2,3,4,5,6,7,8,9]
// for loop
// Example : Find sum of all number in an array
/*****************************************************/
// Tracing 'for' loop in the above example
//
// 1st: x = 0; true; sumNum = 0 + 22 = 22
// 2nd: x = 1; true; sumNum = 22 + 44 = 66
// 3rd: x = 2; true; sumNum = 66 + 66 = 132
// 4th: x = 3; false; Exit the 'for' loop
//
// Sum of all the number in an array = 132
/*****************************************************/
OUTPUT
Sum of all the number in an array = 132
/*****************************************************/
// Tracing Nested 'for' loop in the above example
//
// Outer for loop - 1st of p: p = 1; true; o/p: p is:1
// 1st of q: q = 1; true; o/p: q is:1
// 2nd of q: q = 2; true; o/p: q is:2
// 3rd of q: q = 3; true; o/p: q is:3
// 4th of q: q = 4; false; Exit the inner q loop
// Outer for loop - 2nd of p: p = 2; true; o/p: p is:2
// 1st of q: q = 1; true; o/p: q is:1
// 2nd of q: q = 2; true; o/p: q is:2
// 3rd of q: q = 3; true; o/p: q is:3
// 4th of q: q = 4; false; Exit the inner q loop
// Outer for loop - 3rd of p: p = 3; false; Exit the outer p loop
//
/*****************************************************/
OUTPUT
p is: 1
q is: 1
q is: 2
q is: 3
p is: 2
q is: 1
q is: 2
q is: 3
const arrFlags = [
["INDIA","Orange","White","Green"],
["GERMANY","Black","Red","Yellow"],
["RUSSIA","White","Red","Blue"],
["COLOMBIA","Yellow","Blue","Red"],
["EGYPT","Red","White","Black"]
]
/*****************************************************/
// Tracing nested 'for' loop in the above example
//
// Outer for loop - 1st of a: a = 0; true; flagRow =
["INDIA","Orange","White","Green"] ; O/P: INDIA Flag Colors
// 1st of b: b = 1; true : O/P: Orange
// 2nd of b: b = 2; true : O/P: White
// 3rd of b: b = 3; true : O/P: Green
// 4th of b: b = 4; false Exit the inner b loop
// Outer for loop - 2nd of a: a = 1; true; flagRow =
["GERMANY","Black","Red","Yellow"] ; O/P: GERMANY Flag Colors
// 1st of b: b = 1; true : O/P: Black
// 2nd of b: b = 2; true : O/P: Red
// 3rd of b: b = 3; true : O/P: Yellow
// 4th of b: b = 4; false Exit the inner b loop
// ... continue
//
/*****************************************************/
OUTPUT
INDIA Flag Colors
Orange
White
Green
GERMANY Flag Colors
Black
Red
Yellow
RUSSIA Flag Colors
White
Red
Blue
COLOMBIA Flag Colors
Yellow
Blue
Red
EGYPT Flag Colors
Red
White
Black
for...of statement loops through the values of an iterable objects such as arrays, strings,
maps, NodeLists etc.
In the below Syntax of for...of loop :
o variable : For every iteration the value of the next property is assigned to the variable.
Variable can be declared with const, let, or var.
o iterable : An object that has iterable properties.
o Block of code within curly braces {} executes multiple statements.
SYNTAX:
let total = 0;
let arrayNum = [10, 20, 30, 40]
/*****************************************************/
// Tracing 'for...of' loop in the above example
//
// 1st : n = 10; total = 0 + 10 = 10
// 2nd : n = 20; total = 10 + 20 = 30
// 3rd : n = 30; total = 30 + 30 = 60
// 4th : n = 40; total = 60 + 40 = 100
// No more values in the array, hence exit the for loop
//
// Sum of all the number in an array = 100
/*****************************************************/
OUTPUT
Sum of all the number in an array = 100
const charArray = []
let charIndex = 0
/******************************************************/
// Tracing 'for...of' loop in the above example
//
// 1st: singleChar = S; o/p: S is added to the array
// 2nd: singleChar = K; o/p: K is added to the array
// 3rd: singleChar = I; o/p: I is added to the array
// 4th: singleChar = L; o/p: L is added to the array
// 5th: singleChar = L; o/p: L is added to the array
// 6th: singleChar = Z; o/p: Z is added to the array
// 7th: singleChar = A; o/p: A is added to the array
// 8th: singleChar = M; o/p: M is added to the array
// No more charaters in the string "SKILLZAM",
// hence exit the for loop
//
// The "charArray" contains = [S,K,I,L,L,Z,A,M]
/*****************************************************/
OUTPUT
The "charArray" contains = [S,K,I,L,L,Z,A,M]
// "for .. of" loop iterating Object
// Example : Iterate values in Object - turn data into an array
let gTotal = 0
const goalScores = {
Messi: 44,
Ronaldo: 43,
Diogo: 43,
Robert: 39,
Turpel: 37,
Suarez: 36,
Salah: 35,
Griezmann: 35,
Cifuente: 34,
Kane: 33
}
// goals = [44,43,43,39,37,36,35,35,34,33]
for (let goal of goals) {
gTotal += goal;
}
OUTPUT
The array of object values is = [44,43,43,39,37,36,35,35,34,33]
Total goals scored by top 10 players in the year 2018: 379
SYNTAX:
for (key in object) {
// Block of code to be executed
}
const car = {
year: 2022,
make: 'Mahindra',
model: 'XUV700'
}
[Link](str)
OUTPUT
2022 Mahindra XUV700
const bioMessi = {
name: "Leo Messi",
team: "PSG",
position: "Forward",
height: 170,
weight: 159,
birthdate: "24/6/1987",
age: 35,
country: "Argentina",
careerHist: ["PSG","FCB","Argentina"],
isRetired: false
}
/
******************************************************************************
********************/
// Tracing for loop
//
// 1st: bio = name; bioMessi[bio] = Leo Messi; o/p: NAME is Leo Messi
// 2nd: bio = team; bioMessi[bio] = PSG; o/p: TEAM is PSG
// 3rd: bio = position; bioMessi[bio] = Forward; o/p: POSITION is Forward
// 4th: bio = height; bioMessi[bio] = 170; o/p: HEIGHT is 170
// 5th: bio = weight; bioMessi[bio] = 159; o/p: WEIGHT is 159
// 6th: bio = birthdate; bioMessi[bio] = 24/6/1987; o/p: BIRTHDATE is
24/6/1987
// 7th: bio = age; bioMessi[bio] = 35; o/p: AGE is 35
// 8th: bio = country; bioMessi[bio] = Argentina; o/p: COUNTRY is
Argentina
// 9th: bio = careerHist; bioMessi[bio] = PSG,FCB,Argentina; o/p: CAREERHIST
is PSG,FCB,Argentina
// 10th: bio = isRetired; bioMessi[bio] = false; o/p: ISRETIRED is false
// No more name:value pair exists in the object literal, hence exit the for
loop
//
/
******************************************************************************
********************/
OUTPUT
NAME is Leo Messi
TEAM is PSG
POSITION is Forward
HEIGHT is 170
WEIGHT is 159
BIRTHDATE is 24/6/1987
AGE is 35
COUNTRY is Argentina
CAREERHIST is PSG,Barcelona,Argentina
ISRETIRED is false
Examples:
break statement
continue statement
break statement
Example of using break statement for a less trivial task. This loop will fill a list with all
Fibonacci numbers up to a certain value:
let a = 0,
b = 1,
n,
maxNum = 100,
index = 0;
const listFibo = [];
while (true) {
listFibo[index] = a;
index++;
n = a + b;
a = b;
b = n;
if (a > maxNum) {
break; // usuage of break statement to exit the loop
}
}
[Link](listFibo)
OUTPUT
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
continue statement
continue statement: The continue statement skips the remainder of the current loop,
and goes to the next iteration.
continue statement breaks one iteration (in the loop).
With the continue statement we can stop the current iteration of the for or while loop, and
continue with the next.
Example of using continue to print a string of odd numbers. In this case, the result could be
accomplished just as well with an if...else statement, but sometimes the continue statement
can be a more convenient way to express the idea you have in mind:
OUTPUT
1 3 5 7 9
label statement
label provides a statement with an identifier that lets you refer to it elsewhere in your
program.
To label JavaScript statements you precede the statements with a label name and a
colon :
With a label reference, the break statement can be used to jump out of any code block.
label names can not be a reserved words.
SYNTAX:
label:
statements
let total = 0,
i = 1;
OUTPUT
total = 1
total = 3
Functions in JavaScript
A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for your application and a high degree of code
reusing.
One way to organize our JavaScript code and to make it more readable and reusable is to
factor-out useful pieces into reusable function.
The function will allow you to call the same block of code without having to write it
multiple times. This in turn will allow you to create more complex scripts.
To use a function, you must define it somewhere in the scope from which you wish to call
it.
Function definition
For example, the following code defines a simple function named createFullName :
function createFullName() {
let fname = "Brendan",
lname = "Eich",
fullname = fname + " " + lname;
[Link](fullname)
}
Function invoking
Defining a function does not execute it. Defining it names the function and specifies what to
do when the function is called.
[Link](fullname)
}
OUTPUT
Brendan Eich
The return keyword allows you to actually save the result of the output of a function as a
variable.
The [Link]() function simply displays the output to web console, but doesn't save it for
future use. [Link]() doesn't return any value, as it returns undefined
// function Parameters & Arguments
OUTPUT
Brendan Eich
Default parameters
The most useful form is to specify a default value for one or more parameter.
Defaulting parameter values will creates a function that can be called with fewer arguments
than it is defined to allow.
If we call the function without argument, it uses the default value.
// Default function Parameter values
playerClub("Barcelona")
playerClub() // default parameter is set
playerClub("Al-Nassr")
OUTPUT
I play for Barcelona.
I play for no one.
I play for Al-Nassr.
1. [a]. giving only the mandatory argument: ask_ok('Enter the capital city: ')
2. [b]. giving one of the optional arguments: ask_ok('Enter the capital city: ', 2)
3. [c]. or even giving all arguments: ask_ok('Enter the capital city: ', 2, 'Just asked
to enter city name!')
OUTPUT
Enter the capital city: Hyderabad
true
Recursion Function
0! = 1
1! = 1 x 0! = 1 x 1 = 1
2! = 2 x 1! = 2 x 1 = 2
3! = 3 x 2! = 3 x 2 = 6
4! = 4 x 3! = 4 x 6 = 24
5! = 5 x 4! = 5 x 24 = 120
// Function recursion example
function factorial(num) {
let result = 0;
if (num === 1) {
return 1;
} else {
result = num * factorial(num-1);
return result;
}
}
let randNum = 5,
funcRtn = factorial(randNum);
OUTPUT
The factorial of 5 is 120
Nested Function
function indiaWorldCup() {
const runScored = [317,350,322,301];
function announceScores() {
let matchNum = 1;
function scoreBoard() {
for (let run of runScored) {
[Link](`${matchNum} : Team India scored ${run} runs.`);
matchNum++;
}
}
scoreBoard();
}
announceScores();
}
indiaWorldCup();
OUTPUT
1 : Team India scored 317 runs.
2 : Team India scored 350 runs.
3 : Team India scored 322 runs.
4 : Team India scored 301 runs.
JavaScript Examples
JavaScript Notes contains many examples for your understanding. With our online editor, you
can edit and test each example yourself.
JavaScript is a programming language that is used primarily to add interactivity and dynamic
behavior to websites. JavaScript code can be embedded directly into HTML web pages or
included in external script files, and it can be used to manipulate HTML and CSS, handle user
input, and interact with web servers through APIs. JavaScript is a crucial component of modern
web development, and it is used extensively in frameworks and libraries such as React, Angular,
and Vue.
null and undefined are both used to represent absence of a value, but they have slightly different
meanings. Undefined is a value that is assigned to a variable that has not been initialized, or to a
function parameter that has not been passed a value. Null, on the other hand, is a value that is
explicitly assigned to a variable or object property to represent the absence of a value. In
practice, null is often used as a default value when an object property is expected to be set later,
while undefined is typically used to represent a programming error or oversight.
Hoisting in JavaScript is a feature that allows variables and functions to be declared after they
are used in a program. This is possible because JavaScript uses two passes to interpret code: the
first pass scans the code for variable and function declarations and "hoists" them to the top of
their respective scopes, and the second pass executes the code. This means that a variable or
function can be used before it is declared, as long as it is declared somewhere in the same scope.
However, hoisted variables and functions are not initialized until their declaration statements are
reached, so they may have the value "undefined" until they are explicitly assigned a value.
What are the differences between JavaScript and other programming languages
like Java and Python?
There are several differences between JavaScript and other programming languages like Java and
Python:
JavaScript is a scripting language, while Java and Python are compiled languages.
JavaScript is mainly used for web development, while Java and Python are used for a variety
of applications, including web development, mobile app development, and data analysis.
JavaScript has a loose type system, while Java and Python have strict type systems.
JavaScript uses prototype-based inheritance, while Java and Python use class-based
inheritance.
JavaScript is single-threaded, while Java and Python can support multithreading.
There are many types of events in JavaScript, including mouse events (such as click, mouseover,
and mouseout), keyboard events (such as keypress and keydown), form events (such as submit
and change), and document and window events (such as load and resize).
What is the difference between a primitive data type and an object data type in
JavaScript?
A primitive data type is a value that is not an object and has no methods. Examples of primitive
data types in JavaScript include numbers, strings, booleans, null, and undefined. An object data
type, on the other hand, is a complex data type that can contain properties and methods.
Examples of object data types in JavaScript include arrays, functions, and objects.
A callback function is a function that is passed as an argument to another function and is then
executed when the parent function completes. Callback functions are commonly used in
JavaScript for asynchronous programming tasks, such as handling events or making API calls.
The event loop in JavaScript is a mechanism that allows for asynchronous execution of code in a
single-threaded environment. When an asynchronous operation is initiated, such as a network
request or a timer, the operation is placed in a queue and the program continues to execute.
When the operation is completed, a callback function is added to another queue. The event loop
constantly checks the callback queue and executes any functions that are waiting, in the order
they were added. This allows JavaScript to handle multiple asynchronous operations
simultaneously, without blocking the main thread.
let and const are block-scoped declarations, while var is function-scoped. Variables declared
with let and const cannot be redeclared in the same block, while var allows for redeclaration.
Additionally, variables declared with const cannot be reassigned a new value, while let and var
can be. Let and const are relatively new features of JavaScript that were introduced in ES6, while
var has been part of the language since its inception.
The double equals (==) operator in JavaScript compares two values for equality, allowing for
type coercion if necessary. For example, the expression "5" == 5 would evaluate to true, because
the string "5" is coerced into the number 5 for comparison. The triple equals (===) operator, on
the other hand, compares two values for equality without type coercion, so the expression "5"
=== 5 would evaluate to false, because the types are different.
JavaScript has several primitive data types, including number, string, boolean, null, undefined,
bigint and symbol. Additionally, JavaScript has a complex data type called object, which can
store collections of key-value pairs and functions. Arrays are a special type of object that can
store collections of values, and functions are a type of object that can be called like a regular
function.
A promise in JavaScript is an object that represents a value that may not be available yet, but will
be resolved at some point in the future. Promises are used to handle asynchronous operations,
such as network requests or database queries, and allow the program to continue executing while
the operation is in progress. Promises have three states: pending, fulfilled, and rejected. When a
promise is fulfilled, it means that the value is available and the promise's then() method is called
with the value as an argument. When a promise is rejected, it means that an error occurred and
the promise's catch() method is called with the error as an argument.
Both call() and apply() are methods in JavaScript that allow a function to be called with a
specific value for the "this" keyword, and with arguments passed in as an array-like object. The
main difference between call() and apply() is in how the arguments are passed in. With call(), the
arguments are passed in as a comma-separated list, while with apply(), the arguments are passed
in as an array. This means that apply() is useful when the number of arguments is not known
ahead of time, or when the arguments are already in an array-like object.
You can declare a variable in JavaScript using the var, let, or const keyword, like this:
A closure in JavaScript is a function that has access to variables and functions defined in its outer
scope, even after the outer function has returned. A callback function, on the other hand, is a
function that is passed as an argument to another function and is called at a later time, usually
after some asynchronous operation has completed. While both closures and callbacks are used to
handle asynchronous operations in JavaScript, closures are used to maintain access to variables
and functions in the outer scope, while callbacks are used to execute a function after an operation
has completed.
The main difference between let and var in JavaScript is in their scoping. Variables declared with
let are block-scoped, meaning they are only accessible within the block in which they are
declared. Variables declared with var, on the other hand, are function-scoped, meaning they are
accessible throughout the entire function in which they are declared. Additionally, variables
declared with let cannot be redeclared in the same block, while var allows for redeclaration.
In JavaScript, every object has a prototype property, which is a reference to another object. This
prototype object contains methods and properties that are inherited by the object.
When a property or method is accessed on an object, JavaScript first looks for that property or
method on the object itself. If the property or method is not found on the object, JavaScript then
looks for it on the object's prototype. If the property or method is still not found, JavaScript
continues the search up the prototype chain until it reaches the top level, which is typically the
[Link] object.
In other words, the prototype is a way to implement inheritance in JavaScript, allowing objects to
inherit properties and methods from other objects. This can help simplify code and make it more
efficient, by allowing objects to share common functionality without having to recreate it for
each object. To create a new object with a specific prototype, you can use the [Link]()
method, passing in the desired prototype object as an argument.
What is event bubbling in JavaScript?
Event bubbling is a mechanism in JavaScript where events propagate from the innermost to the
outermost elements in the HTML DOM. When an event is triggered on an element, it is first
handled by that element's event listener. If the event listener does not stop the event from
propagating, the event then bubbles up to the element's parent, and so on until it reaches the top-
level element.
Event bubbling can be useful for handling events on multiple elements with a common ancestor.
However, it can also cause unintended consequences if not handled properly. To stop event
bubbling, you can call the [Link]() method within the event listener.
The main difference between let and const in JavaScript is in their mutability. Variables declared
with let can be reassigned a new value, while variables declared with const cannot be reassigned.
Additionally, variables declared with const must be initialized with a value at the time of
declaration, while variables declared with let can be initialized later. Both let and const are
block-scoped, meaning they are only accessible within the block in which they are declared.
What is the difference between a for loop and a forEach loop in JavaScript?
A for loop in JavaScript is a traditional loop structure that iterates over a set of values using a
counter variable. A forEach loop, on the other hand, is a method on the Array object that allows
you to iterate over each element in an array and perform an action on each element. The main
difference between the two is that a for loop is more flexible and can be used for iterating over
any set of values, while a forEach loop is specifically designed for iterating over arrays.
Additionally, a forEach loop cannot be interrupted or stopped in the middle, while a for loop can
be exited using a break statement.
The main difference between a regular function and an arrow function in JavaScript is in their
syntax and the way they handle the this keyword. Arrow functions have a shorter syntax than
regular functions, and they do not bind their own this keyword. Instead, the this keyword in an
arrow function refers to the value of this in the context in which the arrow function was defined.
This can be useful for avoiding the common "this" pitfalls that can arise with regular functions.
The innerHTML property in JavaScript allows for the manipulation of the HTML content inside
an element, including tags and attributes. The textContent property, on the other hand, only
returns the text content of an element, without any HTML tags or attributes. It is generally
recommended to use textContent when dealing with text-only content, and innerHTML when
dealing with HTML content that may contain tags and attributes.
The "use strict" directive in JavaScript enables strict mode, which is a set of rules that must be
followed in order to write secure and efficient JavaScript code. In strict mode, certain JavaScript
features that are considered error-prone or dangerous are disabled, and stricter rules are enforced
for variable declaration, function invocation, and other aspects of the language. Using strict
mode can help to prevent common coding mistakes and improve the overall quality of JavaScript
code.
What is the difference between the spread operator (...) and the rest operator (...)
in JavaScript?
The spread operator (...) in JavaScript is used to expand an iterable (such as an array or a string)
into individual elements. It is often used to pass the contents of an array or an object as
arguments to a function or to concatenate arrays. The rest operator (...), on the other hand, is used
to capture a variable number of arguments passed to a function into an array. It is often used in
function declarations to allow for a variable number of arguments to be passed to the function.
The "this" keyword refers to the current execution context, which is typically the object that the
function is a method of. It is often used to access or manipulate properties of the current object
within a method, or to bind a function to a specific object. The behavior of the "this" keyword
can be affected by the way in which a function is called, such as with the "call" or "apply"
methods, or by using arrow functions, which bind the "this" keyword to the lexical scope of the
function.
The "use strict" directive in JavaScript is a feature introduced in ECMAScript 5 that enables
strict mode, which is a stricter version of JavaScript that eliminates some silent errors and
enforces stricter coding standards. In strict mode, certain actions that were previously ignored or
silently failed will now throw errors, making it easier to write more reliable and secure code. The
"use strict" directive is typically placed at the beginning of a JavaScript file or function to enable
strict mode for that scope.
A generator function in JavaScript is a special type of function that can be paused and resumed,
allowing for the generation of a sequence of values on demand. Generator functions are declared
using the "function*" syntax and use the "yield" keyword to produce a value and pause
execution. They can also receive input values when resumed using the "next" method.
You can define a function in JavaScript using the function keyword, like this:
An event in JavaScript is an action that occurs on a web page, such as a mouse click or a key
press.
What is the DOM in JavaScript?
You can access an element in the DOM using JavaScript using methods such as
[Link](), [Link](), or [Link]().
AJAX (Asynchronous JavaScript and XML) in JavaScript is a technique used to update parts of
a web page without reloading the entire page.
A constructor function in JavaScript is a function that is used to create and initialize an object.