Introduction
Hey folks, I hope that you must have read my Day 1 Article on #30DaysOfJs. In case, if you haven't read it then make sure you do give it a read by clicking here.
Mathematical Operations
- Declaring Number Data Types: JavaScript provides functionality to perform various operations using integers and decimal values.
For example:
let age = 35
const height = 10 // Height in metres
let mass = 72 // Mass is in kilogram
const PI = 3.14 // PI a geometrical constant
const boilingPoint = 100 // Temperature in °C, boiling point of water which is a constant
console.log(age, height, mass, PI, boilingPoint);
- Mathematical Object: JavaScript provides a lot of functionality with Math Objects and all of them help in working with numbers.
For example:
// Generating mathematical number PI, i.e 3.14159...
const PI = Math.PI
// Math.round is used for rounding to the closest number
console.log(Math.round(PI)); // 3
console.log(Math.round(9.81)); // 10
console.log(Math.floor(PI)); // 3, Rounds the value down
console.log(Math.ceil(PI)); // 4, Rounds the value up
console.log(Math.min(-5, 3, 20, 4, 5, 10)); // -5, Returns the minimum value
console.log(Math.max(-5, 3, 20, 4, 5, 10)); // 20, Returns the maximum value
const randNum = Math.random(); // Creates a random number between 0 to 0.999999
console.log(randNum);
// Let us create random number between 0 to 10
const num = Math.floor(Math.random () * 11); // creates random number between 0 and 10
console.log(num);
// Returns the Absolute value, i.e the positive value
console.log(Math.abs(-10)) // 10
// Square root
console.log(Math.sqrt(100)) // 10
console.log(Math.sqrt(2)) // 1.4142135623730951
// Returns the Power
console.log(Math.pow(3, 2)) // 9
//Returns the exponential value
console.log(Math.E) // 2.718
// Logarithm
// Returns the natural logarithm with base E of x, Math.log(x)
console.log(Math.log(2)) // 0.6931471805599453
console.log(Math.log(10)) // 2.302585092994046
// Returns the natural logarithm of 2 and 10 respectively
console.log(Math.LN2) // 0.6931471805599453
console.log(Math.LN10) // 2.302585092994046
// Trigonometry
Math.sin(60) //0.866
Math.cos(60) //0.5
- Random Number Generator: JavaScript Math Object has a random() method number which generates a number from 0 to 0.999999999...
For example:
let randomNum = Math.random() // Generates 0 to 0.999...
For generating a random number between 0 to 10:
let randomNum = Math.random() // Generates 0 to 0.999
let numBtnZeroAndTen = randomNum * 11
console.log(numBtnZeroAndTen); // Gives: min 0 and max 10.99
let randomNumRoundToFloor = Math.floor(numBtnZeroAndTen)
console.log(randomNumRoundToFloor) // Gives between 0 and 10
String Operations
- Strings are texts, which are under single*, **double*, and *back-tick** quotes. To declare a string, we need a variable name, an assignment operator, and a value under a single quote, double quote, or backtick quote.*
For example:
let space = ' ' // An empty space string
let firstName = 'Shivank'
let lastName = 'Kapur'
let country = 'India'
let city = 'New Delhi'
let lang = 'JavaScript'
console.log(space, firstName, lastName, country, city, lang);
- String Concatenation: Connecting or merging two or more strings is known as concatenation.
For example:
let fullName = firstName + space + lastName; // Concatenation
console.log(fullName); // Shivank Kapur
- Concatenating Using Addition Operator: Concatenating using the addition operator is an old method also this way of concatenating is quite tedious.
For example:
// Declaring different variables of different data types
let space = ' '
let firstName = 'Shivank'
let lastName = 'Kapur'
let country = 'India'
let city = 'New Delhi'
let lang = 'JavaScript'
let age = 18
let fullName = firstName + space + lastName
let personInfoOne = fullName + '. I am ' + age + '. I live in ' + country + '.';
console.log(personInfoOne); // Shivank Kapur. I am 18. I live in India.
- Long Literal Strings: A string could be a single character or a paragraph. If the string length is too big it does not fit in one line. We can use the backslash character (\) at the end of each line to indicate that the string will continue on the next line.
For example:
const paragraph = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do \
eiusmod teLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod te, \
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse \
cillum dolore eu fugiat nulla pariatur \
sunt in culpa qui officia deserunt mollit anim id est laborum.\
Lorem ipsum dolor sit amet, consectetur adipiscing elit\
, sed do eiusmod tempor incididunt \
labore et dolore magna."
console.log(paragraph); // Printing the entire output
Escape Sequences In A String: In JavaScript and other programming languages, " \ " followed by some characters is an escape sequence. Some of them are:
\n: new line
\t: Tab, means 8 spaces
\\: Backslash
\': Single quote (')
\": Double quote (")
For example:
console.log('I hope everyone is enjoying the 30 Days Of JavaScript challenge.\nDo you ?'); // line break
console.log('Days\tTopics\tExercises');
console.log('Day 1\t3\t5');
console.log('Day 2\t3\t5');
console.log('Day 3\t3\t5');
console.log('Day 4\t3\t5');
console.log('This is a backslash symbol (\\)');
console.log('\"Hello, World!\"');
console.log(" \'Hello, World!\'");
console.log('Hey everyone \'hope you all\' are doing good.')
Output In Console:
I hope everyone is enjoying the 30 Days Of JavaScript challenge.
Do you ?
Days Topics Exercises
Day 1 3 5
Day 2 3 5
Day 3 3 5
Day 4 3 5
This is a backslash symbol (\)
"Hello, World!"
'Hello, World!'
Hey everyone \'hope you all\' are doing good.
- Template Literals: To create template strings, we use two back-ticks. We can inject data as expressions inside a template string. To inject data, we enclose the expression with curly braces ({}) starting with a $ sign.
Syntax:
// Syntax
`String literal text`
`String literal text ${expression}`
For example:
let firstName = 'Shivank'
let lastName = 'Kapur'
let country = 'India'
let city = 'Delhi'
let language = 'JavaScript'
let job = 'student'
let age = 18
let fullName = firstName + ' ' + lastName
let personInfoTwo = `I am ${fullName}. I am ${age}. I live in ${country}.`
let personInfoThree = `I am ${fullName}. I live in ${city}, ${country}. I am a ${job}. I code in ${language}.`
console.log(personInfoTwo);
console.log(personInfoThree);
Output In Console:
I am Shivank Kapur. I am 18. I live in India.
I am Shivank Kapur. I live in Delhi, India. I am a student. I code in JavaScript.
- String Length: The string length method returns the number of characters in a string including the empty spaces.
For example:
let js = 'JavaScript'
console.log(js.length); // 10
let firstName = 'Shivank'
console.log(firstName.length) // 7
- Accessing Characters In A String: We can access each character in a string using its index. In programming, counting starts from 0. The first index of a string is always 0, and the last index is given the position -1.
For example:
let string = 'JavaScript'
let firstLetter = string[0]
console.log(firstLetter); // J
let secondLetter = string[1] // a
let thirdLetter = string[2] // v
let lastLetter = string[9]
console.log(lastLetter); // t
let lastIndex = string.length - 1
console.log(lastIndex); // 9
console.log(string[lastIndex]); // t
- Upper Casing The String: toUpperCase(), this method changes the entire string to uppercase.
For example:
let string = 'JavaScript'
console.log(string.toUpperCase()); // JAVASCRIPT
let name = 'Shivank'
console.log(name.toUpperCase()); // SHIVANK
let country = 'India'
console.log(country.toUpperCase()); // INDIA
- Lower Casing The String: toLowerCase(), this method changes the entire string to lowercase.
For example:
let string = 'JavasCript'
console.log(string.toLowerCase()); // javascript
let name = 'Shivank'
console.log(name.toLowerCase()); // shivank
let country = 'India'
console.log(country.toLowerCase()); // india
- Dividing A String: susbtr(), it takes two arguments, the starting index and the number of characters to slice.
For example:
let string = 'JavaScript'
console.log(string.substr(4,6)); // Script
let country = 'India'
console.log(country.substr(2, 2)); // dia
- Another Way Of Breaking The String: substring(), also takes two arguments, the starting index and the stopping index, but it doesn't include the character of the stopping index.
For example:
let string = 'JavaScript'
console.log(string.substring(0,4)); // Java
console.log(string.substring(4,10)); // Script
console.log(string.substring(4)); // Script
let country = 'Finland'
console.log(country.substring(0, 3)); // Fin
console.log(country.substring(3, 7)); // land
console.log(country.substring(3)); // land
- Splitting The String: split(), this method splits the string at a specified place.
For example:
let string = '30 Days Of JavaScript'
console.log(string.split()); // Changes to an array -> ["30 Days Of JavaScript"]
console.log(string.split(' ')); // Split to an array at space -> ["30", "Days", "Of", "JavaScript"]
let firstName = 'Shivank'
console.log(firstName.split()); // Change to an array - > ["Shivank"]
console.log(firstName.split('')); // Split to an array at each letter -> ["S", "h", "i", "v", "a", "n", "k"]
let countries = 'Finland, Sweden, Norway, Denmark, and Iceland'
console.log(countries.split(',')); // Split to any array at comma -> ["Finland", " Sweden", " Norway", " Denmark", " and Iceland"]
console.log(countries.split(', ')); // ["Finland", "Sweden", "Norway", "Denmark", "and Iceland"]
- Removing Trailing Spaces: trim(), this method removes the trailing spaces at the beginning or the end of a string.
For example:
let string = ' 30 Days Of JavaScript '
console.log(string);
console.log(string.trim(' '));
let firstName = ' Shivank '
console.log(firstName);
console.log(firstName.trim()); // Still removes spaces at the beginning and the end of the string
Output In Console:
30 Days Of JavasCript
30 Days Of JavasCript
Shivank
Shivank
- Replacing A String: replace(), takes in the parameter an old string as well as a new string.
Syntax:
string.replace(oldsubstring, newsubstring)
For example:
let string = '30 Days Of JavaScript'
console.log(string.replace('JavaScript', 'Python')); // 30 Days Of Python
let country = 'Finland'
console.log(country.replace('Fin', 'Noman')); // Nomanland
- Repeating A String: repeat(), it takes a number as an argument and returns the repeated version of the string.
Syntax:
string.repeat(n)
For example:
let string = 'hi'
console.log(string.repeat(10)); // hihihihihihihihihihi
- Searching Within A String: search(), takes a substring as an argument and returns the index of the first match. The search value can either be a string or a regular expression.
Syntax:
string.search(substring)
For example:
let string = 'I enjoy coding. If you do not enjoy coding what else can you enjoy.'
console.log(string.search('enjoy')); // 3
console.log(string.search('coding')); // 2
- Joining Many Strings: concat(), takes many strings and joins them together.
Syntax:
string.concat(substring, substring, substring)
For example:
let string = '30'
console.log(string.concat("Days", "Of", "JavaScript")); // 30DaysOfJavaScript
let country = 'In'
console.log(country.concat("dia")); // India
- Returning A Particular Index Of A String: charAt(), takes the index and returns the value at that index.
Syntax:
string.charAt(index)
For example:
let string = '30 Days Of JavaScript'
console.log(string.charAt(0)); // 3
let lastIndex = string.length - 1
console.log(string.charAt(lastIndex)); // t
- Returning ASCII Value Of A Particular Index: charCodeAt(), takes the index and returns the ASCII value at that particular index.
Syntax:
string.charCodeAt(index)
For example:
let string = '30 Days Of JavaScript'
console.log(string.charCodeAt(3)); // D ASCII number is 68
let lastIndex = string.length - 1
console.log(string.charCodeAt(lastIndex)); // t ASCII is 116
Checking Data Types And Casting
- Checking Data Types: To check the Data Type of a certain variable we use the typeof method.
For example:
// Different JavaScript Data Types
let firstName = 'Shivank' // String
let lastName = 'Kapur' // String
let country = 'India' // String
let age = 18 // Number
let job // Undefined, because a value was not assigned
console.log(typeof 'Shivank'); // String
console.log(typeof firstName); // string
console.log(typeof 10); // number
console.log(typeof 3.14); // number
console.log(typeof true); // boolean
console.log(typeof false); // boolean
console.log(typeof NaN); // number
console.log(typeof job); // undefined
console.log(typeof undefined); // undefined
console.log(typeof null); // object
- Changing Data Type (Casting): It means converting one data type to another data type. We use parseInt(), parseFloat(), Number()+ sign, str(). When we perform arithmetic operations string numbers should be first converted to integer or float if it doesn't return any error.
- String To Integer: We can convert a string to a number. Any number inside quotes is a string number. We can convert a string to a number using the following ways:
- parseint()
For example:
let num = '10'
let numInt = parseInt(num)
console.log(numInt); // 10
- Number()
For example:
let num = '10'
let numInt = Number(num)
console.log(numInt); // 10
- Plus sign(+)
For example:
let num = '10'
let numInt = +num
console.log(numInt); // 10
- String To Float: We can convert a string float number to a float number. Any float number inside quotes is a string float number. We can convert string float to a number using the following ways:
- parseFloat()
For example:
let num = '9.81'
let numFloat = parseFloat(num)
console.log(numFloat); // 9.81
- Number()
For example:
let num = '9.81'
let numFloat = Number(num)
console.log(numFloat); // 9.81
- Plus sign(+)
For example:
let num = '9.81'
let numFloat = +num
console.log(numFloat); // 9.81
- Float To Integer: We can convert float numbers to integers. This can be done using the following method:
- parseInt()
For example:
let num = 9.81
let numInt = parseInt(num)
console.log(numInt) // 9
I hope that you must have found this article quite helpful. If yes, then do give a read to some of my other articles!
Who knows you might become a great programmer 🤔!