Methods in JavaScript
Methods in JavaScript
Methods in JavaScript
Methods in JavaScript
Learning JavaScript
DigiChamps
Learning Objectives
2
1/23/2024
Outline
JavaScript provides various types of data. When you declare a variable such as let a = “Hello,
welcome to the official website of Qubits.”; it becomes an object in JavaScript. In this specific
case, the variable a becomes a string object. Objects in JavaScript come with specific
properties and hence you can apply built-in methods to these objects. Methods help us
perform various operations on objects without worrying about how they work. For instance,
you can convert all the letters present in the string stored in variable a to upper case using a
method available in JavaScript. In this sprint, you will learn several methods that can be
applied to strings and numbers.
4
1/23/2024
Strings in JavaScript
Strings in JavaScript
A string is a group of characters that can be made up of letters, numbers, or symbols. You can
use an index number to get to any character in a JavaScript string. Whenever data should be
represented in text form, storing them as strings is useful. JavaScript provides a lot of
functionalities to access and manipulate the strings. Let’s learn a few of them.
Strings indexing
Each character in a string has an index number that corresponds to it, starting with 0 . For
instance, let’s make a string whose value is "Computer Science" .
6
1/23/2024
The index 0 points to the first character in the string, which is C . The last character is an e ,
which has an index 15 . There is also an index for white space at 8 . Thus, you can interact
with, and alter strings in a variety of ways since you have access to every character in a string.
Let's look at how to retrieve characters using indexes from the string "Computer Science" .
Step 1: Open the Console .
To access a character located at the index value n , where n is an integer, write the name of
the variable followed by the index value enclosed in square brackets.
8
1/23/2024
Syntax:
Step 3: Access the character at index 5 in the string "Computer Science" stored in variable str
. Type the following and then press Enter :
Step 4: Try str[9]; and press Enter . What result do you get?
10
1/23/2024
Heron's formula is used to calculate the area of a triangle, when its three sides are given. As
per this formula, the area (A) of a triangle expressed in terms of the lengths of its sides, a, b
and c, is given as:
11
Consider an application or a program that requires calculating the area of multiple triangles. In
such situations, it would be efficient to write the code once and reuse it. Functions in
programming help us do this. You can write a function once and then call this function
whenever you need it again. Like other programming languages, we can create functions in
JavaScript and call them whenever we need them. We will learn how to create functions in the
next sprint. In this sprint, let's learn how to use some in-built functions in JavaScript, called
methods. Methods perform specific tasks or actions on objects. You can use a method to
accomplish a task without being explicitly aware of how it works or what is its internal
structure. To use a method in JavaScript, type the name of the object, followed by a period (.),
and then name of the method.
12
1/23/2024
String methods
JavaScript provides methods to manipulate string objects. Let's use a few methods on strings.
13
indexOf() is a method in JavaScript that returns the character’s index, which is its position
number in the string. Let’s look at how to find the index value of the string/character from the
given string. Step 1: Let’s initialize str variable as "Computer Science" ,
Step 2: To return the index position of the specified string "Science" from the main string
"Computer Science" , use str.indexOf("Science") . It will return the index number of the first
character of the substring "Science"
14
1/23/2024
Step 4: Implement indexOf() to return the index number for the first occurrence of a
character "e"
With the lastIndexOf() method, you can find the index of the character when it appears for
the last time in a string.
Step 5: To find the last occurrence of the character "e" in the string "Computer Science" , use
lastIndexOf()
15
To extract a part of a string, JavaScript provides the slice() method. This method returns the
parts of the string from the given start index to the given end index. In this method,
startIndex is inclusive, and endIndex is exclusive.
Syntax:
16
1/23/2024
Let us check the implementation of the slice method on the given string. Step 1: Initialize
the str variable as "Computer Science".
Step 2: To return the string starting at index position 3 and ending at index position 5
(remember endIndex is excluded from the result), use:
17
Do it yourself
Declare a variable str with a string value and try the following str.slice(50), str.slice(3,7),
str.slice(0). See if the results you obtain are correct. Discuss with others.
18
1/23/2024
Do it yourself - Solution
Solution:
Step 2: Declare a variable str with a string value and perform the following string operations.
19
20
1/23/2024
" " //Since the provided index is greater than the length
of the string, the result will be an empty string.
s is
This is a sample string for testing purposes.
21
23
Step 2: To convert all the letters in the string "Computer Science" to lowercase letters, type:
24
1/23/2024
Concatenating strings
Concatenating refers to joining or combining two things. JavaScript provides the concat()
method to join two strings together. To join stringObject1 and stringObject2 , such that the
stringObject2 follows stringObject1 , use the following syntax.
Step 1: Concatenate two strings "Computer" and "Science" together with the help of the
concat() method.
25
Step 2: Let's use the concatenation operator ( + ) to merge two strings together. You can also
add an empty space in between two strings using this operator. To concatenate "Computer"
and "Science" by adding an empty space in between, type:
26
1/23/2024
Step 3: Strings can be put together with variables that are not strings, but the variables that
are not strings will be type-converted into strings.
27
Trim whitespace
With the trim() method, the spaces on either side of the string are removed. However, the
spaces between the strings are unchanged.
28
1/23/2024
The replace() method allows us to look for a value in a string and then replace it with a given
string. The value to be found will be the first parameter, and the replacement value will be the
second.
Syntax:
Let us find and replace the word from the given string using the replace() method. To replace
the word "Science" with "Application" in the given string "Computer Science" , apply the
following:
29
The total number of characters present in a string is called the length of a string. JavaScript
provides the length property to return a string's length. To use a property, type the name of
the object, followed by a period (.), and then name of the property. Unlike methods,
properties in JavaScript do not end with parentheses.
30
1/23/2024
Step 1: Apply the length property to find the total length of the given string " Computer
Science" .
31
Printing statements
32
1/23/2024
Printing statements
So far we were able to get the output on the console without using any method. JavaScript
provides console.log() method to output a message on the Console .
Step 1: To print a statement on the Console , enclose the text within single or double quotes
inside the parentheses. For example, to print “Light travels faster than sound in the air.” , use
the following input:
33
Step 2: To print the value of a variable, enclose the variable name between parentheses.
Step 3: To print a variable and text together in the output statement on the Console, use the
+ operator to combine them. For instance, to print a statement, “a is larger than b” , where
both a and b are variables, use the following:
34
1/23/2024
35
36
1/23/2024
JavaScript Math is an in-built object that has properties and methods that can be useful in
calculations. Let's explore a few methods to understand how to use them.
The Math.sqrt() method is used to find the square root of a number. Enclose the number in
parentheses whose square root you need to find.
37
Rounding a number
The Math.round() method is used to round off a number to the nearest integer. If the
fractional part of the number is less than 0.5 , it returns the closest integer smaller than it. If it
is more than or equal to 0.5 , it returns the closest integer greater than it. To round off a
number x , use the following syntax.
38
1/23/2024
39
To round up a number to the nearest integer greater than the given number, use the
Math.ceil() method. Take the number 13.334 . This number is between 13 and 14 , and the
nearest integer greater than it is 14 . Consider another number -23.56 . This number is
negative and falls between -23 and -24 , with -23 being the nearest integer greater than it.
Thus, -23.56 will be rounded up to -23 .
40
1/23/2024
Step 1: Apply the Math. ceil() method to round the number 206.45.
To round down a number to the nearest integer smaller than the given number, use the
Math.floor() method. Take the number 10.432 . This number is between 10 and 11 , and the
nearest integer smaller than it is 10 . Consider -23.56 again, it falls between -23 and -24 ,
with -24 being the nearest integer smaller than it. Thus, -23.56 will be rounded down to -24.
41
42
1/23/2024
43
To generate random numbers greater than or equal to 0 and less than 1 , JavaScript provides
Math.random() method. This method requires no parameters.
44
1/23/2024
It will generate a random number like 0.09127961987495858 . In your case, the number
would be different as this method generates numbers randomly. Try this method multiple
times. Every time it will return a different number between 0 and 1 , with 0 inclusive and 1
exclusive.
Generate random Integers
Math.random() has many important uses. For instance, you can generate a random number
between any two numbers using Math.floor() with Math.random() . In order to generate a
number between 0 and 10 , with 0 inclusive and 10 exclusive:
a) Use Math.random() . It will produce a number between 0 and 1 , say
0.38222258383340124 .
b) If you multiply this number by 10 , you will get 3.8222258383340124 . So, multiply
Math.random() with 10 .
c) Now, round down the number 3.8222258383340124 , using the Math.floor() method. It
will give the result 3 . So, to round down the number, apply the Math.floor() method
on Math.random() * 10
45
46
1/23/2024
Activity
Use Math.floor() with Math.random() to return any random integer from 0 to 100 .
47
Activity - Solution
Solution:
Step 2: Use Math.floor() with Math.random() to return any random integer from 0 to 100.
48
1/23/2024
49
Activity
a) Math.sqrt(0.0049);
b) Math.round(4.4999);
c) Math.ceil(3.002);
d) Math.floor(8.99);
e) Math.floor(Math.random() * 506);
f) Math.round(Math.random() * 10);
g) Math.round(Math.random() * -9);
50
1/23/2024
Activity - Solution
A sample solution is given below:
Step 2: Use the following code to evaluate the value of the given expressions.
51
Master Challenges
52
1/23/2024
Challenge 1
Evaluate the output of the following:
a.
b.
53
c.
54
1/23/2024
a. 2
b. -3
c. Basic Information Technology21
55
Challenge 2
56
1/23/2024
Challenge 2 - Solution
Solution:
57
Challenge 3
58
1/23/2024
Challenge 3 - Solution
Solution:
59