0% found this document useful (0 votes)
6 views

javascript methods

The document provides a comprehensive overview of essential JavaScript methods, including string, array, math, and date methods, along with JSON conversion techniques. It includes examples of how to manipulate strings, arrays, perform mathematical operations, and handle dates, as well as converting JavaScript objects to JSON and vice versa. Each method is illustrated with code snippets and expected outputs for clarity.

Uploaded by

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

javascript methods

The document provides a comprehensive overview of essential JavaScript methods, including string, array, math, and date methods, along with JSON conversion techniques. It includes examples of how to manipulate strings, arrays, perform mathematical operations, and handle dates, as well as converting JavaScript objects to JSON and vice versa. Each method is illustrated with code snippets and expected outputs for clarity.

Uploaded by

omkarwarik1204
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Must-Know

JavaScript
Methods
Swipe to know
String Methods

1
const text = ' JavaScript is amazing! JavaScript is powerful! ';

3
// 1 Extracting a part of the string using `.slice(start, end)`

4
const extracted = text.slice(2, 12); // Removes leading spaces & extracts "JavaScript"

5
console.log(extracted); // Output: "JavaScript"

7
// 2 Replacing a word in the string using `.replace()`

8
const replaced = text.replace('JavaScript', 'React'); // Replaces first occurrence only

9
console.log(replaced); // Output: " React is amazing! JavaScript is powerful! "

10

11
// 3 Replacing all occurrences using `.replaceAll()`

12
const replacedAll = text.replaceAll('JavaScript', 'React');

13
console.log(replacedAll); // Output: " React is amazing! React is powerful! "

14

15
// 4 Splitting the string into an array using `.split(separator)`

16
const words = text.trim().split(' '); // Splits by spaces & removes leading/trailing spaces

17
console.log(words); // Output: ["JavaScript", "is", "amazing!", "JavaScript", "is", "powerful!"]

18

19
// 5 Converting to uppercase using `.toUpperCase()`

20
const upperCaseText = text.toUpperCase();

21
console.log(upperCaseText); // Output: " JAVASCRIPT IS AMAZING! JAVASCRIPT IS POWERFUL! "

22

23
// 6 Converting to lowercase using `.toLowerCase()`

24
const lowerCaseText = text.toLowerCase();

25
console.log(lowerCaseText); // Output: " javascript is amazing! javascript is powerful! "

26

27
// 7 Trimming whitespace from both sides using `.trim()`

28
const trimmedText = text.trim();

29
console.log(trimmedText); // Output: "JavaScript is amazing! JavaScript is powerful!"

30

31
// 8 Checking if the string contains a word using `.includes()`

32
console.log(text.includes('amazing')); // Output: true

33
console.log(text.includes('Python')); // Output: false

34

35
// 9 Finding the first occurrence of a word using `.indexOf()`

36
console.log(text.indexOf('JavaScript')); // Output: 2 (first "JavaScript" starts at index 2)

37

38
// 10 Finding the last occurrence using `.lastIndexOf()`

39
console.log(text.lastIndexOf('JavaScript')); // Output: 23 (last "JavaScript" starts at index 23)

40

41
// 11 Extracting a specific character using `.charAt(index)`

42
console.log(text.charAt(5)); // Output: "S" (5th character in "JavaScript")

43

44
// 12 Repeating a string using `.repeat()`

45
console.log('Hello! '.repeat(3)); // Output: "Hello! Hello! Hello! "

46
essential Array Methods
1
const numbers = [1, 2, 3, 4, 5];

3
// 1 Filtering an array using `.filter(callback)`

4
const evenNumbers = numbers.filter((num) => num % 2 === 0); // Keep only even numbers

5
console.log(evenNumbers); // Output: [2, 4]

7
// 2 Transforming array values using `.map(callback)`

8
const squaredNumbers = numbers.map((num) => num * num); // Square each number

9
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]

10

11
// 3 Summing up all values using `.reduce(callback, initialValue)`

12
const sum = numbers.reduce((acc, num) => acc + num, 0); // Add all numbers together

13
console.log(sum); // Output: 15

14

15
// 4 Checking if any element matches a condition using `.some(callback)`

16
const hasEvenNumber = numbers.some((num) => num % 2 === 0); // Does at least one number match?

17
console.log(hasEvenNumber); // Output: true

18

19
// 5 Checking if all elements match a condition using `.every(callback)`

20
const allPositive = numbers.every((num) => num > 0); // Are all numbers positive?

21
console.log(allPositive); // Output: true

22

23
// 6 Finding a specific element using `.find(callback)`

24
const firstEven = numbers.find((num) => num % 2 === 0); // Finds the first even number

25
console.log(firstEven); // Output: 2

26

27
// 7 Finding an index using `.findIndex(callback)`

28
const index = numbers.findIndex((num) => num > 3); // Find index of first number > 3

29
console.log(index); // Output: 3 (because numbers[3] is 4)

30

31
// 8 Removing duplicates using `Set` and `Array.from()`

32
const duplicateNumbers = [1, 2, 2, 3, 4, 4, 5];

33
const uniqueNumbers = [...new Set(duplicateNumbers)];

34
console.log(uniqueNumbers); // Output: [1, 2, 3, 4, 5]

35

36
// 9 Flattening nested arrays using `.flat(depth)`

37
const nestedArray = [1, [2, [3, 4]], 5];

38
const flatArray = nestedArray.flat(Infinity); // Flattens the array to a single level

39
console.log(flatArray); // Output: [1, 2, 3, 4, 5]

40

41
// 10 Sorting an array using `.sort(callback)`

42
const unsortedNumbers = [5, 2, 9, 1, 7];

43
const sortedNumbers = unsortedNumbers.sort((a, b) => a - b); // Sort numbers in ascending order

44
console.log(sortedNumbers); // Output: [1, 2, 5, 7, 9]

45

46
// 11 Combining arrays using `.concat()`

47
const moreNumbers = [6, 7, 8];

48
const combinedArray = numbers.concat(moreNumbers); // Merge arrays

49
console.log(combinedArray); // Output: [1, 2, 3, 4, 5, 6, 7, 8]

50

51
// 12 Converting an array to a string using `.join(separator)`

52
const fruits = ['Apple', 'Banana', 'Cherry'];

53
console.log(fruits.join(', ')); // Output: "Apple, Banana, Cherry"

54
essential Math methods
1
// 1 Rounding a number using `.round()`

2
console.log(Math.round(4.7)); // Output: 5 (Rounds to nearest integer)

3
console.log(Math.round(4.3)); // Output: 4

5
// 2 Rounding down using `.floor()`

6
console.log(Math.floor(4.9)); // Output: 4 (Always rounds down)

8
// 3 Rounding up using `.ceil()`

9
console.log(Math.ceil(4.1)); // Output: 5 (Always rounds up)

10

11
// 4 Getting the absolute value using `.abs()`

12
console.log(Math.abs(-10)); // Output: 10 (Removes negative sign)

13

14
// 5 Finding the maximum value using `.max()`

15
console.log(Math.max(10, 20, 5, 40, 15)); // Output: 40

16

17
// 6 Finding the minimum value using `.min()`

18
console.log(Math.min(10, 20, 5, 40, 15)); // Output: 5

19

20
// 7 Generating a random number using `.random()`

21
console.log(Math.random()); // Output: Random number between 0 and 1

22

23
// 8 Generating a random number between a range

24
const randomBetween = (min, max) => Math.random() * (max - min) + min;

25
console.log(randomBetween(5, 10)); // Output: Random number between 5 and 10

26

27
// 9 Raising a number to a power using `.pow(base, exponent)`

28
console.log(Math.pow(2, 3)); // Output: 8 (2³)

29

30
// 10 Calculating the square root using `.sqrt()`

31
console.log(Math.sqrt(25)); // Output: 5 (√25)

32

33
// 11 Getting the sign of a number using `.sign()`

34
console.log(Math.sign(10)); // Output: 1 (Positive number)

35
console.log(Math.sign(-10)); // Output: -1 (Negative number)

36
console.log(Math.sign(0)); // Output: 0 (Zero)

37

38
// 12 Getting the value of Pi using `.PI`

39
console.log(Math.PI); // Output: 3.141592653589793

40

41
// 13 Getting the value of Euler's Number (e) using `.E`

42
console.log(Math.E); // Output: 2.718281828459045

43

44
// 14 Calculating logarithms using `.log()`

45
console.log(Math.log(10)); // Output: Natural log of 10

46

47
// 15 Converting degrees to radians using `.toRadians()`

48
const degreesToRadians = (degrees) => degrees * (Math.PI / 180);

49
console.log(degreesToRadians(180)); // Output: 3.141592653589793 (Pi radians)

50
essential Date methods
1
// 1 Creating a new date instance (current date & time)

2
const now = new Date();

3
console.log(now); // Output: Current date & time

5
// 2 Creating a specific date (YYYY, MM (0-based), DD, HH, MM, SS)

6
const specificDate = new Date(2023, 0, 15, 10, 30, 0); // January 15, 2023, at 10:30 AM

7
console.log(specificDate);

9
// 3 Getting the year using `.getFullYear()`

10
console.log(now.getFullYear()); // Output: e.g., 2024

11

12
// 4 Getting the month (0-based, so January = 0) using `.getMonth()`

13
console.log(now.getMonth()); // Output: 0 for January, 11 for December

14

15
// 5 Getting the day of the month using `.getDate()`

16
console.log(now.getDate()); // Output: Day of the month

17

18
// 6 Getting the day of the week using `.getDay()` (0 = Sunday, 6 = Saturday)

19
console.log(now.getDay()); // Output: Day index (0-6)

20

21
// 7 Getting the hours using `.getHours()`

22
console.log(now.getHours()); // Output: Current hour (0-23)

23

24
// 8 Getting the minutes using `.getMinutes()`

25
console.log(now.getMinutes()); // Output: Current minutes (0-59)

26

27
// 9 Getting the seconds using `.getSeconds()`

28
console.log(now.getSeconds()); // Output: Current seconds (0-59)

29

30
// 10 Converting a date to a readable string using `.toDateString()`

31
console.log(now.toDateString()); // Output: "Thu Feb 29 2024"

32

33
// 11 Getting the timestamp (milliseconds since Jan 1, 1970) using `.getTime()`

34
console.log(now.getTime()); // Output: Timestamp (milliseconds)

35

36
// 12 Formatting the date to an ISO string using `.toISOString()`

37
console.log(now.toISOString()); // Output: "2024-02-29T12:34:56.789Z"

38

39
// 13 Formatting the date as a locale string using `.toLocaleDateString()`

40
console.log(now.toLocaleDateString('en-US')); // Output: "2/29/2024" (MM/DD/YYYY format)

41

42
// 14 Formatting the time as a locale string using `.toLocaleTimeString()`

43
console.log(now.toLocaleTimeString('en-US')); // Output: "12:34:56 PM"

44

45
// 15 Adding days to a date

46
const futureDate = new Date();

47
futureDate.setDate(futureDate.getDate() + 5); // Adds 5 days

48
console.log(futureDate.toDateString()); // Output: Adjusted date

49

50
// 16 Subtracting days from a date

51
const pastDate = new Date();

52
pastDate.setDate(pastDate.getDate() - 7); // Subtracts 7 days

53
console.log(pastDate.toDateString()); // Output: Adjusted date

54

55
// 17 Comparing two dates

56
const date1 = new Date(2024, 1, 29);

57
const date2 = new Date(2024, 1, 28);

58
console.log(date1 > date2); // Output: true (date1 is later than date2)

59

60
// 18 Getting the difference between two dates in days

61
const diffTime = Math.abs(date1 - date2); // Difference in milliseconds

62
const diffDays = diffTime / (1000 * 60 * 60 * 24); // Convert to days

63
console.log(diffDays); // Output: 1 (difference in days)

64
Part 1: Converting Data Between JSON &
JavaScript Objects

1
// Sample object representing API data

2
const user = {

3
name: 'John Doe',

4
age: 30,

5
email: '[email protected]',

6
isAdmin: false,

7
};

9
// 1 Converting an object to a JSON string using `JSON.stringify()`

10
const jsonString = JSON.stringify(user);

11
console.log(jsonString);

12
// Output: '{"name":"John Doe","age":30,"email":"[email protected]","isAdmin":false}'

13
// Converts the object into a JSON string that can be sent via API requests or stored.

14

15
// 2 Parsing a JSON string back into a JavaScript object using `JSON.parse()`

16
const parsedObject = JSON.parse(jsonString);

17
console.log(parsedObject);

18
// Output: { name: 'John Doe', age: 30, email: '[email protected]', isAdmin: false }

19
// Converts JSON back into a JavaScript object for further manipulation.

20

21
// 3 Handling nested JSON structures

22
const nestedData = {

23
user: {

24
name: 'Alice',

25
posts: [

26
{ id: 1, content: 'Hello World!' },

27
{ id: 2, content: 'Learning JSON!' },

28
],

29
},

30
};

31
const nestedJsonString = JSON.stringify(nestedData, null, 2); // Pretty-print JSON

32
console.log(nestedJsonString);

33
// Output: Formatted JSON with proper indentation, making it easier to read

34

35
// 4 Filtering out specific properties while converting to JSON using `replacer`

36
const filteredJson = JSON.stringify(user, ['name', 'email']);

37
console.log(filteredJson);

38
// Output: '{"name":"John Doe","email":"[email protected]"}'

39
// Only includes "name" and "email" properties in the JSON output.

40
Part 2: Handling Errors & Advanced JSON
Operations

1
// 5 Handling errors when parsing invalid JSON using `try...catch`

2
const invalidJson = "{name: 'John'}"; // Incorrect JSON format (keys must be in double quotes)

3
try {

4
JSON.parse(invalidJson);

5
} catch (error) {

6
console.error('Invalid JSON format:', error.message);

7
}

8
// Output: "Invalid JSON format: Unexpected token n in JSON at position 1"

9
// Prevents the application from breaking due to incorrect JSON data.

10

11
// 6 Stringifying JSON while formatting it with indentation using `JSON.stringify(value, null, spaces)`

12
const formattedJson = JSON.stringify(user, null, 4); // Pretty print with 4 spaces

13
console.log(formattedJson);

14
// Output: Nicely formatted JSON with proper spacing for better readability

15

16
// 7 Removing undefined values when stringifying an object

17
const dataWithUndefined = {

18
name: 'Jane',

19
age: undefined,

20
city: 'New York',

21
};

22
console.log(JSON.stringify(dataWithUndefined));

23
// Output: '{"name":"Jane","city":"New York"}'

24
// Undefined values are automatically removed when converting an object to JSON.

25

26
// 8 Converting a JSON array into an object

27
const jsonArray = '[{"id":1,"title":"Post 1"},{"id":2,"title":"Post 2"}]';

28
const objectArray = JSON.parse(jsonArray);

29
console.log(objectArray);

30
// Output: [{ id: 1, title: "Post 1" }, { id: 2, title: "Post 2" }]

31
// Parses JSON data into an array of objects for easy manipulation.

32

33
// 9 Deep cloning an object using `JSON.stringify()` and `JSON.parse()`

34
const clonedUser = JSON.parse(JSON.stringify(user));

35
console.log(clonedUser);

36
// Output: A deep copy of the `user` object, ensuring no reference to the original object.

37

38
// 10 Ensuring circular references are avoided when stringifying JSON

39
const circularObj = {};

40
circularObj.self = circularObj; // Circular reference

41

42
try {

43
JSON.stringify(circularObj);

44
} catch (error) {

45
console.error('Cannot stringify circular structure:', error.message);

46
}

47
// Output: "Cannot stringify circular structure: Converting circular structure to JSON"

48
// JSON.stringify cannot handle circular structures and will throw an error.

49
essential Promise methods
Part 1: Understanding Promises & Basic Operations

1
// 1 Creating a basic promise

2
const fetchData = new Promise((resolve, reject) => {

3
setTimeout(() => {

4
resolve('Data fetched successfully!'); // Simulate async operation

5
}, 2000);

6
});

8
// Consuming the promise using `.then()` and `.catch()`

9
fetchData

10
.then((response) => console.log(response)) // Output: "Data fetched successfully!"

11
.catch((error) => console.error(error)); // Handles errors if `reject()` is called

12

13
// 2 Simulating an API call using `fetch()` (real-world example)

14
fetch('https://jsonplaceholder.typicode.com/posts/1')

15
.then((response) => response.json()) // Convert response to JSON

16
.then((data) => console.log(data)) // Output: JSON object from API

17
.catch((error) => console.error('Error fetching data:', error)); // Handle errors

18

19
// 3 Using `async/await` to handle Promises more cleanly

20
const getData = async () => {

21
try {

22
const response = await fetch(

23
'https://jsonplaceholder.typicode.com/posts/1',

24
);

25
const data = await response.json();

26
console.log(data); // Output: JSON object

27
} catch (error) {

28
console.error('Error:', error);

29
}

30
};

31
getData();

32
Part 2: Advanced Promise Handling & Parallel
Execution
1
// 4 Chaining multiple Promises using `.then()`

2
const stepOne = () => Promise.resolve('Step 1 Complete');

3
const stepTwo = () => Promise.resolve('Step 2 Complete');

5
stepOne()

6
.then((result) => {

7
console.log(result); // Output: "Step 1 Complete"

8
return stepTwo(); // Return the next Promise

9
})

10
.then((result) => console.log(result)) // Output: "Step 2 Complete"

11
.catch((error) => console.error('Error in steps:', error));

12

13
// 5 Running multiple promises in parallel using `Promise.all()`

14
const promise1 = new Promise((resolve) =>

15
setTimeout(() => resolve('Task 1 Done'), 1000),

16
);

17
const promise2 = new Promise((resolve) =>

18
setTimeout(() => resolve('Task 2 Done'), 2000),

19
);

20
const promise3 = new Promise((resolve) =>

21
setTimeout(() => resolve('Task 3 Done'), 1500),

22
);

23

24
Promise.all([promise1, promise2, promise3])

25
.then((results) => console.log(results)) // Output: ["Task 1 Done", "Task 2 Done", "Task 3 Done"]

26
.catch((error) => console.error('Error in tasks:', error));

27

28
// 6 Handling multiple Promises where some may fail using `Promise.allSettled()`

29
const failPromise = new Promise((_, reject) =>

30
setTimeout(() => reject('Task Failed'), 1200),

31
);

32

33
Promise.allSettled([promise1, failPromise, promise3]).then((results) =>

34
console.log(results),

35
);

36
/* Output:

37
[

38
{ status: 'fulfilled', value: 'Task 1 Done' },

39
{ status: 'rejected', reason: 'Task Failed' },

40
{ status: 'fulfilled', value: 'Task 3 Done' }

41
]

42
*/

43

44
// 7 Getting the first resolved Promise using `Promise.race()`

45
Promise.race([promise1, promise2, promise3])

46
.then((result) => console.log(result)) // Output: "Task 1 Done" (fastest one)

47
.catch((error) => console.error(error));

48

49
// 8 Getting the first successfully resolved Promise using `Promise.any()`

50
Promise.any([failPromise, promise2, promise3])

51
.then((result) => console.log(result)) // Output: "Task 3 Done" (ignores failures)

52
.catch((error) => console.error(error)); // Runs only if ALL fail

53
Mohammad Al-Haj

Please like; if you find value,

consider following!

You might also like