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

JavaScript Notes

The document provides an overview of JavaScript variables and data types, detailing types such as Number, String, Boolean, Object, and more. It explains variable declaration using 'let' and 'const', naming conventions, string manipulation, and common methods. Additionally, it covers arithmetic operations, operator precedence, and the dynamic typing nature of JavaScript.

Uploaded by

syntaxsagex
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

JavaScript Notes

The document provides an overview of JavaScript variables and data types, detailing types such as Number, String, Boolean, Object, and more. It explains variable declaration using 'let' and 'const', naming conventions, string manipulation, and common methods. Additionally, it covers arithmetic operations, operator precedence, and the dynamic typing nature of JavaScript.

Uploaded by

syntaxsagex
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

JavaScript Variables and Data Types

Data Types in JavaScript:

Data types help the program understand the kind of data it's working with, whether it's a number, text, or something
else.

 Number: A number represents both integers and floating-point values. Examples of integers include 7, 19,
and 90.

 Floating point: A floating point number is a number with a decimal point. Examples include 3.14, 0.5, and
0.0001.

 String: A string is a sequence of characters, or text, enclosed in quotes. "I like coding" and 'JavaScript is
fun' are examples of strings.

 Boolean: A boolean represents one of two possible values: true or false. You can use a boolean to represent
a condition, such as isLoggedin = true.

 Undefined and Null: An undefined value is a variable that has been declared but not assigned a value.
A null value is an empty value, or a variable that has intentionally been assigned a value of null.

 Object: An object is a collection of key-value pairs. The key is the property name, and the value is the
property value.

Here, the pet object has three properties or keys: name, age, and type. The values are Fluffy, 3, and dog, respectively.

let pet = {

name: "Fluffy",

age: 3,

type: "dog"

};

 Symbol: The Symbol data type is a unique and immutable value that may be used as an identifier for object
properties.

In this example below, two symbols are created with the same description, but they are not equal.

const crypticKey1= Symbol("saltNpepper");

const crypticKey2= Symbol("saltNpepper");

console.log(crypticKey1 === crypticKey2); // false

 BigInt: When the number is too large for the Number data type, you can use the BigInt data type to
represent integers of arbitrary length.

By adding an n to the end of the number, you can create a BigInt.

const veryBigNumber = 1234567890123456789012345678901234567890n;

Variables in JavaScript

 Variables can be declared using the let keyword.

let cityName;
 To assign a value to a variable, you can use the assignment operator =.

cityName = "New York";

 Variables declared using let can be reassigned a new value.

cityName = "Los Angeles";

console.log(cityName); // Los Angeles

 Apart from let, you can also use const to declare a variable. However, a const variable cannot be reassigned a
new value.

const cityName = "New York";

cityName = "Los Angeles"; // TypeError: Assignment to constant variable.

 Variables declared using const find uses in declaring constants, that are not allowed to change throughout
the code, such as PI or MAX_SIZE.

Variable Naming Conventions

 Variable names should be descriptive and meaningful.

 Variable names should be camelCase like cityName, isLoggedin, and veryBigNumber.

 Variable names should not start with a number. They must begin with a letter, _, or $.

 Variable names should not contain spaces or special characters, except for _ and $.

 Variable names should not be reserved keywords.

 Variable names are case-sensitive. age and Age are different variables.

Strings and String immutability in JavaScript

 Strings are sequences of characters enclosed in quotes. They can be created using single quotes and double
quotes.

let correctWay = 'This is a string';

let alsoCorrect = "This is also a string";

 Strings are immutable in JavaScript. This means that once a string is created, you cannot change the
characters in the string. However, you can still reassign strings to a new value.

let firstName = "John";

firstName = "Jane"; // Reassigning the string to a new value

String Concatenation in JavaScript

 Concatenation is the process of joining multiple strings or combining strings with variables that hold text.
The + operator is one of the simplest and most frequently used methods to concatenate strings.

let studentName = "Asad";

let studentAge = 25;

let studentInfo = studentName + " is " + studentAge + " years old.";


console.log(studentInfo); // Asad is 25 years old.

 If you need to add or append to an existing string, then you can use the += operator. This is helpful when you
want to build upon a string by adding more text to it over time.

let message = "Welcome to programming, ";

message += "Asad!";

console.log(message); // Welcome to programming, Asad!

 Another way you can concatenate strings is to use the concat() method. This method joins two or more
strings together.

let firstName = "John";

let lastName = "Doe";

let fullName = firstName.concat(" ", lastName);

console.log(fullName); // John Doe

Logging Messages with console.log()

 The console.log() method is used to log messages to the console. It's a helpful tool for debugging and testing
your code.

console.log("Hello, World!");

// Output: Hello, World!

Semicolons in JavaScript

 Semicolons are primarily used to mark the end of a statement. This helps the JavaScript engine understand
the separation of individual instructions, which is crucial for correct execution.

let message = "Hello, World!"; // first statement ends here

let number = 42; // second statement starts here

 Semicolons help prevent ambiguities in code execution and ensure that statements are correctly terminated.

Comments in JavaScript

 Any line of code that is commented out is ignored by the JavaScript engine. Comments are used to explain
code, make notes, or temporarily disable code.

 Single-line comments are created using //.

// This is a single-line comment and will be ignored by the JavaScript engine

 Multi-line comments are created using /* to start the comment and */ to end the comment.

/*

This is a multi-line comment.

It can span multiple lines.

*/

JavaScript as a Dynamically Typed Language


 JavaScript is a dynamically typed language, which means that you don't have to specify the data type of a
variable when you declare it. The JavaScript engine automatically determines the data type based on the
value assigned to the variable.

let error = 404; // JavaScript treats error as a number

error = "Not Found"; // JavaScript now treats error as a string

 Other languages, like Java, that are not dynamically typed would result in an error:

int error = 404; // value must always be an integer

error = "Not Found"; // This would cause an error in Java

Using the typeof Operator

 The typeof operator is used to check the data type of a variable. It returns a string indicating the type of the
variable.

let age = 25;

console.log(typeof age); // "number"

let isLoggedin = true;

console.log(typeof isLoggedin); // "boolean"

 However, there's a well-known quirk in JavaScript when it comes to null. The typeof operator
returns "object" for null values.

let user = null;

console.log(typeof user); // "object"

JavaScript Strings

String Basics

 Definition: A string is a sequence of characters wrapped in either single quotes, double quotes or backticks.
Strings are primitive data types and they are immutable. Immutability means that once a string is created, is
cannot be changed.

 Accessing Characters from a String: To access a character from a string you can use bracket notation and
pass in the index number. An index is the position of a character within a string, and it is zero-based.

const developer = "Jessica";

developer[0]

 \n (Newline Character): You can create a newline in a string by using the \n newline character.

const poem = "Roses are red,\nViolets are blue,\nJavaScript is fun,\nAnd so are you.";

console.log(poem);

 Escaping Strings: You can escape characters in a string by placing backlashes (\) in front of the quotes.
const statement = "She said, \"Hello!\"";

console.log(statement); // She said, "Hello!"

Template Literals (Template Strings) and String Interpolation

 Definition: Template literals are defined with backticks (`). They allow for easier string manipulation,
including embedding variables directly inside a string, a feature known as string interpolation.

const name = "Jessica";

const greeting = `Hello, ${name}!`; // "Hello, Jessica!"

ASCII, the charCodeAt() Method and the fromCharCode() Method

 ASCII: ASCII, short for American Standard Code for Information Interchange, is a character encoding standard
used in computers to represent text. It assigns a numeric value to each character, which is universally
recognized by machines.

 The charCodeAt() Method: This method is called on a string and returns the ASCII code of the character at a
specified index.

const letter = "A";

console.log(letter.charCodeAt(0)); // 65

 The fromCharCode() Method: This method converts an ASCII code into its corresponding character.

const char = String.fromCharCode(65);

console.log(char); // A

Other Common String Methods

 The indexOf Method: This method is used to search for a substring within a string. If the substring is
found, indexOf returns the index (or position) of the first occurrence of that substring. If the substring is not
found, indexOf returns -1, which indicates that the search was unsuccessful.

const text = "The quick brown fox jumps over the lazy dog.";

console.log(text.indexOf("fox")); // 16

console.log(text.indexOf("cat")); // -1

 The includes() Method: This method is used to check if a string contains a specific substring. If the substring
is found within the string, the method returns true. Otherwise, it returns false.

const text = "The quick brown fox jumps over the lazy dog.";

console.log(text.includes("fox")); // true

console.log(text.includes("cat")); // false

 The slice() Method: This method extracts a portion of a string and returns a new string, without modifying
the original string. It takes two parameters: the starting index and the optional ending index.

const text = "freeCodeCamp";

console.log(text.slice(0, 4)); // "free"

console.log(text.slice(4, 8)); // "Code"

console.log(text.slice(8, 12)); // "Camp"


 The toUpperCase() Method: This method converts all the characters to uppercase letters and returns a new
string with all uppercase characters.

const text = "Hello, world!";

console.log(text.toUpperCase()); // "HELLO, WORLD!"

 The toLowerCase() Method: This method converts all characters in a string to lowercase.

const text = "HELLO, WORLD!"

console.log(text.toLowerCase()); // "hello, world!"

 The replace() Method: This method is used to find a specified value (like a word or character) in a string and
replace it with another value.

const text = "I like cats";

console.log(text.replace("cats", "dogs")); // "I like dogs"

 The repeat() Method: This method is used to repeat a string a specified number of times.

const text = "Hello";

console.log(text.repeat(3)); // "HelloHelloHello"

 The trim() Method: This method is used to remove whitespaces from both the beginning and the end of a
string.

const text = " Hello, world! ";

console.log(text.trim()); // "Hello, world!"

 The trimStart() Method: This method removes whitespaces from the beginning (or "start") of the string.

const text = " Hello, world! ";

console.log(text.trimStart()); // "Hello, world! "

 The trimEnd() Method: This method removes whitespaces from the end of the string.

const text = " Hello, world! ";

console.log(text.trimEnd()); // " Hello, world!"

 The prompt() Method: This method of thw window is used to get information from a user through the form
of a dialog box. This method takes two arguments. The first argument is the message which will appear
inside the dialog box, typically prompting the user to enter information. The second one is a default value
which is optional and will fill the input field initially.

const answer = window.prompt("What's your favorite animal?"); // This will change depending on
what the user answers

JavaScript Math

Working with the Number Data Type


 Definition: JavaScript's Number type includes integers, floating-point numbers, Infinity and NaN. Floating-
point numbers are numbers with a decimal point. Positive Infinity is a number greater than any other
number while -Infinity is a number smaller than any other number. NaN (Not a Number) represents an
invalid numeric value like the string "Jessica".

Common Arithmetic Operations

 Addition Operator: This operator (+) is used to calculate the sum of two or more numbers.

 Subtraction Operator: This operator (-) is used to calculate the difference between two numbers.

 Multiplication Operator: This operator (*) is used to calculate the product of two or more numbers.

 Division Operator: This operator (/) is used to calculate the quotient between two numbers

 Division By Zero: If you try to divide by zero, JavaScript will return Infinity.

 Remainder Operator: This operator(%) returns the remainder of a division.

 Exponentiation Operator: This operator (**) raises one number to the power of another.

Calculations with Numbers and Strings

 Explanation: When you use the + operator with a number and a string, JavaScript will coerce the number
into a string and concatenate the two values. When you use the -, * or / operators with a string and number,
JavaScript will coerce the string into a number and the result will be a number. For null and undefined,
JavaScript treats null as 0 and undefined as NaN in mathematical operations.

const result = 5 + '10';

console.log(result); // 510

console.log(typeof result); // string

const subtractionResult = '10' - 5;

console.log(subtractionResult); // 5

console.log(typeof subtractionResult); // number

const multiplicationResult = '10' * 2;

console.log(multiplicationResult); // 20

console.log(typeof multiplicationResult); // number

const divisionResult = '20' / 2;

console.log(divisionResult); // 10

console.log(typeof divisionResult); // number

const result1 = null + 5;

console.log(result1); // 5

console.log(typeof result1); // number

const result2 = undefined + 5;

console.log(result2); // NaN

console.log(typeof result2); // number


Operator Precedence

 Definition: Operator precedence determines the order in which operations are evaluated in an expression.
Operators with higher precedence are evaluated before those with lower precedence. Values inside the
parenthesis will be evaluated first and multiplication/division will have higher precedence than
addition/subtraction. If the operators have the same precedence, then JavaScript will use associativity.

const result = (2 + 3) * 4;

console.log(result); // 20

const result2 = 10 - 2 + 3;

console.log(result2); // 11

const result3 = 2 ** 3 ** 2;

console.log(result3); // 512

 Definition: Associativity informs us the direction in which an expression is evaluated when multiple
operators of the same type exist. It defines whether the expression should be evaluated from left-to-right
(left-associative) or right-to-left (right-associative). For example, the exponent operator is also right to left
associative:

const result4 = 5 ** 4 ** 1; // 625

console.log(result4);

Increment and Decrement Operators

 Increment Operator: This operator is used to increase the value by one. The prefix notation ++num increases
the value of the variable first, then returns a new value. The postfix notation num++ returns the current
value of the variable first, then increases it.

let x = 5;

console.log(++x); // 6

console.log(x); // 6

let y = 5;

console.log(y++); // 5

console.log(y); // 6

 Decrement Operator: This operator is used to decrease the value by one. The prefix notation and postfix
notation work the same way as earlier with the increment operator.

let num = 5;

console.log(--num); // 4

console.log(num--); // 4

console.log(num); // 3

Compound Assignment Operators

 Addition Assignment (+=) Operator: This operator performs addition on the values and assigns the result to
the variable.
 Subtraction Assignment (-=) Operator: This operator performs subtraction on the values and assigns the
result to the variable.

 Multiplication Assignment (*=) Operator: This operator performs multiplication on the values and assigns
the result to the variable.

 Division Assignment (/=) Operator: This operator performs division on the values and assigns the result to
the variable.

 Remainder Assignment (%=) Operator: This operator divides a variable by the specified number and assigns
the remainder to the variable.

 Exponentiation Assignment (**=) Operator: This operator raises a variable to the power of the specified
number and reassigns the result to the variable.

Booleans and Equality

 Boolean Definition: A boolean is a data type that can only have two values: true or false.

 Equality (==) Operator: This operator uses type coercion before checking if the values are equal.

console.log(5 == '5'); // true

 Strict Equality (===) Operator: This operator does not perform type coercion and checks if both the types
and values are equal.

console.log(5 === '5'); // false

 Inequality (!=) Operator: This operator uses type coercion before checking if the values are not equal.

 Strict Inequality (!==) Operator: This operator does not perform type coercion and checks if both the types
and values are not equal.

Comparison Operators

 Greater Than (>) Operator: This operator checks if the value on the left is greater than the one on the right.

 Greater Than (>=) or Equal Operator: This operator checks if the value on the left is greater than or equal to
the one on the right.

 Less Than (<) Operator: This operator checks if the value on the left is less than the one on the right.

 Less Than (<=) or Equal Operator: This operator checks if the value on the left is less than or equal to the one
on the right.

Unary Operators

 Unary Plus Operator: This operator converts its operand into a number. If the operand is already a number, it
remains unchanged.

const str = '42';

const num = +str;

console.log(num); // 42

console.log(typeof num); // number

 Unary Negation (-) Operator: This operator negates the operand.

const num = 4;

console.log(-num); // -4
 Logical NOT (!) Operator: This operator flips the boolean value of its operand. So, if the operand is true, it
becomes false, and if it's false, it becomes true.

Bitwise Operators

 Bitwise AND (&) Operator: This operator returns a 1 in each bit position for which the corresponding bits of
both operands are 1.

 Bitwise AND Assignment (&=) Operator: This operator performs a bitwise AND operation with the specified
number and reassigns the result to the variable.

 Bitwise OR (|) Operator: This operator returns a 1 in each bit position for which the corresponding bits of
either or both operands are 1.

 Bitwise OR Assignment (|=) Operator: This operator performs a bitwise OR operation with the specified
number and reassigns the result to the variable.

 Bitwise XOR (^) Operator: This operator returns a 1 in each bit position for which the corresponding bits of
either, but not both, operands are 1.

 Bitwise NOT (~) Operator: This operator inverts the binary representation of a number.

 Left Shift (<<) Operator: This operator shifts all bits to the left by a specified number of positions.

 Right Shift (>>) Operator: This operator shifts all bits to the right.

Conditional Statements, Truthy Values, Falsy Values and the Ternary Operator

 if/else if/else: An if statement takes a condition and runs a block of code if that condition is truthy. If the
condition is false, then it moves to the else if block. If none of those conditions are true, then it will execute
the else clause. Truthy values are any values that result in true when evaluated in a Boolean context like
an if statement. Falsy values are values that evaluate to false in a Boolean context.

const score = 87;

if (score >= 90) {

console.log('You got an A');

} else if (score >= 80) {

console.log('You got a B'); // You got an B

} else if (score >= 70) {

console.log('You got a C');

} else {

console.log('You failed! You need to study more!');

 Ternary Operator: This operator is often used as a shorter way to write if else statements.

const temperature = 30;

const weather = temperature > 25 ? 'sunny' : 'cool';

console.log(`It's a ${weather} day!`); // It's a sunny day!

Binary Logical Operators


 Logical AND (&&) Operator: This operator checks if both operands are true. If both are true, then it will
return the second value. If either operand is falsy, then it will return the falsy value. If both operands
are falsy, it will return the first falsy value.

const result = true && 'hello';

console.log(result); // hello

 Logical OR (||) Operator: This operator checks if at least one of the operands is truthy.

 Nullish Coalescing (??) Operator: This operator will return a value only if the first one is null or undefined.

const userSettings = {

theme: null,

volume: 0,

notifications: false,

};

let theme = userSettings.theme ?? 'light';

console.log(theme); // light

The Math Object

 The Math.random() Method: This method generates a random floating-point number between 0 (inclusive)
and 1 (exclusive). This means the possible output can be 0, but it will never actually reach 1.

 The Math.max() Method: This method takes a set of numbers and returns the maximum value.

 The Math.min() Method: This method takes a set of numbers and returns the minimum value.

 The Math.ceil() Method: This method rounds a value up to the nearest whole integer.

 The Math.floor() Method: This method rounds a value down to the nearest whole integer.

 The Math.round() Method: This method rounds a value to the nearest whole integer.

console.log(Math.round(2.3)); // 2

console.log(Math.round(4.5)); // 5

console.log(Math.round(4.8)); // 5

 The Math.trunc() Method: This method removes the decimal part of a number, returning only the integer
portion, without rounding.

 The Math.sqrt() Method: This method will return the square root of a number.

 The Math.cbrt() Method: This method will return the cube root of a number.

 The Math.abs() Method: This method will return the absolute value of a number.

 The Math.pow() Method: This method takes two numbers and raises the first to the power of the second.

Common Number Methods

 isNaN(): NaN stands for "Not-a-Number". It's a special value that represents an unrepresentable or
undefined numerical result. The isNaN() function property is used to determine whether a value is NaN or
not. Number.isNaN() provides a more reliable way to check for NaN values, especially in cases where type
coercion might lead to unexpected results with the global isNaN() function.

console.log(isNaN(NaN)); // true

console.log(isNaN(undefined)); // true

console.log(isNaN({})); // true

console.log(isNaN(true)); // false

console.log(isNaN(null)); // false

console.log(isNaN(37)); // false

console.log(Number.isNaN(NaN)); // true

console.log(Number.isNaN(Number.NaN)); // true

console.log(Number.isNaN(0 / 0)); // true

console.log(Number.isNaN("NaN")); // false

console.log(Number.isNaN(undefined)); // false

 The parseFloat() Method: This method parses a string argument and returns a floating-point number. It's
designed to extract a number from the beginning of a string, even if the string contains non-numeric
characters later on.

 The parseInt() Method: This method parses a string argument and returns an integer. parseInt() stops
parsing at the first non-digit it encounters. For floating-point numbers, it returns only the integer part. If it
can't find a valid integer at the start of the string, it returns NaN.

 The toFixed() Method: This method is called on a number and takes one optional argument, which is the
number of digits to appear after the decimal point. It returns a string representation of the number with the
specified number of decimal places.

JavaScript Comparisons and Conditionals

Comparisons and the null and undefined Data Types

 Comparisons and undefined: A variable is undefined when it has been declared but hasn't been assigned a
value. It's the default value of uninitialized variables and function parameters that weren't provided an
argument. undefined converts to NaN in numeric contexts, which makes all numeric comparisons
with undefined return false.

console.log(undefined > 0); // false

console.log(undefined < 0); // false

console.log(undefined == 0); // false

 Comparisons and null: The null type represents the intentional absence of a value. When using the equality
operator, null and undefined are considered equal. However, when using the strict equality operator (===),
which checks both value and type without performing type coercion, null and undefined are not equal:
console.log(null == undefined); // true

console.log(null === undefined); // false

switch Statements

 Definition: A switch statement evaluates an expression and matches its value against a series of case clauses.
When a match is found, the code block associated with that case is executed. A break statement should be
placed at the end of each case, to terminate its execution and continue with the next. The default case is an
optional case and only executes if none of the other cases match. The default case is placed at the end of
a switch statement.

const dayOfWeek = 3;

switch (dayOfWeek) {

case 1:

console.log("It's Monday! Time to start the week strong.");

break;

case 2:

console.log("It's Tuesday! Keep the momentum going.");

break;

case 3:

console.log("It's Wednesday! We're halfway there.");

break;

case 4:

console.log("It's Thursday! Almost the weekend.");

break;

case 5:

console.log("It's Friday! The weekend is near.");

break;

case 6:

console.log("It's Saturday! Enjoy your weekend.");

break;

case 7:

console.log("It's Sunday! Rest and recharge.");

break;

default:

console.log("Invalid day! Please enter a number between 1 and 7.");


}

JavaScript Functions

JavaScript Functions

 Functions are reusable blocks of code that perform a specific task.

 Functions can be defined using the function keyword followed by a name, a list of parameters, and a block of
code that performs the task.

function addNumbers(x, y, z) {

return x + y + z;}

console.log(addNumbers(5, 3, 8)); // Output: 16

 Arguments are values passed to a function when it is called.

 A function call is the process of executing a function in a program by specifying the function's name followed
by parentheses, optionally including arguments inside the parentheses.

 When a function finishes its execution, it will always return a value.

 By default, the return value of a function is undefined.

 The return keyword is used to specify the value to be returned from the function and ends the function
execution.

 Default parameters allow functions to have predefined values that will be used if an argument is not
provided when the function is called. This makes functions more flexible and prevents errors in cases where
certain arguments might be omitted.

const calculateTotal = (amount, taxRate = 0.05) => {

return amount + (amount * taxRate);

};

console.log(calculateTotal(100)); // Output: 105

 Function Expressions are functions that you assign to variables. By doing this, you can use the function in any
part of your code where the variable is accessible.

const multiplyNumbers = function(firstNumber, secondNumber) {

return firstNumber * secondNumber;

};

console.log(multiplyNumbers(4, 5)); // Output: 20

Arrow Functions

 Arrow functions are a more concise way to write functions in JavaScript.

const calculateArea = (length, width) => {


const area = length * width;

return `The area of the rectangle is ${area} square units.`;

};

console.log(calculateArea(5, 10)); // Output: "The area of the rectangle is 50 square units."

 When defining an arrow function, you do not need the function keyword.

 If you are using a single parameter, you can omit the parentheses around the parameter list.

const cube = x => {

return x * x * x;

};

console.log(cube(3)); // Output: 27

 If the function body consists of a single expression, you can omit the curly braces and the return keyword.

const square = number => number * number;

console.log(square(5)); // Output: 25

Scope in Programming

 Global scope: This is the outermost scope in JavaScript. Variables declared in the global scope are accessible
from anywhere in the code and are called global variables.

 Local scope: This refers to variables declared within a function. These variables are only accessible within the
function where they are declared and are called local variables.

 Block scope: A block is a set of statements enclosed in curly braces {} such as in if statements, or loops.

 Block scoping with let and const provides even finer control over variable accessibility, helping to prevent
errors and make your code more predictable.

JavaScript Array

 Definition: A JavaScript array is an ordered collection of values, each identified by a numeric index. The
values in a JavaScript array can be of different data types, including numbers, strings, booleans, objects, and
even other arrays. Arrays are contiguous in memory, which means that all elements are stored in a single,
continuous block of memory locations, allowing for efficient indexing and fast access to elements by their
index.

const developers = ["Jessica", "Naomi", "Tom"];

 Accessing Elements From Arrays: To access elements from an array, you will need to reference the array
followed by its index number inside square brackets. JavaScript arrays are zero based indexed which means
the first element is at index 0, the second element is at index 1, etc. If you try to access an index that doesn't
exist for the array, then JavaScript will return undefined.

const developers = ["Jessica", "Naomi", "Tom"];

developers[0] // "Jessica"

developers[1] // "Naomi"
developers[10] // undefined

 length Property: This property is used to return the number of items in a array.

const developers = ["Jessica", "Naomi", "Tom"];

developers.length // 3

 Updating Elements in an Array: To update an element in an array, you use the assignment operator (=) to
assign a new value to the element at a specific index.

const fruits = ['apple', 'banana', 'cherry'];

fruits[1] = 'blueberry';

console.log(fruits); // ['apple', 'blueberry', 'cherry']

Two Dimensional Arrays

 Definition: A two-dimensional array is essentially an array of arrays. It's used to represent data that has a
natural grid-like structure, such as a chessboard, a spreadsheet, or pixels in an image. To access an element
in a two-dimensional array, you need two indices: one for the row and one for the column.

const chessboard = [

['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'],

['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'],

[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],

[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],

[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],

[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],

['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'],

['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r']

];

console.log(chessboard[0][3]); // "Q"

Array Destructuring

 Definition: Array destructuring is a feature in JavaScript that allows you to extract values from arrays and
assign them to variables in a more concise and readable way. It provides a convenient syntax for unpacking
array elements into distinct variables.

const fruits = ["apple", "banana", "orange"];

const [first, second, third] = fruits;

console.log(first); // "apple"

console.log(second); // "banana"

console.log(third); // "orange"
 Rest Syntax: This allows you to capture the remaining elements of an array that haven't been destructured
into a new array.

const fruits = ["apple", "banana", "orange", "mango", "kiwi"];

const [first, second, ...rest] = fruits;

console.log(first); // "apple"

console.log(second); // "banana"

console.log(rest); // ["orange","mango","kiwi"]

Common Array Methods

 push() Method: This method is used to add elements to the end of the array and will return the new length.

const desserts = ["cake", "cookies", "pie"];

desserts.push("ice cream");

console.log(desserts); // ["cake", "cookies", "pie", "ice cream"];

 pop() Method: This method is used to remove the last element from an array and will return that removed
element. If the array is empty, then the return value will be undefined.

const desserts = ["cake", "cookies", "pie"];

desserts.pop();

console.log(desserts); // ["cake", "cookies"];

 shift() Method: This method is used to remove the first element from an array and return that removed
element. If the array is empty, then the return value will be undefined.

const desserts = ["cake", "cookies", "pie"];

desserts.shift();

console.log(desserts); // ["cookies", "pie"];

 unshift() Method: This method is used to add elements to the beginning of the array and will return the new
length.

const desserts = ["cake", "cookies", "pie"];

desserts.unshift("ice cream");

console.log(desserts); // ["ice cream", "cake", "cookies", "pie"];

 indexOf() Method: This method is useful for finding the first index of a specific element within an array. If the
element cannot be found, then it will return -1.

const fruits = ["apple", "banana", "orange", "banana"];

const index = fruits.indexOf("banana");

console.log(index); // 1

console.log(fruits.indexOf("not found")); // -1

 splice() Method: This method is used to add or remove elements from any position in an array. The return
value for the splice() method will be an array of the items removed from the array. If nothing is removed,
then an empty array will be returned. This method will mutate the original array, modifying it in place rather
than creating a new array. The first argument specifies the index at which to begin modifying the array. The
second argument is the number of elements you wish to remove. The following arguments are the elements
you wish to add.

const colors = ["red", "green", "blue"];

colors.splice(1, 0, "yellow", "purple");

console.log(colors); // ["red", "yellow", "purple", "green", "blue"]

 includes() Method: This method is used to check if an array contains a specific value. This method
returns true if the array contains the specified element, and false otherwise.

const programmingLanguages = ["JavaScript", "Python", "C++"];

console.log(programmingLanguages.includes("Python")); // true

console.log(programmingLanguages.includes("Perl")); // false

 concat() Method: This method creates a new array by merging two or more arrays.

const programmingLanguages = ["JavaScript", "Python", "C++"];

const newList = programmingLanguages.concat("Perl");

console.log(newList); // ["JavaScript", "Python", "C++", "Perl"]

 slice() Method: This method returns a shallow copy of a portion of the array at a specified index or the entire
array. A shallow copy will copy the reference to the array instead of duplicating it.

const programmingLanguages = ["JavaScript", "Python", "C++"];

const newList = programmingLanguages.slice(1);

console.log(newList); // ["Python", "C++"]

 Spread Syntax: The spread syntax is used to create shallow copies of an array.

const originalArray = [1, 2, 3];

const shallowCopiedArray = [...originalArray];

shallowCopiedArray.push(4);

console.log(originalArray); // [1, 2, 3]

console.log(shallowCopiedArray); // [1, 2, 3, 4]

 split() Method: This method divides a string into an array of substrings and specifies where each split should
happen based on a given separator. If no separator is provided, the method returns an array containing the
original string as a single element.

const str = "hello";

const charArray = str.split("");

console.log(charArray); // ["h","e","l","l","o"]

 reverse() Method: This method reverses an array in place.

const desserts = ["cake", "cookies", "pie"];


console.log(desserts.reverse()); // ["pie","cookies","cake"]

 join() Method: This method concatenates all the elements of an array into a single string, with each element
separated by a specified separator. If no separator is provided, or an empty string ("") is used, the elements
will be joined without any separator.

const reversedArray = ["o", "l", "l", "e", "h"];

const reversedString = reversedArray.join("");

console.log(reversedString); // "olleh"

JavaScript Objects

 Definition: An object is a data structure that is made up of properties. A property consists of a key and a
value. To access data from an object you can use either dot notation or bracket notation.

const person = {

name: "Alice",

age: 30,

city: "New York"

};

console.log(person.name); // Alice

console.log(person["name"]); // Alice

To set a property of an existing object you can use either dot notation or bracket notation together with the
assignment operator.

const person = {

name: "Alice",

age: 30

};

person.job = "Engineer"

person["hobby"] = "Knitting"

console.log(person); // {name: 'Alice', age: 30, job: 'Engineer', hobby: 'Knitting'}

Removing Properties From an Object

 delete Operator: This operator is used to remove a property from an object.

const person = {

name: "Alice",

age: 30,
job: "Engineer"

};

delete person.job;

console.log(person.job); // undefined

Checking if an Object has a Property

 hasOwnProperty() Method: This method returns a boolean indicating whether the object has the specified
property as its own property.

const person = {

name: "Alice",

age: 30

};

console.log(person.hasOwnProperty("name")); // true

console.log(person.hasOwnProperty("job")); // false

 in Operator: This operator will return true if the property exists in the object.

const person = {

name: "Bob",

age: 25

};

console.log("name" in person); // true

Accessing Properties From Nested Objects

 Accessing Data: Accessing properties from nested objects involves using the dot notation or bracket
notation, much like accessing properties from simple objects. However, you'll need to chain these accessors
to drill down into the nested structure.

const person = {

name: "Alice",

age: 30,

contact: {

email: "[email protected]",

phone: {

home: "123-456-7890",

work: "098-765-4321"

}
};

console.log(person.contact.phone.work); // "098-765-4321"

Primitive and Non Primitive Data Types

 Primitive Data Types: These data types include numbers, strings, booleans, null, undefined, and symbols.
These types are called "primitive" because they represent single values and are not objects. Primitive values
are immutable, which means once they are created, their value cannot be changed.

 Non Primitive Data Types: In JavaScript, these are objects, which include regular objects, arrays, and
functions. Unlike primitives, non-primitive types can hold multiple values as properties or elements.

Object Methods

 Definition: Object methods are functions that are associated with an object. They are defined as properties
of an object and can access and manipulate the object's data. The this keyword inside the method refers to
the object itself, enabling access to its properties.

const person = {

name: "Bob",

age: 30,

sayHello: function() {

return "Hello, my name is " + this.name;

};

console.log(person.sayHello()); // "Hello, my name is Bob"

Object Constructor

 Definition: In JavaScript, a constructor is a special type of function used to create and initialize objects. It is
invoked with the new keyword and can initialize properties and methods on the newly created object.
The Object() constructor creates a new empty object.

new Object()

Working with the Optional Chaining Operator (?.)

 Definition: This operator lets you safely access object properties or call methods without worrying whether
they exist.

const user = {

name: "John",

profile: {

email: "[email protected]",
address: {

street: "123 Main St",

city: "Somewhere"

};

console.log(user.profile?.address?.street); // "123 Main St"

console.log(user.profile?.phone?.number); // undefined

Object Destructuring

 Definition: Object destructuring allows you to extract values from objects and assign them to variables in a
more concise and readable way.

const person = { name: "Alice", age: 30, city: "New York" };

const { name, age } = person;

console.log(name); // Alice

console.log(age); // 30

Working with JSON

 Definition: JSON stands for JavaScript Object Notation. It is a lightweight, text-based data format that is
commonly used to exchange data between a server and a web application.

"name": "Alice",

"age": 30,

"isStudent": false,

"list of courses": ["Mathematics", "Physics", "Computer Science"]

 JSON.stringify(): This method is used to convert a JavaScript object into a JSON string. This is useful when
you want to store or transmit data in a format that can be easily shared or transferred between systems.

const user = {

name: "John",

age: 30,

isAdmin: true

};

const jsonString = JSON.stringify(user);

console.log(jsonString); // '{"name":"John","age":30,"isAdmin":true}'
 JSON.parse(): This method converts a JSON string back into a JavaScript object. This is useful when you
retrieve JSON data from a web server or localStorage and you need to manipulate the data in your
application.

const jsonString = '{"name":"John","age":30,"isAdmin":true}';

const userObject = JSON.parse(jsonString);

// result: { name: 'John', age: 30, isAdmin: true }

console.log(userObject);

You might also like