0% found this document useful (0 votes)
2 views78 pages

JavaScript Is The4

The document provides an overview of various JavaScript string methods including includes(), startsWith(), endsWith(), raw(), repeat(), toString(), valueOf(), match(), and matchAll(), detailing their syntax and examples. It also covers the boolean, undefined, null, and bigint data types in JavaScript, explaining their characteristics, truthiness, and differences. Additionally, it discusses methods related to boolean values and the behavior of null and undefined in JavaScript.

Uploaded by

sivangsantonino
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views78 pages

JavaScript Is The4

The document provides an overview of various JavaScript string methods including includes(), startsWith(), endsWith(), raw(), repeat(), toString(), valueOf(), match(), and matchAll(), detailing their syntax and examples. It also covers the boolean, undefined, null, and bigint data types in JavaScript, explaining their characteristics, truthiness, and differences. Additionally, it discusses methods related to boolean values and the behavior of null and undefined in JavaScript.

Uploaded by

sivangsantonino
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

true

// includes() returns true/false depending on the strind found


// specifying the second argument "position"

const rhyme = "Baa, baa, black sheep, have you any wool?"

// Check if a string includes "Baa" - start at position 10


let isExists = [Link]('Baa',10)
[Link](isExists)

OUTPUT
false

1. (15). startsWith() :

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

SYNTAX : startsWith(searchString [, position])

// startsWith() returns whether a string begins with the characters

const mountain = "Mount Kilimanjaro is the highest mountain in Africa"


let doesBegin = [Link]('Mount')
[Link](doesBegin)

OUTPUT
true

// startsWith() returns whether a string begins with the characters


// specifying the second argument "position"

const mountain = "Mount Kilimanjaro is the highest mountain in Africa"

// Check if a string starts with "Kili" - start at position 10


let doesBegin = [Link]('Kili', 10)
[Link](doesBegin) // specify position as '6', it will return true

OUTPUT
false
2. (16). endsWith() :

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

SYNTAX : endsWith(searchString [, position])

// endsWith() returns whether a string ends with the characters

const mountain = "Mount Kilimanjaro is the highest mountain in Africa"


let doesEnd = [Link]('Africa')
[Link](doesEnd)

OUTPUT
true

// endsWith() returns whether a string ends with the characters


// specifying the second argument "position"

const mountain = "Mount Kilimanjaro is the highest mountain in Africa"

// Check if first 32 characters of a string ends with "highest"


let doesEnd = [Link]('highest', 32)
[Link](doesEnd)

OUTPUT
true

3. (17). raw() :

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`

// raw() returns raw string form of a given template literal


// substitutions are processed, but escape sequences are not
const filePath = `C:\Users\Skillzam\Desktop\code\[Link]`
[Link](filePath) // Observer the escape characters being ommited

const scriptPath = [Link]`C:\Users\Skillzam\Desktop\code\[Link]`


[Link](`JavaScript file is located at ${scriptPath}`)

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`

// raw() returns raw string form of a given template literal


// substitutions are processed

let text = [Link]({ raw: "ABCD" }, 0, 1, 2);


[Link](text)

OUTPUT
A0B1C2D

4. (18). repeat() :

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)

// repeat() returns a string with a number of copies


// Example 1

let word = 'buz'


let newWord = word + 'z'.repeat(5)
[Link](newWord)

OUTPUT
buzzzzzz
// repeat() returns a string with a number of copies
// Example 2

let website = 'w'.repeat(3).concat('.[Link]')


[Link](website)

OUTPUT
[Link]

// repeat() returns a string with a number of copies


// Example 3

let academy = 'Skillzam '


academy = [Link](3)
[Link](academy)

OUTPUT
Skillzam Skillzam Skillzam

5. (19). toString() :

returns a string representing the specified string value.

SYNTAX : toString()

// toString() returns a string representation

// new keyword will create a object from a constructor function (String())


const academyObj = new String('Skillzam');
[Link](academyObj);

const academy = [Link]()


[Link](academy);

OUTPUT
String {'Skillzam'}
Skillzam

6. (20). valueOf() :

returns the primitive value of a String object.


SYNTAX : valueOf()

// valueOf() returns the primitive value

const jsObj = new String('JavaScript is everywhere.');


[Link](jsObj);
[Link]([Link]());

OUTPUT
String {'JavaScript is everywhere.'}
JavaScript is everywhere.

7. (21). match() :

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)

// match() return array containing results of matching string


// Argument passed is a "string"

let tongueTwister = `Betty Botter bought a bit of butter,


but the bit of butter was bitter,
so Betty Botter bought a bit of better butter,
to make the bit of bitter butter better.`

const matchResult = [Link]('butter')


[Link](matchResult)

OUTPUT
['butter']

// match() return array containing results of matching Regex


// Argument passed is a "Regex" with 'g' modifier (global search )

let tongueTwister = `Betty Botter bought a bit of butter,


but the bit of butter was bitter,
so Betty Botter bought a bit of better butter,
to make the bit of bitter butter better.`
const regex = /butter/g // regex with g modifier (global search )
const matchResult = [Link](regex)
[Link](matchResult)

OUTPUT
['butter', 'butter', 'butter', 'butter']

// match() return array containing results of matching Regex


// Argument passed is a "Regex"
// using global(g) and ignoreCase(i) flags with match()

let alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"


const regex = /[A-D]/gi // regex with global & ignoreCase flags
const matchResults = [Link](regex);
[Link](matchResults)

OUTPUT
['A', 'B', 'C', 'D', 'a', 'b', 'c', 'd']

8. (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)

// matchAll() return iterator of all results matching a "string"


// Argument passed is a "string"

let tongueTwister = `Betty Botter bought a bit of butter,


but the bit of butter was bitter,
so Betty Botter bought a bit of better butter,
to make the bit of bitter butter better.`

const iterator = [Link]("butter") // string as argument


[Link](iterator)

const resultArray = [Link](iterator)


[Link](resultArray)

OUTPUT
[object RegExp String Iterator]
[['butter'], ['butter'], ['butter'], ['butter']]

// matchAll() return iterator of all results matching a "regex"


// Argument passed is a "Regex" with 'g' modifier (global search )

let tongueTwister = `Betty Botter bought a bit of butter,


but the bit of butter was bitter,
so Betty Botter bought a bit of better butter,
to make the bit of bitter butter better.`

const regex = /butter/g // regex with g modifier (global search )


const iterator = [Link](regex)
[Link](iterator)

const resultArray = [Link](iterator)


[Link](resultArray)

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 values for other values

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

Truthy & Falsy values

 All JavaScript values have an inherent truthyness or falsyness about them.


 Any object can be tested for "truth value", for use in an if or else if or while condition or
as operand of the Boolean operations.
 Falsy values listed below, rest all are truthy:

1. ➤ false
2. ➤ 0 (zero)
3. ➤ NaN
4. ➤ '' (empty string)
5. ➤ null
6. ➤ undefined

 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()
// toString() returns string of either true or false

// new keyword will create a object from a constructor function (Boolean())


const boolAcademyObj = new Boolean('Skillzam');
[Link](boolAcademyObj);

const academy = [Link]()


[Link](academy)
[Link](typeof(academy))

OUTPUT
Boolean {true}
true
string

2. (2). valueOf() :

returns the primitive value of a Boolean object.

SYNTAX : valueOf()

// valueOf() returns the primitive value

const boolworkzamObj = new Boolean('Workzam')


[Link](boolworkzamObj)

const techHire = [Link]()


[Link](techHire)
[Link](typeof(techHire))

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'

// undefined boolean value

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'

// undefined - any variable can be emptied

let price = 200


price = undefined // NOT recommend doing this
[Link](price)

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

const studentCount = null


[Link](studentCount)
[Link](typeof(studentCount)) // typeof null
[Link](Boolean(studentCount)) // Boolean value of null

OUTPUT
null
object
false

Difference between null and undefined

//null and undefined

typeof null // "object" (not "null" for legacy reasons)


typeof undefined // "undefined"
null === undefined // false
null == undefined // true
null === null // true
null == null // true
!null // true
isNaN(1 + null) // false
isNaN(1 + undefined) // true

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:

1. (1). it is converted to a boolean: via the Boolean() function


2. (2). when used with logical operators ||, &&, and !
3. (3). within a conditional test like an if statement

// bigint explained in examples


// Example 1

// create bigint variable


const largeNum = 9007199254740992n // (Number.MAX_SAFE_INTEGER + 1)
[Link](largeNum) // 9007199254740992n
[Link](typeof(largeNum)) // bigint

// bigint explained in examples


// Example 2

// typeof Operator
typeof(999n) === 'bigint' // true
typeof(Object(999n)) === 'object' // true

// bigint explained in examples


// Example 3

// 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

// bigint explained in examples


// Example 4

// Comparisons
9n === 9 // false
9n == 9 // true
9n > 99 // false
9n <= 9 // true
// Conditionals
!9n // false
!0n // true

// bigint explained in examples


// Example 5

// 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)

// toString() returns string representing BigInt value


// Without "radix" argument

// number dataype with big Value


const hugeNumber = 1234567890123456789012345678901234567890
[Link](`hugeNumber value is ${hugeNumber} and datatype is $
{typeof(hugeNumber)}`)

// create a bigint object from a constructor function - Bigint()


const bigintNumObj = BigInt(hugeNumber)
[Link](`bigintNumObj value is ${bigintNumObj} and datatype is $
{typeof(bigintNumObj)}`)

// apply toString() method to bigintNumObj


const largeNumber = [Link]()
[Link](`largeNumber value is ${largeNumber} and datatype is $
{typeof(largeNumber)}`)

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

// toString() returns string representing BigInt value


// with "radix" argument

const bigN = 9007199254740991n


[Link](2) // '11111111111111111111111111111111111111111111111111111'
[Link](10) // '9007199254740991'
[Link](16) // '1fffffffffffff'

1. (2). valueOf() :

returns the wrapped primitive value of a BigInt object.

SYNTAX : [Link]()

// valueOf() returns the primitive value

// BigInt variable created by adding 'n' at the end


const largeNum = 1234567890123456789012345678901234567890n

// Using BigInt() method, BigInt variable created


const bigNum = BigInt(9007199254740992)

const largeNumValue = [Link]()


const bigNumValue = [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" }

let pid = Symbol('pid') // description argument as 'pid'


player[pid] = 98765;
[Link]('Player pid using Symbol: ' + player[pid])
[Link]('typeof(pid) is ' + typeof(pid))
[Link]('Player pid using Object: ' + [Link])

OUTPUT
Player pid using Symbol: 98765
typeof(pid) is symbol
Player pid using Object: undefined

Shared Symbols in global registry

 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)
1. (1). [Link]() method takes a symbol value and returns the
string key corresponding to it.
2. (2). To get the key associated with a symbol, you use the [Link]() method.
3. (3). If a symbol that does not exist in the global symbol registry, the [Link]() method
returns undefined.

// [Link]() method

let aadhar = [Link]('aadhar')


let citizenID = [Link]('aadhar')

[Link](aadhar) // Symbol(aadhar)
[Link](citizenID) // Symbol(aadhar)
[Link](aadhar === citizenID) // true
[Link](typeof aadhar) // symbol
[Link](typeof citizenID) // symbol

// [Link]() method

let keyAadhar = [Link](aadhar)


let keyCitizenID = [Link](citizenID)

[Link](keyAadhar) // aadhar
[Link](keyCitizenID) // aadhar

Symbol Methods

1. (1). toString() :

returns a string containing the description of the Symbol.

SYNTAX : toString()

// toString() returns string containing description of Symbol

Symbol('skill').toString() // "Symbol(skill)"
[Link]() // "Symbol([Link])
[Link]('zam').toString() // "Symbol(zam)"

1. (2). valueOf() :

method returns the primitive value of a Symbol object.

SYNTAX : valueOf()
// valueOf() returns the primitive value of Symbol

const symbolSSN = Symbol('ssn')


typeof (symbolSSN) // "symbol"
[Link]() // Symbol(ssn)
typeof Object(symbolSSN) // "object"
typeof Object(symbolSSN).valueOf() // "symbol"

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, ...];

// Array Indexing Example

const academy = ['S','K','I','L','L','Z','A','M']


[Link]("type of academy array is " + typeof(academy))
[Link]("Length of academy array is " + [Link])
[Link]("The element at the '0' index is " + academy[0])

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

const vowels = ['a', 'e', 'i', 'o', 'u']


[Link](vowels)

OUTPUT
['a', 'e', 'i', 'o', 'u']

// Create array of Fibonacci series (number)


// using array literals

const fibo = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]


[Link](fibo)

OUTPUT
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

// Create array of elements of different datatype

let three = "Three";


const mixData = []; // creating an empty array

// Adding elements to array


mixData[0] = 'One' // Array element is a string
mixData[1] = 2 // Array element is a integer
mixData[2] = three // Array element is a variable
mixData[3] = [4, "five", 6] // Array element is an array
mixData[4] = 7.8 // Array element is a decimal
mixData[5] = {key:9} // Array element is an object

[Link](mixData)

OUTPUT
['One', 2, 'Three', [4, 'five', 6], 7.8, {key: 9}]

Creating array

Arrays may be created in several ways:

 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']

Array(1, 2, 3) returns [1, 2, 3]

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 [,,]

// Creating array using pair of square brackets


// Example: array of single digit even number

// creating Empty Array


const arrayOne = []

// Adding elements/items using index


arrayOne[0] = 6
arrayOne[1] = 28
arrayOne[2] = 496
arrayOne[3] = 8128

[Link](arrayOne)

OUTPUT
[6, 28, 496, 8128]

// Creating arrays using different ways


// use of 'new' keyword is optional

const arrayTwo = [[1],[2,3],[4,5,6]] // array from square brackets,


separating items with commas
const arrayThree = new Array("WORKZAM") // array from single string
argument
const arrayFour = new Array(9) // empty array with length 9
const arrayFive = "ಅ,ಆ,ಇ,ಈ".split(',') // array from string method split()
[Link](arrayTwo)
[Link](arrayThree)
[Link](arrayFour)
[Link](arrayFive)

OUTPUT
[[1],[2,3],[4,5,6]]
['WORKZAM']
[,,,,,,,,]
['ಅ', 'ಆ', 'ಇ', 'ಈ']

Working with array

 Add item(s) to an array.


// Add item to an array

const shoppingArray = ["tea", "coffee", "milk", "eggs"]


shoppingArray[4] = "honey"
[Link](shoppingArray)

OUTPUT
['tea', 'coffee', 'milk', 'eggs', 'honey']

 Modify item in an array.


// Modify item in an array

const shoppingArray = ["tea", "coffee", "milk", "eggs", "honey"]


shoppingArray[4] = "bread" // Change item from 'honey' to 'bread'
[Link](shoppingArray)

OUTPUT
['tea', 'coffee', 'milk', 'eggs', 'bread']

 Remove array elements using the keyword delete .


Using delete creates sparse array i.e. an array which the elements are not sequential, and
they don't always start at 0.
They are essentially Array's with "holes", or gaps in the sequence of their indices.
// using "delete" remove item from array

const shoppingArray = ["tea", "coffee", "milk", "eggs", "bread"]


delete shoppingArray[0] // Remove the last item "honey" in the
array
[Link](shoppingArray)
[Link](shoppingArray[0]) // deleted element at index(0) is removed
[Link]([Link]) // no change in length of array

OUTPUT
['tea', 'coffee', 'milk', 'eggs']
undefined
5

 Concatenation of arrays will return a string.


// Concatenation of arrays
const letters = ['A','B','C']
const numbers = [1,2,3]
let result = letters + numbers // Concatenation using '+' operator
[Link](result)
[Link]("type of 'result' is " + typeof(result))

OUTPUT
A,B,C1,2,3
type of 'result' is string

Nested array

 JavaScript arrays support nesting.


 This means we can have arrays within array.
 Nested array is a multi-dimensional array.
 We can think of multi-dimensional array as a table with rows (r) and columns (c).
For example: An array inside an array.

// Matrix like structure using arrays

const row1 = [1, 2, 3]


const row2 = [4, 5, 6]
const row3 = [7, 8, 9]

// Nesting of arrays within a array


const matrixOne = [row1, row2, row3]
[Link](matrixOne)

OUTPUT
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

// Access first list item in matrix array

matrixOne[0]

OUTPUT
[1, 2, 3]

// access first element of first array item in matrix array

matrixOne[0][0]

OUTPUT
1

Basic Array Methods


 JavaScript allows us to work with "arrays" data structures, as if they were
objects. They also provide methods to call as such.
 In JavaScript these built-in methods / functions of these object, can perform actions or
commands on itself.
 We call methods with a period and then method name. Methods are in the
form: [Link](parameters)
 Here, parameters are extra arguments we can pass into the method.
 JavaScript has many extremely useful string functions/methods; here are a few of them:

(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()

// pop() removes last element of an array

const players = ["Sachin", "Dhoni", "Virat", "Zaheer", "Rahul"];


const popped = [Link](); // removes last element 'Rahul'
[Link](popped)
[Link](players)

OUTPUT
Rahul
['Sachin', 'Dhoni', 'Virat', 'Zaheer']

(2) push()

 push() adds one or more elements to the end of an array.


 It returns the new length of the array.
 push() is a mutating method i.e. it changes length of the array.

SYNTAX : push(element1, element2,...)

// push() adds new items to the end of an array


// push() method with single 'item' as argument

const capitalCities = ["NewDelhi", "NewYork", "London"]


const arraylength = [Link]("Istanbul")
[Link](arraylength)
[Link](capitalCities)

OUTPUT
4
['NewDelhi', 'NewYork', 'London', 'Istanbul']

// push() adds new items to the end of an array


// push() method with multiple 'items' as argument

const numbers = [12, 24, 45, 67]


const arraylength = [Link](78, 89, 91)
[Link](arraylength)
[Link](numbers)

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()

// shift() removes first element from an array

const players = ["Sachin", "Dhoni", "Virat", "Zaheer", "Rahul"];


const shifted = [Link](); // removes first element 'Sachin'
[Link](shifted)
[Link](players)

OUTPUT
Sachin
['Dhoni', 'Virat', 'Zaheer', 'Rahul']

// shift() removes first element from an array


// shift() method is used in 'while' loop

const players = ['Messi', 'Neymar', 'Ronaldo', 'Benzema']

// every iteration will remove next element from an array, until it is empty
while (typeof (player = [Link]()) !== "undefined") {
[Link](player)
}

[Link]("The 'players' array contains ", players)

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.

SYNTAX : unshift(element1, element2,...)

// unshift() adds one or more elements to beginning of Array

const healthyFood = ['Avocado', 'Kiwi', 'Moringa']


const arrayLen = [Link]('Spinach', 'Kale', 'Collard')
[Link](arrayLen)
[Link](healthyFood)

OUTPUT
6
['Spinach', 'Kale', 'Collard', 'Avocado', 'Kiwi', 'Moringa']

(5) includes()

 specifies whether an array includes a certain element, returning true or false as


appropriate.
 The optional argument fromIndex will specify from which index position should the
search start.

SYNTAX : includes(element [, fromIndex])

// includes() returns true if an array contains 'element'


// Example contains one argument : 'element'

const fishes = ['Catfish', 'Bass', 'Carp', 'Tuna', 'Salmon']


let isExists = [Link]('Carp') // search for 'Carp'
[Link](isExists)

OUTPUT
true

// includes() returns true if an array contains 'element'


// Example contains two argument : 'element' & 'fromIndex'
const fishes = ['Catfish', 'Bass', 'Carp', 'Tuna', 'Salmon']

// search for 'Tuna' from index position 3


let isExists = [Link]('Tuna', 3)
[Link](isExists)

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.

SYNTAX : indexOf(element [, fromIndex])

// indexOf() returns first index of the found element else -1


// Example contains one argument : 'element'

const ranNum = [11, 12, 34 ,76, 11, 98]


let searchIndex = [Link](11)
[Link](searchIndex)

OUTPUT
0

// indexOf() returns first index of the found element else -1


// Example contains two argument : 'element' & 'fromIndex'

const ranNum = [11, 12, 34 ,76, 11, 98]

// search for 11 from index position 3


let searchIndex = [Link](11, 3)
[Link](searchIndex)

OUTPUT
4
(7) concat()

 method is used to merge two or more arrays.


 concat() method does not change the existing arrays, but instead returns a new array.
 The resultant array will first be populated by the elements in the object on which it is
called. Then, for each argument, its value will be concatenated into the array.
 concat() is a copying method. It does NOT alter any of arrays provided as arguments but
instead returns a shallow copy.
 The argument value can be an arrays and/or values to concatenate into a new array.

SYNTAX : concat(value1, value2,...)

// concat() merge two or more arrays and returns a new array

const symOne = ['INR', 'USD', 'EUR']


const symTwo = ['JPY', 'CNY']
const symThree = [Link](symTwo)
[Link]("symThree = ", symThree)

// no change to the original arrays


[Link]("symOne = ", symOne)
[Link]("symTwo = ", symTwo)

OUTPUT
symThree = ['INR', 'USD', 'EUR', 'JPY', 'CNY']
symOne = ['INR', 'USD', 'EUR']
symTwo = ['JPY', 'CNY']

// concat() merge two or more arrays and returns a new array


// Example to concatenate array1 with array2 and values 7 & 8

const array1 = [2, 4, 6]


const array2 = [1, 3, 5]

// concatenate array1 with array2 and values 7 & 8


const array3 = [Link](array2, 7, 8)
[Link]("array3 = ", array3)

// no change to the original arrays


[Link]("array1 = ", array1)
[Link]("array2 = ", array2)

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

const fruits = ['apples', 'oranges', 'kiwi']


const newArray = [Link]() // creates a shallow copy
[Link]("newArray = ", newArray)

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])

// join() returns a new string by concatenating elements in an array

const shopList = ["Tea", "Milk", "Sugar"]

[Link]() // 'Tea,Milk,Sugar'
[Link](", ") // 'Tea, Milk, Sugar'
[Link](" + ") // 'Tea + Milk + Sugar'
[Link]("") // 'TeaMilkSugar'

// array with one element


['SKILLZAM'].join() // 'SKILLZAM'

(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()

// reverse() method reverses an array

const colors = ['red', 'green', 'blue', 'orange', 'cyan']


[Link]()
[Link](colors)

OUTPUT
['cyan', 'orange', 'blue', 'green', 'red']

// reverse() method reverses an array


// Mutating returned array will mutate original array

const fibonacci = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 80]


const newFibo = [Link]()
[Link]("newFibo = ", newFibo)

// Modify one element of new array 'newFibo'


// original array 'fibonacci' is also modified
newFibo[0] = 89
[Link]("newFibo = ", newFibo)
[Link]("fibonacci = ", fibonacci)

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]

// reverse() method reverses an array


// NOT mutate the original array

const fibonacci = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 80]

// spread(...) operator, will create a shallow-copied array


const newFibo = [...fibonacci].reverse()
[Link]("newFibo = ", newFibo)

// Modify one element of new array 'newFibo'


// No change to original array 'fibonacci'
newFibo[0] = 89
[Link]("newFibo = ", newFibo)
[Link]("fibonacci = ", fibonacci)
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 = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 80]

(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.

SYNTAX : slice([start], [end])

// slice() returns shallow-copied portion of array


// Single optional argument 'start' is used

const dinosaurs = ['Brachiosaurus', 'Patagosaurus', 'Spinosaurus',


'Tyrannosaurus']
const carniDino = [Link](2)
[Link](carniDino)

OUTPUT
['Spinosaurus', 'Tyrannosaurus']

// slice() returns shallow-copied portion of array


// Both optional argument 'start' & 'end' are used

const dinosaurs = ['Brachiosaurus', 'Patagosaurus', 'Spinosaurus',


'Tyrannosaurus']
const herbiDino = [Link](0,2)
[Link](herbiDino)

OUTPUT
['Brachiosaurus', 'Patagosaurus']

// slice() returns shallow-copied portion of array


// NO optional arguments are used
const dinosaurs = ['Brachiosaurus', 'Patagosaurus', 'Spinosaurus',
'Tyrannosaurus']
const newDino = [Link]() // creates a shallow-copied full array
[Link](newDino)

OUTPUT
['Brachiosaurus', 'Patagosaurus', 'Spinosaurus', 'Tyrannosaurus']

(11) splice()

 method changes the contents of an array by removing or replacing existing elements


and/or adding new elements in place.
 splice() method is a mutating method.
 If the specified number of elements to insert differs from the number of elements being
removed, the array's length will be changed as well.
 The start argument specifies the starting index position of the array. If start is omitted,
then 0 is used.
 The optional argument deleteCount specifies the number of elements in the array to
remove from start index. If deleteCount is omitted, then all the elements from start to the
end of the array will be deleted.
 The optional argument item specifies the elements to add to the array, beginning
from start. If we do not specify any elements, splice() will only remove elements from the
array.

SYNTAX : splice(start [, deleteCount] [, item1, item2... ])

// splice() changes the contents of an array


// Using all three arguments with 0 'deleteCount'

const animals = ['Ape', 'Cow', 'Dog', 'Fox']


[Link](1, 0, 'Cat') // Inserts 1 element at index 1
[Link](animals)

OUTPUT
['Ape', 'Cat', 'Cow', 'Dog', 'Fox']

// splice() changes the contents of an array


// Using all three arguments

const animals = ['Ape', 'Cow', 'Dog', 'Fox']

// Replaces 1 element with 1 element at index 3


[Link](3, 1, 'Elk')
[Link](animals)
OUTPUT
['Ape', 'Cow', 'Dog', 'Elk']

// splice() changes the contents of an array


// Using all three arguments

const animals = ['Ape', 'Cow', 'Dog', 'Fox']

// Replaces 1 element with 3 elements at index 3


[Link](3, 1, 'Elk', 'Kob', 'Yak')
[Link](animals)

OUTPUT
['Ape', 'Cow', 'Dog', 'Elk', 'Kob', 'Yak']

// splice() changes the contents of an array


// Using two arguments 'start' & 'deleteCount'

const animals = ['Ape', 'Cow', 'Dog', 'Fox']


[Link](3, 1) // Removes 1 element at index 3
[Link](animals)

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.

For Example: Consider Football Player Leo Messi's Bio


This player bio example can be represented by a object data structure.

// Object Literal Example:

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
}

// Objects do not allow duplicate keys

const numbers = {Keyone:1, Keyone:2, Keythree:3}


[Link](numbers)

OUTPUT
{Keyone: 2, Keythree: 3}

// Object values can be of any dataType

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'

const fruitCost = { apples:123, oranges:456} // using key:value pairs


[Link](fruitCost)

OUTPUT
{apples: 123, oranges: 456}

// Creating Object: using new keyword with


// in-built Object constructor function

const car = new Object()

// Add properties to 'car' object


[Link] = 2022
[Link] = 'Mahindra'
[Link] = 'XUV700'

[Link](car)

OUTPUT
{year: 2022, make: 'Mahindra', model: 'XUV700'}

// Creating Object: using new with


// user-defined constructor function

// constructor function with 'this' keyword


function Cricketer (name, score) {
[Link] = name;
[Link] = score;
}

// Create new Object 'playerOne'


const playerOne = new Cricketer('Virat Kohli', 183)
[Link](playerOne)
[Link]([Link])

OUTPUT
Cricketer {fullName: 'Virat Kohli', runsScored: 183}
183

// Creating Object: using [Link]()


// to create new objects

// 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
}

// Create new Object 'PlayerBio' using [Link]()


const PlayerBio = [Link]({}, biography, playerHist)

[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

// Creating Object: using class to create objects

// class created with constructor function


class Employee {
constructor(name, location) {
[Link] = name
[Link] = location
}
}

// Create new object


const empOne = new Employee('Fred Silva', 'Rio de Janeiro')

[Link]([Link])
[Link]([Link])
[Link](empOne)

OUTPUT
Fred Silva
Rio de Janeiro
Employee {fullname: 'Fred Silva', city: 'Rio de Janeiro'}

Working with Object

Almost "everything" is an object in JavaScript. All values, except primitives, are objects.

 Booleans can be objects (if defined with the new keyword)


 Numbers can be objects (if defined with the new keyword)
 Strings can be objects (if defined with the new keyword)
 Dates are always objects
 Maths are always objects
 Regex are always objects
 Arrays are always objects
 Functions are always objects
 Objects are always objects

Access the properties of an object by referring to its key, inside square brackets.

// Accessing the items of a Object


// Using 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!

Access the properties of an object by referring to its key, using dot(.).

// Accessing the items of a Object


// Using object name & key seperated by dot(.)
const students = {
fName: "Jasmine",
lName: "Dsouza",
gender: "Female",
age: 20,
isGraduate: true,
cgpa: 8.4,
favSub: ["Physics","Computers","History"]
}

firstname = [Link]
scoreCGPA = [Link]
[Link](firstname + ' scored ' + scoreCGPA + '!')

OUTPUT
Jasmine scored 8.4!

Adding new properties of an object by giving it a value.

// Adding new properties to the Object

const vehicle = {
year: 2021,
make: 'Mahindra'
}

// add new porperty - model: 'XUV700'


[Link] = "XUV700"
[Link](vehicle)

OUTPUT
{year: 2021, make: 'Mahindra', model: 'XUV700'}

Change/Modify the value of a specific property of an object, by referring to its key name.

// Change value of a specific property of an object

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]'}

Computed properties of an object using square brackets [] in an object literal, when


creating an object.

// Computed properties of an object

let brand = 'Samsung';

const mobile = {
[brand]: 25000, // 'Samsung' property key is taken from variable 'brand'
year: 2022
}

[Link](mobile)

OUTPUT
{Samsung: 25000, year: 2022}

Deleting a properties of an object by using delete keyword.

// Deleting a properties from the object

const vehicle = {
year: 2021,
make: 'Mahindra',
model: 'XUV700'
}

delete [Link] // same as: delete vehicle['model']


[Link](vehicle)

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.

// Check if a key exists 'in' the object

const users = {
fname: 'Guido',
lname: 'van Rossum',
email: 'guido@[Link]'
}

isEmailExists = 'email' in users


[Link](isEmailExists)

OUTPUT
true

Static Methods in Object:

 [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
}

const allItems = [Link](employee)


[Link](allItems)

const allKeys = [Link](employee)


[Link](allKeys)

const allValues = [Link](employee)


[Link](allValues)

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.

// Nested Object : Example 1

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'

// Nested Object : Example 2

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)

// hasOwnProperty() returns whether object has property

const player = {
name: 'Leo Messi',
position: 'Forward'
}

[Link]('position') // returns true

OUTPUT
true

2. (2). toString() :

method returns a string representing the object.


This method is meant to be overridden by derived objects for custom type conversion logic.

SYNTAX : toString()
// toString() returns string representing the object

function Player(name, position) {


[Link] = name
[Link] = position
}

const player1 = new Player('Leo Messi', 'Forward')

[Link] = function playerToString() {


return `${[Link]} plays as ${[Link]}`;
}

[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];
}

const radiusObj = new SquareRad(5)


[Link]("Area of circle = " + 3.142 * radiusObj )

OUTPUT
Area of circle = 78.55

Control Flow in JavaScript


 Control flow is where the rubber really meets the road in programming. Without it, a
program is simply a list of statements that are sequentially executed.
 With control flow, you can execute certain code blocks conditionally and/or repeatedly.
 A programming language uses control statements to control the flow of execution of a
program based on certain conditions. These are used to cause the flow of execution to
advance and branch based on changes to the state of a program.
 Control flow statements in JavaScript can be put into three broad categories:

1. [1]. Decision Making statements ( if, else if, else, switch )


2. [2]. Loop statements ( for, for...in, for...of, while, do...while)
3. [3]. Jump statements ( break, continue )

Decision making statements


 Decision making statements are sometimes also known as "Conditional statements" often
referred to if-else statements, allow the programmer to execute certain pieces of code
depending on some Boolean condition.
 Decision making statements in JavaScript are:

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

 if statement is the most simple decision-making statement.


 An "if statement" is written by using the if keyword.
 It is used to decide whether a certain statement or block of statements will be executed or not
i.e if a certain condition is true then a block of statement is executed otherwise not.
 The condition after evaluation will be either true or false
 JavaScript relies on block scope (curly brackets {}) to define scope in the code. Other
programming language like Python, often use "indentation" for this purpose.

Example of Simple if statement:

// Simple 'if' statement

let num1 = 24,


num2 = 12;

// 'if' condition is true, hence the block will be executed


if (num1 > num2) {
[Link](`num1(${num1}) is greater than num2(${num2})`)
}

// if condition is false, hence "if" block will NOT be executed


if (num2 > num1) {
[Link](`num2(${num2}) is greater than num1(${num1})`)
}

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

let num1 = 36,


num2 = 48;

// if condition is false, hence "if" block will NOT be executed


// hence, else block will be executed
if (num1 > num2) {
[Link](`num1(${num1}) is greater than num2(${num2})`)
}
else {
[Link](`num1(${num1}) is lesser than num2(${num2})`)
}

OUTPUT
num1(36) is lesser than num2(48)

Nested if statement

 A nested if is an if statement that is the target of another if or else.


 Nested if statements mean an if statement inside an if statement.
 Yes, JavaScript allows us to nest if statements within if statements. i.e, we can place
an if statement inside another if statement.
// Nested "if/else" statement

let ranNum = 28

// if condition is true, hence "if" block will be executed


if (ranNum == 28 || ranNum <= 30) {

// if condition is true, hence nested "if" block will be executed


if (ranNum < 30) {
[Link]('ranNum is smaller than 30')
}

// if condition is false, hence nested "if" block will NOT be executed


if (ranNum < 15) {
[Link]('ranNum is smaller than 15')
}
}

// never executes else block


else {
[Link]('ranNum is larger than 30')
}

OUTPUT
ranNum is smaller than 30

if...else if...else ladder statement

 The if statements are executed from the top down.


 As soon as one of the conditions controlling the if is true, the statement associated with
that if is executed, and the rest of the ladder is bypassed.
 If none of the conditions is true, then the final else statement will be executed.
// if...else if...else ladder statement

let givenNum = 100

// if condition is false, hence "if" block will NOT be executed


if (givenNum == 25) {
[Link]('givenNum is 25')
}

// if condition is false, hence "else if" block will NOT be executed


else if (givenNum == 50) {
[Link]('givenNum is 50')
}

// if condition is false, hence "else if" block will NOT be executed


else if (givenNum == 75) {
[Link]('givenNum is 75')
}

// if condition is true, hence "else if" block will be executed


else if (givenNum == 100) {
[Link]('givenNum is 100')
}

// never executes else block


else {
[Link]('givenNum is INVALID')
}

OUTPUT
givenNum is 100

switch statement

 switch statement is to be used, when one of many code blocks is to be executed.


 The switch statement evaluates an expression, matching the expression's value against a
series of case clauses.
 It executes statements after the first case clause with a matching value (using the strict
equality comparison), until a break statement is encountered.
 The default clause of a switch statement will be executed, if no case matches the
expression's value.
// switch statement
// Example: Based on billing rate, decide salay of employee

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

let weightOne = 225,


weightTwo = 125;

if (weightOne > weightTwo) [Link]("weightOne is heavier")


[Link]("***End of Code***")

OUTPUT
weightOne is heavier
***End of Code***

Shorthand if...else or "Ternary" operator

 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

let num1 = 144,


num2 = 169;

// (condition) ? (If 'true') : (If 'false')


(num1 > num2) ? [Link]("num1 is largest") : [Link]("num2 is
largest")

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

// Nested "while" loop

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

[2]. do while Loop

 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 :

o Block of codeis always executed once before the condition is checked.


o If conditionis true, the statement executes again. At the end of every execution, the
condition is checked. When the condition is false, execution stops, and control passes
to the statement following do while.

SYNTAX:

do {
// Block of code to be executed
}
while (condition);

// do while loop Example

let counter = 1

do {
[Link](counter)
counter++
} while (counter <= 3)

OUTPUT
1
2
3

[3]. for Loop

 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:

for (expression1; expression2; expression3) {


// Block of code to be executed
}

When a for loop executes, the following ordered steps occurs:

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

const numArray = [] // create empty array


let singleDigit,
index = 0;

for (singleDigit = 0; singleDigit <= 9; singleDigit += 1) {


numArray[index] = singleDigit
index++
}
[Link](`The "numArray" contains = [${numArray}]`)

/****************************************************/
// 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

let evenNum = [22, 44, 66]; // array length = 3


let sumNum = 0;
for (let x = 0; x < [Link]; x++) {
sumNum = sumNum + evenNum[x];
}
[Link](`Sum of all the number in an array = ${sumNum}`)

/*****************************************************/
// 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

// Nested "for" loop example

for (let p = 1; p <= 2; p++) { //p: 1,2


[Link](`p is: ${p}`)
for (let q = 1; q < 4; q++) { //q: 1,2,3
[Link](` q is: ${q}`)
}
}

/*****************************************************/
// 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

// "for" loop : Iterate multi-dimension array using "for" loop


// Example : Print the country name and Flag colors

const arrFlags = [
["INDIA","Orange","White","Green"],
["GERMANY","Black","Red","Yellow"],
["RUSSIA","White","Red","Blue"],
["COLOMBIA","Yellow","Blue","Red"],
["EGYPT","Red","White","Black"]
]

for (let a = 0; a < [Link]; a++) { // [Link] = 5


let flagRow = arrFlags[a];
[Link](flagRow[0] + " Flag Colors");
for (let b = 1; b < [Link] ; b++) { // [Link] = 4
[Link](flagRow[b]);
}
}

/*****************************************************/
// 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

[4]. for...of Loop

 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:

for (variable of iterable) {


// Block of code to be executed
}

// "for .. of" loop iterating arrays


// Example : Sum of all the number in an array

let total = 0;
let arrayNum = [10, 20, 30, 40]

for (let n of arrayNum) {


total = total + n;
}
[Link](`Sum of all the number in an array = ${total}`)

/*****************************************************/
// 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

// "for .. of" loop iterating strings


// Example : convert string into an array of characters

const charArray = []
let charIndex = 0

for (let singleChar of "SKILLZAM") {


charArray[charIndex] = singleChar;
charIndex++;
}
[Link](`The "charArray" contains = [${charArray}]`)

/******************************************************/
// 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
}

// Using Object constructor, create array of 'values'


let goals = [Link](goalScores)

// goals = [44,43,43,39,37,36,35,35,34,33]
for (let goal of goals) {
gTotal += goal;
}

[Link](`The array of object values is = [${goals}]`)


[Link](`Total goals scored by top 10 players in the year 2018: $
{gTotal}`)

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

[5]. for...in Loop

 for...in statement loops through the properties of an Object.


 Difference between a for...of loop and a for...in loop is, while for...in iterates over
property names, for...of iterates over property values.
 Do not use for...in over an Array. It is better to use a for loop, a for...of loop,
or [Link]() when the order is important.
 In the below Syntax of for...in loop :

o key : the key from the key : value pair of an object.


o object : is a complex datatypes containing named values called properties.
o Block of code within curly braces {} executes multiple statements.

SYNTAX:
for (key in object) {
// Block of code to be executed
}

// "for .. in" loop


// Example : Use "for .. in" loop to iterate Object literals

let str = ""

const car = {
year: 2022,
make: 'Mahindra',
model: 'XUV700'
}

for (let item in car) {


str += car[item]
str += ' '
}

[Link](str)

OUTPUT
2022 Mahindra XUV700

// "for .. in" loop


// Example : Use "for .. in" loop to iterate Object literals

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
}

for (let bio in bioMessi) {


[Link](`${[Link]()} is ${bioMessi[bio]}`);
}

/
******************************************************************************
********************/
// 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

Jump statements : break & continue


Jump statements are the loop control statements that change the execution from its normal
sequence.

Examples:

 break statement
 continue statement

break statement

 The break statement breaks-out of the loop entirely.


 It was used to jump out of a switch statement as well.
 The combination infinite loop + break as needed is great for situations when a loop's
condition must be checked not in the beginning or end of the loop, but in the middle or even in
several places of its body.
 With the break statement, we can stop the for or for...of or for...in loop before it has
looped through all the items.
 With the break statement, we can stop the while or do while loop even if the condition
is true.

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:

// "break" statement for printing Fibonacci numbers

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:

// "continue" statement for printing ODD numbers

const numArray = [1,2,3,4,5,6,7,8,9,10]


let str = "";
for (let num in numArray) {
// if the remainder of num / 2 is 0, skip the rest of current loop
if (num % 2 == 0) {
continue;
}
str += num + ' '
}
[Link](str)

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

// label statement Example

let total = 0,
i = 1;

whileloop1: while (true) {


i = 1;
whileloop2: while (i < 3) {
total += i;
if (total > 3) {
break whileloop1; // break using 'label' statement
}
[Link]("total = " + total);
i++;
}
}

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

To create a function, we can use a function definition/declaration.

A function definition (also called function declaration, or function statement ) consists of :

 The function keyword, followed by name of the function.


 Then a list of parameters to the function, enclosed in parentheses () and separated by
commas ,
 Followed by Block of code i.e. JavaScript statements that define the function, enclosed in
curly brackets, {}
 Function hoisting only works with function declarations — not with function expressions.
This is because the JavaScript interpreter hoists the entire function declaration to the top of the
current scope.

For example, the following code defines a simple function named createFullName :

// Function definition or declaration Example

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.

 Calling a function is also known as invoking a function.


 To call a function, you use its name followed by arguments enclosing in parentheses ()
 When calling a function, JavaScript executes the code inside the function body (Block of
code within curly brackets {} .
 Functions must be in scope when they are called, but the function declaration can be hoisted
(appear below the call in the code).
 The scope of a function declaration is the function in which it is declared (or the entire
program, if it is declared at the top level).
 The arguments of a function are not limited to strings and numbers. You can pass whole
objects to a function.
 A function can call itself. It is said to be recursive function.
 Remember that funcName() and [Link]() is the same function.
// Function definition/invoking Example

// function definition or declaration


function createFullName() {
let fname = "Brendan",
lname = "Eich",
fullname = fname + " " + lname;

[Link](fullname)
}

// function invoking / calling


createFullName()

OUTPUT
Brendan Eich

Function Arguments & Parameters

 Information / data can be passed into functions as arguments.


 An argument is the value that is sent to the function when it is called/invoked.
 A parameter is the variable listed inside the parentheses () in the function definition.
 Arguments/Parameters are specified after the function name, inside the parentheses (). You
can add as many arguments/parameters as you want, just separate them with a comma ,
 By default, a function must be called with the correct number of arguments. Meaning that
if your function expects 2 arguments, you have to call the function with 2 arguments, not more,
and not less.
 To let a function return a value, use the return statement

What is the difference between return and [Link]() ?

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

// Two Parameters (fname & lname) used in function declaration


function createFullName(fname, lname) {
let fullname = fname + " " + lname
return fullname // function returns a value
}

let firstName = "Brendan",


lastName = "Eich";

// Two Arguments used in function invoking


let funcReturn = createFullName(firstName, lastName)
[Link](funcReturn)

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

function playerClub(club = "no one") {


[Link](`I play for ${club}.`)
}

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.

 The below example function can be called/invoked in several ways:

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!')

// Default function Parameter values


function ask_ok(place, retries=3, reminder='Please try again!') {
while (true) {
let city = prompt(place);
if (city === 'Bengaluru' || city === 'Hyderabad' || city === 'Chennai') {
return true
}
if (city === 'Kanpur' || city === 'Surat') {
return false
}
retries = retries - 1;
if (retries < 0) {
[Link]('invalid user response')
}
[Link](reminder)
}
}

// function invoking using only mandatory argument


ask_ok('Enter the capital city: ')

OUTPUT
Enter the capital city: Hyderabad
true

Recursion Function

 A Recursion function is defined as a function that calls itself.


 Recursion has the benefit of meaning that you can loop through data to reach a result.
 The developer should be very careful with recursion as it can be quite easy to slip into
writing a function which never terminates, or one that uses excess amounts of memory or
processor power. However, when written correctly recursion can be a very efficient and
mathematically-elegant approach to programming.
 In some ways, recursion is analogous to a loop. Both execute the same code multiple
times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in
this case).
 In the below example, factorial() is a function that we have defined to call itself
("recurse").

Suppose we want to find the factorial of 5, then it will goes as below:

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);

[Link](`The factorial of ${randNum} is ${funcRtn}`)

OUTPUT
The factorial of 5 is 120

Nested Function

 A function within another function.


 The nested (inner) function is private to its containing (outer) function.
 Nested functions have access to the scope "above" them.
// Nested Function Example

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.

Listed below are the links to the Examples


Description of Example Links
Display - Hello World Code
Add internal JS to HTML Code
Add inline JS to HTML Code
Variables : let, var & const Code
Data Types Code
typeof Operator Code
Aritmetic Operators Code
Assignment Operators Code
Comparison Operators Code
Logical Operators Code
Conditional Operator Code
Decision Making Code
Truthy & Falsy Code
Arrays Code
Array Methods - Part -1 Code
Objects Code
for Loop Code
while Loop Code
Function declaration & invoking Code
Function parameters & arguments Code
Function Block & Lexical scope Code
Functions : Object Methods Code
Function with try & Catch Code
Function Expression Code
Arrow Function Expression Code
Nested & Callback Functions Code
Default Params Code
Array Methods - Part -2 Code
spread Operator Code
Destructuring Code

JavaScript Interview Questions


Get the hold of actual interview questions during job hiring.

What is JavaScript, and how is it used in web development?

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.

What is the difference between null and undefined in JavaScript?

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.

What is hoisting in JavaScript, and how does it work?

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.

What are arrow functions in JavaScript?


Arrow functions are a concise way to define functions in JavaScript. They were introduced in
ECMAScript 6 and provide a shorter syntax for defining functions compared to traditional
function declarations. Arrow functions are also automatically bound to the scope of their parent
function or the global scope, depending on how they are defined.

What are the different types of events in JavaScript?

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 purpose of the async/await keywords in JavaScript?

The async/await keywords were introduced in ECMAScript 7 as a way to simplify asynchronous


programming in JavaScript. Async/await allows developers to write asynchronous code that
looks and behaves like synchronous code, making it easier to reason about and debug.
Async/await works by allowing developers to mark a function as asynchronous using the "async"
keyword, and then use the "await" keyword to wait for a Promise to resolve before continuing
with the execution of the code.

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.

What is a callback function in JavaScript?

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.

What is the event loop in JavaScript, and how does it work?

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.

What is closure in JavaScript, and how is it used?


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. Closures are created when a function returns
another function that references variables in its parent scope. This allows the inner function to
access and modify the parent scope's variables, even though the parent function has already
completed execution. Closures are often used to create private variables and functions in
JavaScript, or to implement higher-order functions that return functions with customized
behavior.

What is the difference between let, const, and var in JavaScript?

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.

What is the difference between == and === in JavaScript?

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.

What are the different data types in JavaScript?

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.

What is a promise in JavaScript, and how does it work?

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.

What is the difference between call and apply in JavaScript?

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.

How do you declare a variable in JavaScript?

You can declare a variable in JavaScript using the var, let, or const keyword, like this:

var greet = 'Hello, world!';


let num = 123;
const PI = 3.14;

What is the difference between a closure and a callback in JavaScript?

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.

What is the difference between let and var in JavaScript?

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.

What is the prototype in JavaScript?

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.

What is the difference between let and const in JavaScript?

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 synchronous and asynchronous programming in


JavaScript?

Synchronous programming in JavaScript refers to a style of programming where each statement


is executed in turn, and the program waits for each statement to complete before moving on to
the next one. Asynchronous programming, on the other hand, refers to a style of programming
where operations can run in the background while the program continues to execute.
Asynchronous programming is often used for I/O operations, such as reading or writing to a file,
or making a network request, where the operation can take a long time to complete.

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.

What is the difference between a regular function and an arrow function in


JavaScript?

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.

What is the difference between a callback function and a promise in JavaScript?

A callback function is a function that is passed as an argument to another function, and is


typically used for handling asynchronous operations in JavaScript. A promise, on the other hand,
is an object that represents the eventual completion of an asynchronous operation, and provides a
more structured and flexible way of handling asynchronous code. While both callback functions
and promises can be used for handling asynchronous operations in JavaScript, promises are
generally considered to be more flexible and easier to reason about, especially when dealing with
complex asynchronous workflows.

What are the four principles of object-oriented programming?

The four principles of object-oriented programming are inheritance, encapsulation, abstraction,


and polymorphism. Inheritance allows objects to inherit properties and methods from other
objects. Encapsulation is the practice of keeping an object's internal state and behavior hidden
from the outside world. Abstraction is the practice of simplifying complex systems by breaking
them down into smaller, more manageable parts. Polymorphism allows objects to take on
multiple forms or behaviors depending on the context in which they are used.

What is the difference between the innerHTML and textContent properties in


JavaScript?

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.

What is the purpose of the "use strict" directive in JavaScript?

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.

What is the purpose of the "this" keyword in JavaScript?

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.

What is the purpose of the "use strict" directive in JavaScript?

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.

What is a generator function in JavaScript?

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.

How do you define a function in JavaScript?

You can define a function in JavaScript using the function keyword, like this:

function myFunction(parameter1, parameter2) {


// Code to perform the task
return result;
}

What is an event in JavaScript?

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?

The DOM (Document Object Model) in JavaScript is a hierarchical representation of a web


page's HTML structure, which can be manipulated using JavaScript.

How do you access an element in the DOM using JavaScript?

You can access an element in the DOM using JavaScript using methods such as
[Link](), [Link](), or [Link]().

What is AJAX in JavaScript?

AJAX (Asynchronous JavaScript and XML) in JavaScript is a technique used to update parts of
a web page without reloading the entire page.

What is a constructor function in JavaScript?

A constructor function in JavaScript is a function that is used to create and initialize an object.

You might also like