The console is a powerful tool used for practicing and running temporary code snippets. It follows the Read Evaluate Print Loop (REPL) concept, which means it reads the code, evaluates it, prints the result, and then repeats the process.
- Input (i): The console reads the code you write.
- Evaluation (ii): It calculates or computes the code.
- Output (iii): It prints the result.
- Loop (iv): The process is repeated for each input.
To clear the console window, you can press Ctrl + L.
A variable is like a container that holds data. It is simply the name of a storage location used to store and manipulate values in a program.
JavaScript is a dynamically typed language, meaning it infers data types based on the assigned values. Here are some fundamental data types:
-
Number:
- Represents positive and negative values, including integers and floating-point numbers.
- Example:
let age = 25; let pi = 3.14;
-
Boolean:
- Represents truth values:
trueorfalse. - Example:
let isAdult = true; let hasPermission = false;
- Represents truth values:
-
String:
- Represents text or a sequence of characters.
- Enclosed in either double or single quotes.
- Example:
let firstName = "John"; let message = 'Hello, World!';
-
Undefined:
- Represents a variable that has been declared but not assigned a value.
- Example:
let name;
-
Null:
- Represents the intentional absence of any object value.
- Example:
let car = null;
-
BigInt:
- Used to represent integers larger than the maximum safe integer supported by the
Numbertype.
- Used to represent integers larger than the maximum safe integer supported by the
-
Symbol:
- Represents unique and immutable values, often used as keys in objects.
Binary operations involve using operators on two operands (variables).
- Addition:
sum = a + b - Subtraction:
diff = a - b - Multiplication:
mul = a * b - Division:
div = a / b - Modulo (remainder):
mod = a % b(e.g.,12 % 5 = 2as the remainder is 2) - Exponentiation (power):
exp = a ** b(e.g.,2 ** 3 = 8)
NaN stands for "Not-A-Number" and is a global property that represents a value that is not a valid number. For example, 0/0 results in NaN because it is not a valid numerical value.
Operator precedence refers to the order in which operators are evaluated in an expression. It follows the BODMAS rule (Brackets, Orders, Division and Multiplication, Addition and Subtraction).
- Parentheses
() - Exponentiation
** - Multiplication
*, Division/, Modulo% - Addition
+, Subtraction-
Assignment operators are used to assign values to variables.
- Increment:
age += 1orage++(e.g.,age = age + 1) - Decrement:
age -= 1orage--(e.g.,age = age - 1)
Unary operators work with a single operand.
- Post-increment:
age++(first use the value, then increment) - Post-decrement:
age--(first use the value, then decrement) - Pre-increment:
++age(first increment, then use the value) - Pre-decrement:
--age(first decrement, then use the value)
Identifiers are names given to variables and follow specific rules in JavaScript.
- Names can contain letters, digits, underscores, and dollar signs (no spaces).
- Names must begin with a letter, underscore, or dollar sign.
- Names cannot begin with a number.
- Names are case-sensitive (e.g.,
yandYare different variables). - Reserved words (JavaScript keywords) cannot be used as identifiers.
In JavaScript, it's common to use camelCase for writing identifiers. For example:
let fullNamelet ageOfPersonlet favoriteColor
TypeScript is a superset of JavaScript and is used in numerous companies. It is statically typed, meaning that once a variable is defined with a specific data type, it cannot be changed later. In contrast, JavaScript is dynamically typed, allowing variable data types to change.
Strings in JavaScript are indexed, meaning each letter is assigned a position. Indexing starts from 0, and we can access individual characters using their index.
Example:
let name = 'TONY STARK';
name[0] // 'T'
name[4] // ' '
name.length // 10
name[name.length - 1] // 'K'Concatenation is the process of combining multiple strings together using the + operator.
Example:
"Tony" + "Stark" // "Tonystark"
let firstName = 'Tony';
let lastName = "Stark";
let fullName = firstName + " " + lastName; // "Tony Stark"Template literals, denoted by backticks (`), allow us to embed expressions within a string. The expressions are enclosed in ${}.
Example:
let a = 5;
let b = 10;
console.log(`Your pay is ${a + b} rupees.`);
// Output: Your pay is 15 rupees.JavaScript supports various types of operators for performing different operations.
- Arithmetic Operators:
+,-,*,/,%,** - Unary Operators:
++,--(pre-increment, post-increment, pre-decrement, post-decrement) - Assignment Operators:
=,+=,-=,*=,/=,%=, etc. - Comparison Operators:
<,<=,>,>=,==,!=,===,!== - Logical Operators:
&&(AND),||(OR),!(NOT)
Conditional statements allow us to make decisions based on certain conditions.
- if-else Statement:
The if statement is used to execute a block of code if a specified condition is true. If the condition is false, the else block is executed (if provided).
Example:
let age = 19;
if (age >= 19) {
console.log("You are an adult.");
} else {
console.log("You are not an adult.");
}- else if Statement:
The else if statement allows us to check multiple
conditions in sequence.
Example:
let marks = 63;
if (marks >= 90) {
console.log("A grade");
} else if (marks >= 60) {
console.log("B grade");
} else if (marks >= 40) {
console.log("C grade");
} else {
console.log("Fail");
}- Nested if-else:
Nested if-else allows us to have multiple levels of conditions.
Example:
let number = 50;
if (number >= 50) {
if (number === 50) {
console.log("Number is equal to 50");
} else {
console.log("Number is greater than 50");
}
} else {
console.log("Number is less than 50");
}In JavaScript, every value can be treated as either truthy or falsy when used in a boolean context. Falsy values are considered false, while truthy values are considered true.
Falsy values: false, 0, -0, NaN, null, undefined, "" (empty string)
Everything else is considered truthy.
The switch statement is used when we have fixed values to compare.
Example:
let color = "red";
switch (color) {
case "red":
console.log("Stop");
break;
case "yellow":
console.log("Slow down");
break;
case "green":
console.log("Go");
break;
default:
console.log("Broken light");
}- Alert
alert() displays an alert message as a popup on the web page.
Example:
alert("Something is wrong!");- Prompt
prompt() displays a dialog box that allows the user to enter some input.
Example:
let firstName = prompt("Enter your name");
console.log(firstName);Remember to use these statements wisely, as they can disrupt the user experience if overused or used at inappropriate times.
String methods are actions that can be performed on strings, and they return a new string or perform specific operations on the original string.
str.trim()- Trims leading and trailing white spaces from the string.
- Returns a new string without leading or trailing white spaces.
Example:
let str = " Hello, World! ";
let trimmedStr = str.trim();
console.log(trimmedStr); // Output: "Hello, World!"-
str.toUpperCase()- Converts the string to uppercase.
- Returns a new string with all characters in uppercase.
-
str.toLowerCase()- Converts the string to lowercase.
- Returns a new string with all characters in lowercase.
String Methods with Arguments:
-
str.indexOf(substring)- Searches for a specified value (substring) in the string.
- Returns the index of the first occurrence of the substring in the string.
- If the substring is not found, it returns -1.
-
str.slice(start, end)- Extracts a portion of the string and returns it as a new string.
- It takes two arguments: the starting index and the ending index (not inclusive).
- If the ending index is not provided, it extracts till the end of the string.
-
str.replace(oldValue, newValue)- Searches for a specified value (oldValue) in the string and replaces it with another value (newValue).
- Returns a new string with the specified value replaced.
-
str.repeat(count)- Creates and returns a new string with a specified number of copies of the original string.
Arrays are a type of data structure in JavaScript that can store multiple values in a single variable. They are a collection of elements, and each element in an array has a unique index starting from 0.
Example:
let fruits = ["mango", "apple", "litchi"];Arrays can hold different types of values, making them flexible and powerful.
let info = ["Akhil", 23, 89.9];Arrays are mutable, meaning you can change their elements after initialization.
Example:
let fruits = ["mango", "apple", "litchi"];
fruits[0] = "banana";Arrays have many built-in methods that allow us to perform various operations on them.
Here are some commonly used Array methods:
- push(): Adds an element to the end of an array.
- unshift(): Adds elements to the beginning of an array.
- pop(): Removes the last element from an array and returns it.
- shift(): Removes the first element from an array and returns it.
- indexOf(): Returns the index of the first occurrence of a specified element in an array.
- includes(): Checks if an array includes a specific element and returns
trueorfalse. - concat(): Merges two or more arrays to create a new array.
- reverse(): Reverses the order of elements in an array.
- slice(): Returns a shallow copy of a portion of an array.
- splice(): Modifies an array by adding or removing elements at a specified index.
- sort(): Sorts the elements of an array in place and returns the sorted array.
if we say reference in js that means address, so Arrays are reference types in JavaScript, which means that when you create a new variable and assign it an array, the new variable holds a reference to the original array. Any changes made to the original array will be reflected in all references.
lets take an example that i have 2 arrays declared like this let a = [1,2,3] and let b = [1,2,3] so if i compare a == b or a === b then it will result into false because when i create an array and store in variable then both array are stored on different location and the variable stores its reference(address) not the value, also this is reason if i declare variable using const keyword then it will just store its reference so that i can perform action in that array created using const.
Example:
let fruits = ["mango", "apple", "litchi"];
let copyFruits = fruits;
fruits[0] = "banana";
console.log(copyFruits); // Output: ["banana", "apple", "litchi"]You can make an array constant using the const keyword. It allows you to perform operations on the array but prevents you from reassigning a new array to the constant variable.
Example:
const arr = [1, 2, 3, 4];
arr.push(5); // This is allowed
arr = [1, 2, 3, 4, 5]; // This is not allowedNested arrays are arrays of arrays, also known as multidimensional arrays. so array is holding another array
Example:
let num = [[2, 4], [3, 6], [4, 8]];we can access numbers like this num[0][1] - result : 2
nested arrays are visualise using matrix like this 2 4 3 6 4 8
to repeat a sequence of code we use loop. for eg you have to print 1 - 1000 numbers then we can use loops so that in just few lines of code we can print all values from 1 to 1000 there are multiple types of loop lets see that
for loop is most used loops in most of programming language, check the syntex below it shows how to write it, for initilisation we will declare variable or use existing one and this is done just once in process of loop
syntex for for loop
for (initialisation,condition, updation){
}