JavaScript is a programming language that is commonly used in web development. It is a high-level, interpreted language that is well-suited for building web applications. JavaScript is often used to add interactivity to websites and can be used to make web pages more responsive to user input. It is a popular choice for building web-based applications and is widely supported by modern web browsers.
Running Code in The Console.
THE EASIEST PLACE TO START
We will run our code early on using the chrome developer tools console. Then, we’ll learn how to write external scripts
How to go with Chrome Developer Tools Console:
1: Open Google Chrome:
2: Go with Three dots ( Top right corner):
3: Click on more tools:
4: Click on Developer tools :
5: And go with the Console tab
Now let’s write our first JavaScript Code here.
Type any number here and enter, you are using JavaScript.
CSS-Data Types:
In JavaScript, there are a few different types of data that you can work with. These include:
- Number: Numbers in JavaScript can be either integers or floating-point values. There is no separate type for integers and floating point values, so you can use the same type for both.
- String: Strings are used to represent text in JavaScript. They can be written with either single quotes (‘) or double quotes (“).
- Boolean: A boolean value is a value that is either true or false. It is often used in control statements (e.g. if statements) to test whether a certain condition is true or false.
- Null: The null type represents a null or empty value. It is used to represent the absence of a value.
- Undefined: The undefined type represents a value that has not been assigned a value.
- Object: An object is a collection of key-value pairs. It is a more complex data type that is often used to store data that is more structured than a simple value like a number or string.
- Symbol: A symbol is a new data type introduced in ECMAScript 6 (ES6). It is a unique and immutable primitive value, and is often used as an identifier for object properties.
These are the basic data types in JavaScript, but there are also a few other types that you may encounter, such as arrays and functions.
CSS Numbers:
n JavaScript, numbers can be either integers or floating point values. There is no separate type for integers and floating point values, so you can use the same type for both.
Here are a few examples of how you might use numbers in JavaScript:
let x = 10; // x is an integer
let y = 3.14; // y is a floating point value
let z = 1.23e5; // z is a floating point value (123000)
You can perform basic arithmetic operations on numbers using the usual operators: +
, -
, *
, /
, and %
. For example:
let a = x + y; // a is 13.14
let b = x * y; // b is 31.4
let c = x / y; // c is 3.184713375796178
let d = x % y; // d is 3.0999999999999996
JavaScript also provides a few built-in functions for working with numbers. For example, you can use the Math.floor()
function to round a number down to the nearest integer, and the Math.random()
function to generate a random number between 0 and 1.
let e = Math.floor(y); // e is 3
let f = Math.random(); // f is a random number between 0 and 1
CSS-MATH OPERATIONS:
In the above example, almost all math operators are used with numbers, and one thing you can see //addition //Subtraction these are comments. Comments are not included in the output. If you are familiar with programming Comments are not new to you.
NOT A NUMBER:
NaN is a numeric value that represents something that is ………… not a number.
n JavaScript, the NaN
(Not a Number) value represents a value that is not a number. This can occur when you try to perform an operation that expects numeric input, but the input provided is not a number.
For example, the following code will result in a NaN
value:
let x = "hello";
let y = x / 2;
console.log(y);
// output: NaN
The NaN
value is considered a special value in JavaScript, and it is not equal to any other value, including itself. This means that the following expression will return false
:
console.log(NaN == NaN);
// output: false
To test whether a value is NaN
, you can use the isNaN()
function. This function returns true
if the value is NaN
, and false
if the value is a number or any other value.
console.log(isNaN(x / 2));
// output: true
console.log(isNaN(y));
// output: trueExercise:
WHAT DOES THIS EVALUATE TO?
-
4 + 3 * 4/2
-
( 13 % 5 ) ** 2
-
200 + 0 / 0
JS-VARIABLES :
In JavaScript, a variable is a container that holds a value. You can use variables to store data, perform calculations, and manipulate values in your code.
To create a variable in JavaScript, you use the var
keyword followed by the name of the variable. Here’s an example:
var x;
You can also assign a value to the variable when you declare it:
var x = 10;
You can declare multiple variables at the same time by separating them with a comma:
var x = 10, y = 20, z = 30;
You can also use the let
and const
keywords to declare variables in JavaScript. The let
keyword declares a block-scoped variable, which means that the variable is only accessible within the block of code in which it is defined. The const
keyword declares a constant, which means that the value of the variable cannot be changed once it is set.
Here are some examples of using let
and const
to declare variables:
let x = 10;
const y = 20;
x = 15; // valid
y = 25; // invalid (will throw a TypeError)
You can also use variables to perform calculations. For example:
var a = 10, b = 20;
var c = a + b; // c is 30
var d = a * b;
// d is 200
var e = a / b; // e is 0.5
You can also use variables to store the result of a function or method call. For example:
function getNumber() {
return 10;
}
var x = getNumber(); // x is 10What is the value of totalScore?
where: Let totalScore =199; totalScore +1;
Ans:
In this code, you are declaring a variable totalScore
and assigning it the value 199
. Then, you are using the +
operator to add 1
to totalScore
. However, this code will not update the value of totalScore
.
To update the value of totalScore
, you need to re-assign the result of the calculation to the variable. Here’s how you can do this:
let totalScore = 199;
totalScore = totalScore + 1;
Alternatively, you can use the compound assignment operator +=
to add 1
to totalScore
:
let totalScore = 199;
totalScore += 1;
Both of these approaches will update the value of totalScore
to 200
.
What is the value of temperature?
Where: const temperature =83; temperature=85;
Ans:
In this code, you are declaring a constant variable temperature
and assigning it the value 83
. Then, you are attempting to re-assign a new value 85
to temperature
. However, this will result in an error because constants cannot be re-assigned.
The const
keyword is used to declare a constant variable, which means that the value of the variable cannot be changed once it is set. If you try to re-assign a new value to a constant variable, you will get a TypeError
.
Here’s an example of what this code would look like:
const temperature = 83;
temperature = 85; // TypeError: Assignment to constant variable
If you want to be able to change the value of a variable, you should use the let
keyword to declare it instead of const
. The let
keyword declares a block-scoped variable, which means that the value of the variable can be changed within the block of code in which it is defined.
What is the value of bankBalance?
Where: let BankBalance = 100;BankBalance +=200; BankBalance –;
Ans:
In this code, you are declaring a variable BankBalance
and assigning it the value 100
. Then, you are using the compound assignment operator +=
to add 200
to BankBalance
. This updates the value of BankBalance
to 300
.
Finally, you are using the decrement operator --
to decrease the value of BankBalance
by 1
. This updates the value of BankBalance
to 299
.
So, after this code is executed, the value of BankBalance
will be 299
JS- Booleans:
Booleans in JavaScript are a primitive data type that can have only two values: true
or false
. They are often used in conditional statements to check if a condition is true or false.
Here are some examples of how you can use Booleans in JavaScript:
let isRainy = true;
if (isRainy) {
console.log(“Don’t forget your umbrella!”);
} else {
console.log(“It’s a beautiful day!”);
}
You can also use Booleans in comparison operators. For example:
let x = 10;
let y = 20;
console.log(x > y); // Output: false
console.log(x < y); // Output: true
console.log(x === y); // Output: false
Booleans are often used to check the truthiness or falsiness of a value. In JavaScript, the following values are considered falsy:
false
0
(zero)""
(empty string)null
undefined
NaN
(Not a Number)
All other values, including objects, arrays, and all other primitive data types, are considered truthy.
You can use the Boolean
function to convert a value to a Boolean. For example:
let x = "hello";
let y = 0;
console.log(Boolean(x)); // Output: true
console.log(Boolean(y)); // Output: false
VARIABLES CAN CHANGE TYPE:
Yes, variables in JavaScript can change type. This is because JavaScript is a dynamically-typed language, which means that the type of a value can change at runtime.
For example, consider the following code:
let x = 10;
console.log(typeof x); // Output: "number"
x = "hello";
console.log(typeof x); // Output: "string"
x = true;
console.log(typeof x); // Output:
“boolean”console.log(typeof x); // Output: "object"
In this code, the x
variable starts as a number, but it is later reassigned to a string, a boolean, and an object. The typeof
operator returns the type of the value stored in the variable. As you can see, the type of x
changes each time it is reassigned.
It’s important to be aware that variables in JavaScript can change type, as this can sometimes lead to unexpected behavior if you’re not careful. However, it can also be a useful feature, as it allows you to be flexible with your data and write code that is more adaptable to changing requirements.
It doesn’t really make sense to change from a number to a boolean here, but we can!
JavaScript Functions
In JavaScript, a function is a block of code that can be defined once and called multiple times. Functions are a key feature of the language and are used to perform a specific task or calculate a value.
Here’s an example of a simple function in JavaScript that takes a single argument and returns a value:
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("John")); // prints "Hello, John!"
To define a function in JavaScript, you use the function
keyword followed by the name of the function and a list of parameters enclosed in parentheses. The function body is then defined inside curly braces.
To call a function in JavaScript, you use the name of the function followed by a list of arguments enclosed in parentheses. The function will execute the code inside its body and return a value if a return
statement is encountered.
Functions can also be defined as anonymous functions, which do not have a name and are usually assigned to a variable:
let greet = function(name) {
return "Hello, " + name + "!";
};
console.log(greet("John")); // prints "Hello, John!"
JavaScript also has arrow functions, which are a concise way to define anonymous functions. Here’s the same example as above using an arrow function:
let greet = (name) => {
return "Hello, " + name + "!";
};
console.log(greet("John")); // prints "Hello, John!"
JavaScript Objects
JavaScript objects are collections of key-value pairs. The values can be any data type, including numbers, strings, arrays, or even other objects.
Here’s an example of an object in JavaScript:
const person = {
name: 'John',
age: 30,
location: 'New York'
};
To access the values in an object, you can use the dot notation or the bracket notation. Here are some examples:
console.log(person.name);
// Output: "John"
console.log(person['age']);
// Output: 30
// You can also use the bracket notation to access a value using a variable
const property = 'location';
console.log(person[property]);
// Output: "New York"
You can also add, modify, and delete properties in an object like this:
// Add a new property
person.email = '[email protected]';
// Modify a property
person.age = 31;
// Delete a property
delete person.location;
JavaScript objects are useful for storing and organizing data in a structured way. They are commonly used to represent real-world objects, such as a user profile or a product in an online store.
JavaScript Events
JavaScript events are actions that can be detected by your JavaScript code. They allow you to specify the behavior of your web page when certain events occur, such as when a user clicks a button or hovers over an element.
Here’s an example of how you can use an event in JavaScript:
const button = document.querySelector('button');
button.addEventListener('click', () =>
{
console.log('Button was clicked');
});
In this example, the addEventListener
method is used to attach a click event to the button element. When the button is clicked, the callback function will be executed, and the message “Button was clicked” will be logged to the console.
There are many different types of events in JavaScript, including:
- Mouse events (e.g. click, mouseover)
- Keyboard events (e.g. keydown, keyup)
- Form events (e.g. submit, focus)
- Document events (e.g. ready, load)
You can use events to create interactive and dynamic websites by writing JavaScript code that responds to user actions. For example, you can use events to show and hide elements, validate form inputs, or submit a form using AJAX.
JavaScript Strings
JavaScript strings are for storing and manipulating text.
A JavaScript string is zero or more characters written inside quotes.
Example
let text = “John Doe”;
ou can use single or double quotes:
Example
let carName1 = “Volvo XC60”; // Double quotes
let carName2 = ‘Volvo XC60’; // Single quotes
You can use quotes inside a string, as long as they don’t match the quotes surrounding the string:
Example
let answer1 = “It’s alright”;
let answer2 = “He is called ‘Johnny'”;
let answer3 = ‘He is called “Johnny”‘;
String Length
To find the length of a string, use the built-in length
property:
Example
let text = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
let length = text.length;
very soon discussed below topics:
JavaScript String Methods
String length String slice() String substring() String substr() String replace() String replaceAll() String toUpperCase() String toLowerCase() String concat() |
String trim() String trimStart() String trimEnd() String padStart() String padEnd() String charAt() String charCodeAt() String split() |
JavaScript String Length
The length
property returns the length of a string:
Example
let text = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
let length = text.length;
Extracting String Parts
There are 3 methods for extracting a part of a string:
slice(start, end)
substring(start, end)
substr(start, length)
JavaScript String slice()
slice()
extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: start position, and end position (end not included).
Example
Slice out a portion of a string from position 7 to position 13:
let text = “Apple, Banana, Kiwi”;
let part = text.slice(7, 13);
Note
JavaScript counts positions from zero. First position is 0. Second position is 1.
Examples
If you omit the second parameter, the method will slice out the rest of the string:
let text = “Apple, Banana, Kiwi”;
let part = text.slice(7);
If a parameter is negative, the position is counted from the end of the string:
let text = “Apple, Banana, Kiwi”;
let part = text.slice(-12);
This example slices out a portion of a string from position -12 to position -6:
let text = “Apple, Banana, Kiwi”;
let part = text.slice(-12, –6);
JavaScript String Search
JavaScript Search Methods
- String indexOf()
- String lastIndexOf()
- String search()
- String match()
- String matchAll()
- String includes()
- String startsWith()
- String endsWith()
JavaScript String indexOf()
The indexOf()
method returns the index of (position of) the first occurrence of a string in a string:
Example
let str = “Please locate where ‘locate’ occurs!”;
str.indexOf(“locate”);
Note
JavaScript counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is the third, …
JavaScript String lastIndexOf()
The lastIndexOf()
method returns the index of the last occurrence of a specified text in a string:
Example
let text = “Please locate where ‘locate’ occurs!”;
text.lastIndexOf(“locate”);
Both indexOf()
, and lastIndexOf()
return -1 if the text is not found:
Example
let text = “Please locate where ‘locate’ occurs!”;
text.lastIndexOf(“John”);
Both methods accept a second parameter as the starting position for the search:
Example
let text = “Please locate where ‘locate’ occurs!”;
text.indexOf(“locate”, 15);
The lastIndexOf()
methods searches backwards (from the end to the beginning), meaning: if the second parameter is 15
, the search starts at position 15, and searches to the beginning of the string.
Example
let text = “Please locate where ‘locate’ occurs!”;
text.lastIndexOf(“locate”, 15);
JavaScript String search()
The search()
method searches a string for a string (or a regular expression) and returns the position of the match:
Examples
let str = “Please locate where ‘locate’ occurs!”;
str.search(“locate”);
let str = “Please locate where ‘locate’ occurs!”;
str.search(/locate/);
Did You Notice?
The two methods, indexOf()
and search()
, are equal?
They accept the same arguments (parameters), and return the same value?
The two methods are NOT equal. These are the differences:
- The
search()
method cannot take a second start position argument. - The
indexOf()
method cannot take powerful search values (regular expressions).
You will learn more about regular expressions in a later chapter.
JavaScript String match()
The match()
method returns an array containing the results of matching a string against a string (or a regular expression).
Examples
Perform a search for “ain”:
let text = “The rain in SPAIN stays mainly in the plain”;
text.match(“ain”);
Perform a search for “ain”:
let text = “The rain in SPAIN stays mainly in the plain”;
text.match(/ain/);
Perform a global search for “ain”:
let text = “The rain in SPAIN stays mainly in the plain”;
text.match(/ain/g);
Perform a global, case-insensitive search for “ain”:
let text = “The rain in SPAIN stays mainly in the plain”;
text.match(/ain/gi);
Note
If a regular expression does not include the g modifier (global search), match()
will return only the first match in the string.
Read more about regular expressions in the chapter JS RegExp.
JavaScript String matchAll()
The matchAll()
method returns an iterator containing the results of matching a string against a string (or a regular expression).
Example
const iterator = text.matchAll(“Cats”);
If the parameter is a regular expression, the global flag (g) must be set, otherwise a TypeError is thrown.
Example
const iterator = text.matchAll(/Cats/g);
If you want to search case insensitive, the insensitive flag (i) must be set:
Example
const iterator = text.matchAll(/Cats/gi);
JavaScript String includes()
The includes()
method returns true if a string contains a specified value.
Otherwise it returns false
.
Examples
Check if a string includes “world”:
let text = “Hello world, welcome to the universe.”;
text.includes(“world”);
Check if a string includes “world”. Start at position 12:
let text = “Hello world, welcome to the universe.”;
text.includes(“world”, 12);
Notes
includes()
is case sensitive.
includes()
is an ES6 feature.
includes()
is not supported in Internet Explorer.
JavaScript String startsWith()
The startsWith()
method returns true
if a string begins with a specified value.
Otherwise it returns false
:
Examples
Returns true:
let text = “Hello world, welcome to the universe.”;
text.startsWith(“Hello”);
Returns false:
let text = “Hello world, welcome to the universe.”;
text.startsWith(“world”)
A start position for the search can be specified:
Returns false:
let text = “Hello world, welcome to the universe.”;
text.startsWith(“world”, 5)
Returns true:
let text = “Hello world, welcome to the universe.”;
text.startsWith(“world”, 6)
Notes
startsWith()
is case sensitive.
startsWith()
is an ES6 feature.
startsWith()
is not supported in Internet Explorer.
JavaScript String endsWith()
The endsWith()
method returns true
if a string ends with a specified value.
Otherwise it returns false
:
Examples
Check if a string ends with “Doe”:
let text = “John Doe”;
text.endsWith(“Doe”);
Check if the 11 first characters of a string ends with “world”:
let text = “Hello world, welcome to the universe.”;
text.endsWith(“world”, 11);
Notes
endsWith()
is case sensitive.
endsWith()
is an ES6 feature.
endsWith()
is not supported in Internet Explorer.
JavaScript Template Literals
JavaScript Numbers
Here are some examples of JavaScript numbers:
- Integer: 42
- Floating-point: 42.0
- Hexadecimal: 0x2A
- Binary: 0b101010
- NaN: NaN
- Infinity: Infinity
- Negative Infinity: -Infinity
Examples of arithmetic operations with numbers:
- Addition: 2 + 3 = 5
- Subtraction: 5 – 2 = 3
- Multiplication: 2 * 3 = 6
- Division: 10 / 2 = 5
- Modulo: 10 % 3 = 1
Example of converting a string to a number:
let str = "42";
let num = Number(str);
console.log(typeof num); // Output: number
BigInt is a new numeric data type in JavaScript introduced in ECMAScript 2020 that can represent integers with arbitrarily large precision. It is used to represent integers that are too big to be represented with the normal Number type. To create a BigInt, add the suffix n
to a number literal or call the BigInt()
function with a string argument representing an integer.
Examples:
let bigInt1 = 9007199254740993n;
let bigInt2 = BigInt("9007199254740993");
console.log(typeof bigInt1); // Output: bigint
console.log(typeof bigInt2); // Output: bigint
Note: BigInts have their own set of operations and cannot be mixed with normal JavaScript numbers without explicit conversion.
JavaScript Number Methods
JavaScript Number type has several built-in methods that can be used to perform operations on numbers:
toFixed()
: returns a string representation of the number with a specified number of decimal places.toPrecision()
: returns a string representation of the number with a specified number of significant digits.toExponential()
: returns a string representation of the number in exponential notation.valueOf()
: returns the primitive value of the number object.parseInt()
: parses a string argument and returns an integer.parseFloat()
: parses a string argument and returns a floating-point number.isNaN()
: returns a Boolean indicating whether the passed value is NaN (Not a Number).isFinite()
: returns a Boolean indicating whether the passed value is a finite number.
Example:
let num = 42.123456;
console.log(num.toFixed(2)); // Output: 42.12
console.log(num.toPrecision(3)); // Output: 42.1
console.log(num.toExponential(2)); // Output: 4.21e+1
console.log(num.valueOf()); // Output: 42.123456
console.log(parseInt("42")); // Output: 42
console.log(parseFloat("42.123456")); // Output: 42.123456
console.log(isNaN(42)); // Output: false
console.log(isFinite(42)); // Output: true
JavaScript Number Properties
JavaScript Number type has several built-in properties that provide information about numbers:
MAX_VALUE
: returns the largest positive finite value of the number type in JavaScript.MIN_VALUE
: returns the smallest positive value of the number type in JavaScript.POSITIVE_INFINITY
: represents positive infinity.NEGATIVE_INFINITY
: represents negative infinity.NaN
: represents a value that is not a number.EPSILON
: returns the difference between 1 and the smallest floating-point number greater than 1.MAX_SAFE_INTEGER
: returns the largest integer that can be safely represented in JavaScript.MIN_SAFE_INTEGER
: returns the smallest integer that can be safely represented in JavaScript.
Example:
console.log(Number.MAX_VALUE); // Output: 1.7976931348623157e+308
console.log(Number.MIN_VALUE); // Output: 5e-324
console.log(Number.POSITIVE_INFINITY); // Output: Infinity
console.log(Number.NEGATIVE_INFINITY); // Output: -Infinity
console.log(Number.NaN); // Output: NaN
console.log(Number.EPSILON); // Output: 2.220446049250313e-16
console.log(Number.MAX_SAFE_INTEGER); // Output: 9007199254740991
console.log(Number.MIN_SAFE_INTEGER); // Output: -9007199254740991
JavaScript Arrays
An array is a data structure in JavaScript that can store a collection of values or elements of any data type. Arrays are used to store multiple values in a single variable. Arrays are created using square brackets []
, and values are separated by commas.
Example:
let fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // Output: "apple"
console.log(fruits[1]); // Output: "banana"
console.log(fruits[2]); // Output: "cherry"
JavaScript arrays have several built-in methods that can be used to perform operations on arrays, such as:
push()
: adds an element to the end of the array.pop()
: removes the last element of the array.unshift()
: adds an element to the beginning of the array.shift()
: removes the first element of the array.splice()
: adds or removes elements from the array.slice()
: returns a new array with a portion of the original array.concat()
: returns a new array that is a combination of two or more arrays.join()
: returns a string representation of the array, with the elements joined by a specified separator.
Example:
let fruits = ["apple", "banana", "cherry"];
fruits.push("orange");
console.log(fruits); // Output: ["apple", "banana", "cherry", "orange"]
fruits.pop();
console.log(fruits); // Output: ["apple", "banana", "cherry"]
fruits.unshift("lemon");
console.log(fruits); // Output: ["lemon", "apple", "banana", "cherry"]
fruits.shift();
console.log(fruits); // Output: ["apple", "banana", "cherry"]
fruits.splice(1, 1, "mango");
console.log(fruits); // Output: ["apple", "mango", "cherry"]
let newFruits = fruits.slice(1);
console.log(newFruits); // Output: ["mango", "cherry"]
let allFruits = fruits.concat(newFruits);
console.log(allFruits); // Output: ["apple", "mango", "cherry", "mango", "cherry"]
let stringFruits = fruits.join(", ");
console.log(stringFruits); // Output: "apple, mango, cherry"
JavaScript Array Methods
JavaScript arrays have several methods for manipulating and transforming data:
- push() – adds an element to the end of an array.
- pop() – removes the last element from an array.
- shift() – removes the first element from an array.
- unshift() – adds an element to the beginning of an array.
- sort() – sorts the elements of an array in place.
- reverse() – reverses the order of the elements in an array.
- splice() – adds/removes elements from an array.
- slice() – returns a shallow copy of a portion of an array.
- map() – creates a new array with the results of calling a provided function on every element in the calling array.
- filter() – creates a new array with all elements that pass the test implemented by the provided function.
- reduce() – applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.
Note: These are not all the methods available for arrays, but they are some of the most commonly used ones.
JavaScript Sorting Arrays
JavaScript arrays have a sort() method which sorts the elements of an array in place. By default, it sorts the elements in ascending order according to their Unicode code points.
To sort an array in descending order, you can pass a compare function as an argument to the sort() method:
array.sort(function(a, b) {
return b - a;
});
Here’s an example to sort an array of numbers in ascending order:
let numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
numbers.sort(function(a, b) {
return a - b;
});
console.log(numbers);
// Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
For sorting an array of strings, you can use the following code:
let fruits = ['apple', 'banana', 'kiwi', 'mango'];
fruits.sort();
console.log(fruits);
// Output: ['apple', 'banana', 'kiwi', 'mango']
JavaScript Array Iteration
JavaScript arrays have several ways to iterate or loop through its elements:
- for loop – traditional method for looping through an array.
let numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
// Output: 1 2 3 4 5
- forEach() method – executes a provided function once for each array element.
let numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
console.log(number);
});
// Output: 1 2 3 4 5
- map() method – creates a new array with the results of calling a provided function on every element in the calling array.
let numbers = [1, 2, 3, 4, 5];
let doubledNumbers = numbers.map(function(number) {
return number * 2;
});
console.log(doubledNumbers);
// Output: [2, 4, 6, 8, 10]
- for…of loop – allows to iterate over iterable objects, including arrays.
let numbers = [1, 2, 3, 4, 5];
for (const number of numbers) {
console.log(number);
}
// Output: 1 2 3 4 5
- Array.from() method – creates a new Array instance from an array-like or iterable object.
let numbers = Array.from([1, 2, 3, 4, 5]);
console.log(numbers);
// Output: [1, 2, 3, 4, 5]
JavaScript Array Const
In JavaScript, you can declare an array using the const
keyword to make the reference to the array constant, meaning you cannot reassign the reference to a new array, but you can still modify the elements within the array.
Here’s an example:
const fruits = ['apple', 'banana', 'kiwi'];
fruits.push('mango');
console.log(fruits);
// Output: ['apple', 'banana', 'kiwi', 'mango']
// This line will throw an errorfruits = [‘orange’, ‘grape’, ‘pear’];
In this example, fruits.push('mango')
is allowed because the push()
method modifies the existing array, while fruits = ['orange', 'grape', 'pear']
is not allowed because it attempts to reassign the constant reference to a new array.
JavaScript Date Objects
The Date
object in JavaScript represents a specific point in time, and allows you to work with dates and times.
Here’s an example of how to create a Date
object:
let now = new Date();
console.log(now);
// Output: Sun Jan 30 2022 12:34:56 GMT+0000 (Coordinated Universal Time)
You can also create a Date
object for a specific date and time by passing a string or numerical arguments to the Date
constructor:
let birthday = new Date('January 1, 2000');
console.log(birthday);
// Output: Sat Jan 01 2000 00:00:00 GMT+0000 (Coordinated Universal Time)
let launchDate = new Date(2022, 6, 14);console.log(launchDate);
// Output: Mon Jul 14 2022 00:00:00 GMT+0000 (Coordinated Universal Time)
Once you have a Date
object, you can extract its individual components such as the year, month, day, hour, etc. using the various get methods:
let now = new Date();
console.log(now.getFullYear());
// Output: 2022
console.log(now.getMonth());
// Output: 0 (January)
console.log(now.getDate());
// Output: 30
console.log(now.getHours());
// Output: 12
console.log(now.getMinutes());
// Output: 34
console.log(now.getSeconds());
// Output: 56
You can also use the set
methods to change the values of individual components:
let now = new Date();
now.setFullYear(2023);
console.log(now);
// Output: Sun Jan 30 2023 12:34:56 GMT+0000 (Coordinated Universal Time)
JavaScript Date Formats
In JavaScript, you can format a Date
object into a string representation using various methods, including:
- toString() method – returns a string representation of the date:
let date = new Date();
console.log(date.toString());
// Output: Sun Jan 30 2022 12:34:56 GMT+0000 (Coordinated Universal Time)
- toDateString() method – returns the date as a string, without the time:
let date = new Date();
console.log(date.toDateString());
// Output: Sun Jan 30 2022
- toUTCString() method – returns the date as a string, in UTC format:
let date = new Date();
console.log(date.toUTCString());
// Output: Sun, 30 Jan 2022 12:34:56 GMT
- toLocaleDateString() method – returns the date as a string, formatted based on the local date and time format:
let date = new Date();
console.log(date.toLocaleDateString());
// Output: 2022/1/30
- toLocaleTimeString() method – returns the time as a string, formatted based on the local date and time format:
let date = new Date();
console.log(date.toLocaleTimeString());
// Output: 12:34:56 PM
- toISOString() method – returns the date as a string, formatted as an ISO 8601 date:
let date = new Date();
console.log(date.toISOString());
// Output: 2022-01-30T12:34:56.000Z
- Custom format using template literals and various methods – allows you to create a custom string representation of the date:
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
console.log(`${year}-${month}-${day}`);
// Output: 2022-1-30
JavaScript Get Date Methods
Here are a few of the common methods to get the date in JavaScript:
new Date()
: creates a new Date object with the current date and timeDate.now()
: returns the number of milliseconds elapsed since January 1, 1970getFullYear()
: returns the year (4 digits) of the specified dategetMonth()
: returns the month (0-11) of the specified dategetDate()
: returns the day of the month (1-31) of the specified dategetHours()
: returns the hour (0-23) of the specified dategetMinutes()
: returns the minutes (0-59) of the specified dategetSeconds()
: returns the seconds (0-59) of the specified date.
Example:
let now = new Date();
console.log(now.getFullYear());
console.log(now.getMonth());
console.log(now.getDate());
console.log(now.getHours());
console.log(now.getMinutes());
console.log(now.getSeconds());
JavaScript Set Date Methods
Here are a few of the common methods to set the date in JavaScript:
setFullYear(year, [month], [date])
: sets the year (4 digits) for a specified datesetMonth(month, [date])
: sets the month (0-11) for a specified datesetDate(date)
: sets the day of the month (1-31) for a specified datesetHours(hours, [minutes], [seconds], [ms])
: sets the hour (0-23) for a specified datesetMinutes(minutes, [seconds], [ms])
: sets the minutes (0-59) for a specified datesetSeconds(seconds, [ms])
: sets the seconds (0-59) for a specified date
Example:
let now = new Date();
now.setFullYear(2022);
now.setMonth(5);
now.setDate(15);
now.setHours(10);
now.setMinutes(30);
now.setSeconds(0);
console.log(now);JavaScript Math Object
The JavaScript Math object provides properties and methods for mathematical constants and functions. Here are a few common methods of the Math object:
Math.abs(x)
: returns the absolute value of xMath.ceil(x)
: returns the smallest integer greater than or equal to xMath.floor(x)
: returns the largest integer less than or equal to xMath.max(a, b, c, ...)
: returns the largest of zero or more numbersMath.min(a, b, c, ...)
: returns the smallest of zero or more numbersMath.round(x)
: returns the value of x rounded to the nearest integerMath.sqrt(x)
: returns the square root of xMath.pow(x, y)
: returns the value of x raised to the power of yMath.random()
: returns a random number between 0 and 1
Example:
console.log(Math.abs(-4.7));
console.log(Math.ceil(4.4));
console.log(Math.floor(4.7));
console.log(Math.max(1, 2, 3, 4, 5));
console.log(Math.min(1, 2, 3, 4, 5));
console.log(Math.round(4.5));
console.log(Math.sqrt(16));
console.log(Math.pow(2, 3));
console.log(Math.random());
JavaScript Random
The Math.random()
method generates a random number between 0 (inclusive) and 1 (exclusive). To generate a random number within a specific range, you can use the following formula:
Math.floor(Math.random() * (max - min + 1)) + min;
Where min
is the minimum number in the range and max
is the maximum number in the range.
Example:
let randomNumber = Math.floor(Math.random() * 10) + 1;
console.log(randomNumber);
This will generate a random number between 1 and 10 (inclusive).
JavaScript Booleans
In JavaScript, a boolean is a data type that can have only two values: true
or false
. Booleans are often used in conditional statements to control the flow of a program.
Here are a few examples of boolean expressions in JavaScript:
let x = 5;
let y = 10;
console.log(x > y); // falseconsole.log(x < y); // true
console.log(x == y); // false
console.log(x != y); // true
console.log(!(x > y)); // true
Note that ==
compares values for equality and ===
compares both value and type for equality.
You can also use booleans in conditional statements, such as if/else:
let x = 5;
if (x > 0) {
console.log(“x is positive”);
} else {
console.log(“x is not positive”);
}
In JavaScript, you can compare values using comparison operators and combine multiple conditions using logical operators. Here are some of the common comparison and logical operators:
Comparison Operators:
>
: greater than<
: less than>=
: greater than or equal to<=
: less than or equal to==
: equal to (value only)===
: equal to (value and type)!=
: not equal to (value only)!==
: not equal to (value and type)
Logical Operators:
&&
: logical and (returnstrue
if both operands aretrue
,false
otherwise)||
: logical or (returnstrue
if either operand istrue
,false
otherwise)!
: logical not (returns the opposite of a boolean value)
Example:
let x = 5;
let y = 10;
console.log(x > 0 && y > 0); // trueconsole.log(x > 0 || y < 0); // true
console.log(!(x > 0)); // false
JavaScript if, else, and else if
In JavaScript, you can use the if
statement to execute a block of code only if a specified condition is true
. You can also use the else
statement to execute a block of code if the if
condition is false
, and the else if
statement to specify additional conditions.
Here’s the syntax of an if
statement:
if (condition) {
// code to be executed if condition is true
}
Here’s the syntax of an if
…else
statement:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Here’s the syntax of an if
…else if
…else
statement:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition1 is false and condition2 is true
} else {
// code to be executed if both condition1 and condition2 are false
}
Example:
let x = 5;
if (x > 0) {
console.log(“x is positive”);
} else if (x < 0) {
console.log(“x is negative”);
} else {
console.log(“x is zero”);
}
JavaScript Switch Statement
The switch
statement in JavaScript allows you to test an expression against multiple values, known as cases. When a match is found, the corresponding block of code is executed.
Here’s the syntax of a switch
statement:
switch (expression) {
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
...
default:
// code to be executed if no match is found
}
Note that each case must end with a break
statement to prevent the code from falling through to the next case. The default
case is optional, and it will be executed if no match is found.
Example:
let x = 2;
switch (x) {
case 1:
console.log(“x is 1”);
break;
case 2:
console.log(“x is 2”);
break;
case 3:
console.log(“x is 3”);
break;
default:
console.log(“x is not 1, 2, or 3”);
}
JavaScript For Loop
The for
loop in JavaScript allows you to repeat a block of code a specified number of times.
Here’s the syntax of a for
loop:
for (initialization; condition; increment) {
// code to be executed until condition is false
}
The initialization
expression is executed only once, before the loop starts. The condition
expression is evaluated before each iteration of the loop. If the condition is true
, the code block is executed. If the condition is false
, the loop stops. The increment
expression is executed after each iteration of the loop.
Example:
for (let i = 0; i < 5; i++) {
console.log(i);
}
This for
loop will print 0
, 1
, 2
, 3
, and 4
to the console.
JavaScript For In
The for...in
loop in JavaScript allows you to iterate over the properties of an object. It is commonly used to loop through the properties of an object to retrieve their values.
Here’s the syntax of a for...in
loop:
for (variable in object) {
// code to be executed for each property in object
}
The variable
is a temporary variable that holds the current property name of the object. The object
is the object whose properties you want to access.
Example:
let person = { name: "John", age: 30, job: "developer" };
for (let key in person) {
console.log(key + “: “ + person[key]);
}
This for...in
loop will print name: John
, age: 30
, and job: developer
to the console.
JavaScript For Of
The for...of
loop in JavaScript allows you to iterate over the values of an iterable object, such as an array, a string, or a Set.
Here’s the syntax of a for...of
loop:
for (variable of iterable) {
// code to be executed for each value in iterable
}
The variable
is a temporary variable that holds the current value of the iterable object. The iterable
is the object you want to iterate over.
Example:
let numbers = [1, 2, 3, 4, 5];
for (let number of numbers) {
console.log(number);
}
This for...of
loop will print 1
, 2
, 3
, 4
, and 5
to the console.
JavaScript While Loop
The while
loop in JavaScript allows you to repeat a block of code as long as a certain condition is true.
Here’s the syntax of a while
loop:
while (condition) {
// code to be executed while condition is true
}
The condition
expression is evaluated before each iteration of the loop. If the condition is true
, the code block is executed. If the condition is false
, the loop stops.
Example:
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
This while
loop will print 0
, 1
, 2
, 3
, and 4
to the console.
JavaScript Break and Continue
break
and continue
are two control statements in JavaScript that are used within looping structures (for
, while
, etc.).
break
is used to exit a loop early, before its normal termination condition is met. Once the break
statement is executed, the loop stops immediately and the program control resumes after the loop.
continue
is used to skip an iteration of a loop. When the continue
statement is executed, the current iteration is skipped and the next iteration begins.
Example:
for (let i = 0; i < 10; i++) {
if (i === 5) {
break;
}
console.log(i);
}
This for
loop will print 0
, 1
, 2
, 3
, 4
to the console, and then exit the loop immediately when i
reaches 5
.
Example:
for (let i = 0; i < 10; i++) {
if (i % 2 !== 0) {
continue;
}
console.log(i);
}
This for
loop will print 0
, 2
, 4
, 6
, 8
to the console, skipping the iteration when i
is odd.
JavaScript Iterables
An iterable in JavaScript is an object that implements the Symbol.iterator
method, which returns an iterator object. An iterator object is an object with a next
method that returns the next value of the iteration, along with a boolean value indicating whether the iteration has ended or not.
There are several built-in iterable objects in JavaScript, including arrays, strings, and Map and Set objects. You can also create your own iterable objects by defining the Symbol.iterator
method.
Example of using the for...of
loop with an array:
let numbers = [1, 2, 3, 4, 5];
for (let number of numbers) {
console.log(number);
}
This for...of
loop will print 1
, 2
, 3
, 4
, and 5
to the console.
Example of using the for...of
loop with a string:
let name = "John";
for (let letter of name) {
console.log(letter);
}
This for...of
loop will print J
, o
, h
, n
to the console.
JavaScript Sets
A Set is a collection of unique values in JavaScript. You can create a Set using the Set
constructor or the new
operator. The values in a Set can be of any type, including primitive and reference types.
Here’s the syntax for creating a Set:
let set = new Set();
You can add values to a Set using the add
method:
set.add(value);
Here’s an example of creating a Set and adding values to it:
let colors = new Set();
colors.add(“red”);
colors.add(“green”);
colors.add(“blue”);
console.log(colors.size); // 3
You can remove values from a Set using the delete
method:
set.delete(value);
You can check if a value exists in a Set using the has
method:
set.has(value);
You can also use the forEach
method to iterate over the values in a Set:
set.forEach(function(value) {
console.log(value);
});
In addition to the above methods, Sets also have several useful built-in methods like clear
, values
, keys
, and entries
for performing operations like clearing the Set, getting the values, keys, and entries in the Set.
JavaScript Maps
A Map is a collection of key-value pairs in JavaScript. You can create a Map using the Map
constructor or the new
operator. The keys and values in a Map can be of any type, including primitive and reference types.
Here’s the syntax for creating a Map:
let map = new Map();
You can add key-value pairs to a Map using the set
method:
map.set(key, value);
Here’s an example of creating a Map and adding key-value pairs to it:
let user = new Map();
user.set(“name”, “John”);
user.set(“age”, 30);
user.set(“email”, “[email protected]”);
console.log(user.size); // 3
You can remove key-value pairs from a Map using the delete
method:
map.delete(key);
You can get the value associated with a key in a Map using the get
method:
map.get(key);
You can check if a key exists in a Map using the has
method:
map.has(key);
You can also use the forEach
method to iterate over the key-value pairs in a Map:
map.forEach(function(value, key) {
console.log(key + ": " + value);
});
In addition to the above methods, Maps also have several useful built-in methods like clear
, values
, keys
, and entries
for performing operations like clearing the Map, getting the values, keys, and entries in the Map.
JavaScript typeof
The typeof
operator in JavaScript is used to get the data type of a value. It returns a string indicating the type of the operand. The possible values are:
- “undefined”
- “object”
- “boolean”
- “number”
- “string”
- “symbol”
- “function”
Here’s an example of using the typeof
operator:
let num = 10;
console.log(typeof num); // "number"
let name = “John”;console.log(typeof name); // “string”
let flag = true;console.log(typeof flag); // “boolean”
Note that the typeof
operator returns “object” for arrays, maps, and sets. To check if a value is an array, you can use the Array.isArray
method:
let arr = [1, 2, 3];
console.log(typeof arr); // "object"
console.log(Array.isArray(arr)); // true
JavaScript Type Conversion
Type conversion in JavaScript refers to the process of converting values from one data type to another. There are several methods available in JavaScript to perform type conversion, including:
Number(value)
: Converts a value to a numberString(value)
: Converts a value to a stringBoolean(value)
: Converts a value to a booleanparseInt(value)
: Converts a string to an integerparseFloat(value)
: Converts a string to a floating-point number
Here are some examples of type conversion:
let num = "10";
console.log(typeof num); // "string"
num = Number(num);console.log(typeof num); // “number”
let str = 10;console.log(typeof str); // “number”
str = String(str);console.log(typeof str); // “string”
let flag = “true”;console.log(typeof flag); // “string”
flag = Boolean(flag);console.log(typeof flag); // “boolean”
let n = “10.5”;console.log(typeof n); // “string”
n = parseFloat(n);
console.log(typeof n); // “number”
Note that type conversion in JavaScript can sometimes lead to unexpected results, so it’s important to be careful when converting values between different data types.
JavaScript Bitwise Operations
Bitwise operations in JavaScript allow you to manipulate individual bits within a number. Bitwise operations are performed using the following operators:
&
(and)|
(or)^
(xor)~
(not)<<
(left shift)>>
(right shift)>>>
(right shift with zero fill)
Here are some examples of using bitwise operations in JavaScript:
let a = 10; // binary representation: 00000000000000000000000000001010
let b = 6; // binary representation: 00000000000000000000000000000110
console.log(a & b); // 2 (binary: 00000000000000000000000000000010)console.log(a | b); // 14 (binary: 00000000000000000000000000001110)
console.log(a ^ b); // 12 (binary: 00000000000000000000000000001100)
console.log(~a); // -11 (binary: 11111111111111111111111111110101)
console.log(a << 1); // 20 (binary: 00000000000000000000000000010100)console.log(a >> 1); // 5 (binary: 00000000000000000000000000000101)
Note that bitwise operations in JavaScript are performed on 32-bit signed integers, so the results of these operations are limited to the range of values that can be represented by 32-bit integers.
JavaScript Regular Expressions
A regular expression (regex) is a sequence of characters that define a search pattern. In JavaScript, regular expressions are objects and are used to match, search, and replace strings.
Here’s an example of using regular expressions in JavaScript to search for a pattern in a string:
let str = "Hello, World!";
let pattern = /Hello/;
console.log(pattern.test(str)); // trueAnd here’s an example of using regular expressions to replace a pattern in a string:
let str = "Hello, World!";
let pattern = /Hello/;
let replacement = "Hi";
console.log(str.replace(pattern, replacement)); // “Hi, World!”There are many useful methods available for working with regular expressions in JavaScript, including test
, exec
, match
, replace
, search
, and split
. Regular expressions can also be used with the RegExp
object, which allows you to create complex patterns and perform more advanced operations with them.
JavaScript Operator Precedence
Operator precedence in JavaScript determines the order in which operations are performed in an expression. Higher precedence operators are performed before lower precedence operators. Here is a list of operator precedences in JavaScript, from highest to lowest:
()
(Parentheses).
(Property access)[]
(Array indexing)++
(Post-increment)--
(Post-decrement)++
(Pre-increment)--
(Pre-decrement)!
(Not)~
(Bitwise not)new
(Object creation)typeof
void
delete
+
(Positive)-
(Negative)*
(Multiplication)/
(Division)%
(Modulo)+
(Addition)-
(Subtraction)<<
(Left shift)>>
(Right shift)>>>
(Right shift with zero fill)<
(Less than)>
(Greater than)<=
(Less than or equal to)>=
(Greater than or equal to)instanceof
in
==
(Equal to)!=
(Not equal to)===
(Strict equal to)!==
(Strict not equal to)&
(Bitwise and)^
(Bitwise xor)|
(Bitwise or)&&
(Logical and)||
(Logical or)? :
(Ternary)=
(Assignment)+=
(Addition assignment)-=
(Subtraction assignment)*=
(Multiplication assignment)/=
(Division assignment)%=
(Modulo assignment)<<=
(Left shift assignment)>>=
(Right shift assignment)>>>=
(Right shift with zero fill assignment)&=
(Bitwise and assignment)^=
(Bitwise xor assignment)|=
(Bitwise or assignment),
(Comma)
You can use parentheses to specify the order of operations, if needed, like this:
let x = 4 + 5 * 6;
console.log(x); // 34
let y = (4 + 5) * 6;console.log(y); // 54
JavaScript Errors
There are several types of errors in JavaScript:
- Syntax errors: occur when the code is written incorrectly and does not follow the proper syntax.
- Reference errors: occur when an undefined variable is referenced.
- Type errors: occur when a value is not of the expected type.
- Range errors: occur when a number is outside of its valid range, such as a number that is too large or too small.
- EvalError: occurs when the eval() function is used incorrectly.
- URIError: occurs when encodeURI() or decodeURI() functions are used incorrectly.
- SecurityError: occurs when a security violation occurs.
- Custom errors: Developers can create custom error types by creating new instances of the Error object.
JavaScript Scope
Scope in JavaScript refers to the visibility and accessibility of variables and functions in different parts of your code. There are two types of scope in JavaScript:
- Global scope: Variables and functions declared outside of any function have global scope and can be accessed from anywhere in your code.
- Local scope: Variables and functions declared within a function have local scope and can only be accessed within that function.
In JavaScript, the scope is determined by the location of the curly braces {}. Variables and functions declared inside the curly braces of a function are only accessible within that function, while variables and functions declared outside of any function are considered to have global scope. The var keyword is used to declare variables in JavaScript, while the let and const keywords were introduced in ECMAScript 6 to provide block-level scope.
JavaScript Hoisting
Hoisting in JavaScript is a behavior in which variable and function declarations are moved to the top of their scope. This means that even though you may declare a variable or function later in your code, it is effectively moved to the top of its scope and can be used throughout the rest of the code.
For example, consider the following code:
console.log(hoistedVar);
var hoistedVar = "I'm a hoisted variable";
Even though the variable hoistedVar
is declared after the console.log
statement, it is still accessible and its value is "I'm a hoisted variable"
. This is because the variable declaration is hoisted to the top of its scope.
The same behavior occurs with function declarations:
hoistedFunc();
function hoistedFunc() {
console.log(“I’m a hoisted function”);
}
Here, the function hoistedFunc
can be called before it is declared because its declaration is hoisted to the top of its scope.
It is important to note that only the declarations are hoisted, not the assignments. For example:
console.log(notHoistedVar);
var notHoistedVar = "I'm not a hoisted variable";
In this case, the console.log
statement will throw a ReferenceError
, because only the declaration of notHoistedVar
is hoisted, not its assignment.
JS Strict Mode
Strict mode is a feature in JavaScript that provides a way to write safer, more secure code. When strict mode is enabled, JavaScript will enforce a set of restrictions that are intended to catch potential problems in your code.
In strict mode, the following behaviors are modified:
- Variables must be declared before they are used.
- The use of a variable before it has been declared will result in a ReferenceError.
- The use of a property on an undefined object will result in a TypeError.
- The use of the with statement is prohibited.
- Assignment to a non-writable property or a non-configurable property will result in an error.
- Attempts to delete an undeletable property will result in an error.
- Octal numeric literals and escape characters are not allowed.
Strict mode is optional and can be enabled on a per-function or per-script basis. To enable strict mode for a function, you can add the following statement at the beginning of the function:
;To enable strict mode for a script, you can add the following statement at the beginning of the script:
;Enabling strict mode is recommended for production-level code, as it can help you catch potential problems before they become more serious issues.
JS this Keyword
The this
keyword in JavaScript refers to the current object that the code is being executed within. The value of this
is determined by the context in which the code is executed, and it is often used to access properties and methods of the current object.
In most cases, this
refers to the object that was used to invoke the function that contains the this
keyword. For example:
const person = {
name: "John Doe",
sayHello: function() {
console.log(`Hello, my name is ${this.name}.`);
}
};
person.sayHello(); // Output: “Hello, my name is John Doe.”In the example above, this
refers to the person
object inside the sayHello
method, so this.name
returns "John Doe"
.
However, the value of this
can be changed by using the call
, apply
, or bind
methods. These methods allow you to explicitly set the value of this
when calling a function. For example:
const anotherPerson = { name: "Jane Doe" };
person.sayHello.call(anotherPerson); // Output: “Hello, my name is Jane Doe.”
In the example above, this
is set to anotherPerson
when the sayHello
method is called, so this.name
returns "Jane Doe"
.
It is important to understand how this
works in JavaScript, as it can lead to unexpected behavior if used improperly. It is recommended to use arrow functions or bind
when you want to ensure a specific value for this
.
JS Arrow Function
Arrow functions are a shorthand syntax for defining anonymous functions in JavaScript. They were introduced in ECMAScript 6 as a way to write more concise and expressive code.
The basic syntax for an arrow function is as follows:
const functionName = (arg1, arg2, ...) => {
// function body
};
For example, the following code defines a function that takes two arguments and returns their sum:
const add = (a, b) => {
return a + b;
};
console.log(add(2, 3)); // Output: 5If an arrow function only has one argument, the parentheses can be omitted:
const square = x => {
return x * x;
};
console.log(square(5)); // Output: 25If an arrow function only has one statement, the curly braces and the return
keyword can be omitted:
const double = x => x * 2;
console.log(double(5)); // Output: 10
One of the key differences between arrow functions and regular functions is the behavior of the this
keyword. In arrow functions, this
refers to the value of the enclosing lexical context, which means that it does not change based on how the function is called. This can make arrow functions particularly useful for handling events or working with objects.
For example:
const obj = {
name: "John Doe",
greet: function() {
setTimeout(() => {
console.log(`Hello, my name is ${this.name}.`);
}, 1000);
}
};
obj.greet(); // Output (after 1 second): “Hello, my name is John Doe.”In the example above, the greet
method uses an arrow function as the callback for the setTimeout
function. Because this
refers to the obj
object in the arrow function, this.name
returns "John Doe"
as expected.
JS Classes
JavaScript classes are a template for creating objects. They are based on object-oriented programming concepts, such as inheritance and encapsulation, and provide a syntax for organizing and structuring code. Classes in JavaScript are defined using the class
keyword and include a constructor method that is used to initialize the object and class methods that define the behavior of the object. Classes are useful for creating reusable objects with similar properties and behaviors, making it easier to manage and maintain large applications.
JS Modules
JavaScript modules are a way to organize and share code between different parts of an application. They allow developers to split code into multiple files, each containing a specific piece of functionality, and export specific parts of the code to be used in other parts of the application. Modules in JavaScript can be created using either the export
and import
keywords, or using module systems like CommonJS or ES6 modules. This helps to reduce code duplication and make it easier to maintain large applications by encapsulating code and keeping it separate from the rest of the application.
JS JSON
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate.
Here’s an example of a JSON object:
{
"name": "John Doe",
"age": 32,
"email": "[email protected]",
"address": {
"street": "123 Main St",
"city": "San Francisco",
"state": "CA"
}
}
And here’s an example of parsing this JSON object in JavaScript:
var json = '{"name": "John Doe","age": 32,"email": "[email protected]","address": {"street": "123 Main St","city": "San Francisco","state": "CA"}}';
var obj = JSON.parse(json);
console.log(obj.name); // “John Doe”
console.log(obj.age); // 32
console.log(obj.email); // “[email protected]”
console.log(obj.address.street); // “123 Main St”
JS Debugging
Debugging in JavaScript refers to the process of identifying and fixing errors or bugs in code. Here are some common methods for debugging in JavaScript:
console.log()
: Theconsole.log()
method is the simplest and most commonly used method for debugging. It allows you to log information to the browser’s console, which you can access from the developer tools in your browser.- Debugger statement: The
debugger
statement allows you to pause the execution of JavaScript code at a specific line. When you run the code, it will stop at thedebugger
statement, allowing you to examine the state of your code and variables at that point. - Breakpoints: Another way to pause the execution of code is by setting breakpoints in the debugger. You can set a breakpoint by clicking on the line number in the developer tools, and the code will pause when it reaches that line.
- Watch expressions: Watch expressions allow you to keep an eye on the values of specific variables while you’re debugging. You can add a watch expression in the developer tools to see how its value changes as the code executes.
- The
try...catch
statement: Thetry...catch
statement allows you to catch and handle errors in your code. If an error occurs in thetry
block, the code in thecatch
block will be executed, allowing you to log the error or take other actions to resolve it.
These are just a few of the methods you can use to debug JavaScript code. The specific method you choose will depend on the nature of the error you’re trying to resolve.
JS Style Guide
A style guide is a set of guidelines for writing code in a specific programming language. It’s designed to improve the readability and maintainability of code, and ensure that all code written within an organization follows a consistent style.
Here are some common JavaScript style guidelines:
- Use semicolons: Semicolons are used to end statements in JavaScript. It’s good practice to use them at the end of every statement, even though they are optional in some cases.
Example:
var x = 10;
var y = 20;
- Indentation: Use consistent indentation to indicate the structure of your code. A common indentation level is 2 spaces.
Example:
if (x > 10) {
console.log("x is greater than 10");
} else {
console.log("x is not greater than 10");
}
- Naming conventions: Use descriptive and meaningful names for variables, functions, and other identifiers. CamelCase is commonly used for variables and functions, and PascalCase is used for constructors and classes.
Example:
var firstName = "John";
var lastName = "Doe";
function addNumbers(x, y) {return x + y;
}
- White space: Use white space to separate code blocks and improve readability. For example, you should add a new line after the curly brace that opens a block, and before the curly brace that closes it.
Example:
if (x > 10) {
console.log("x is greater than 10");
} else {
console.log("x is not greater than 10");
}
- Commenting: Add comments to your code to explain what it does, especially for complex or non-obvious sections.
Example:
// Calculate the sum of two numbers
function addNumbers(x, y) {
return x + y;
}
These are just a few examples of JavaScript style guidelines. There are many more style guides available, and the specific guidelines you choose to follow will depend on the needs of your organization. The important thing is to choose a set of guidelines and stick to them consistently throughout your codebase.
JS Best Practices
JavaScript is a versatile and widely used programming language, and there are many best practices to keep in mind when writing JavaScript code. Here are some common best practices to follow:
- Keep code organized and modular: Write clean, organized, and well-structured code that is easy to maintain. Break your code into small, reusable functions, and use modules to organize related functionality.
- Use strict mode: Use “use strict” at the beginning of your code or individual functions to enable strict mode. This makes JavaScript run in a more secure and efficient manner, and can help you avoid common mistakes.
- Validate user input: Always validate user input to prevent security vulnerabilities and unexpected behavior. This includes checking for the correct type of data, as well as for data that is within a specified range or length.
- Minimize DOM manipulation: DOM manipulation can be slow and resource-intensive, so minimize the amount of DOM manipulation you do. Use JavaScript libraries like jQuery or React to perform complex DOM manipulations if necessary.
- Use modern JavaScript: Take advantage of modern JavaScript features like arrow functions, template literals, and destructuring. These features make code more concise and easier to read.
- Test and debug regularly: Test your code thoroughly and debug any issues as they arise. Use tools like Jest or Mocha to automate your testing, and use the browser’s developer tools to inspect and debug your code.
- Optimize for performance: Optimize your code for performance by minimizing the number of function calls, reducing the amount of data you process, and avoiding memory leaks.
- Keep code updated: Keep your code up to date by regularly checking for updates to libraries and tools, and updating your code to take advantage of new features and improvements.
These are just a few examples of best practices for writing JavaScript code. Following these practices will help you write high-quality, maintainable, and efficient code.
JS Mistakes
JavaScript is a powerful and flexible language, but it can be easy to make mistakes if you’re not careful. Here are some common mistakes that developers make when writing JavaScript code:
- Forgetting to use var or let/const: JavaScript uses function scoping, so if you forget to use
var
,let
, orconst
to declare a variable, it will become a global variable, which can cause unintended side effects and reduce the readability of your code. - Using == instead of ===:
==
performs type coercion, which can lead to unexpected results. Always use===
to check for equality, as it does not perform type coercion. - Off-by-one errors: Off-by-one errors can occur when iterating over arrays or other data structures. Make sure to keep track of your indices carefully, and always double-check your loops to make sure they are doing what you expect.
- Misusing callbacks: Callbacks are a powerful feature of JavaScript, but they can also be tricky to use. Make sure that you understand how callbacks work and how to use them correctly, and be careful to avoid callback hell by using promises, async/await, or other techniques.
- Incorrect use of this keyword:
this
refers to the object that a function is invoked on, but its value can be unpredictable in certain contexts. Make sure you understand howthis
works, and usebind
,call
, orapply
if necessary to control its value. - Not handling errors properly: Make sure to handle errors properly in your code by using try/catch blocks and providing meaningful error messages. This will help you catch and diagnose problems early on, and make your code more robust.
- Using global variables unnecessarily: Global variables can lead to naming collisions and make your code harder to maintain. Avoid using global variables unless they are truly necessary, and consider using modules or other techniques to minimize the number of global variables in your code.
These are just a few examples of common mistakes that developers make when writing JavaScript code. Being aware of these mistakes and taking steps to avoid them will help you write better, more reliable, and more maintainable code.
JS Performance
Performance is an important consideration when writing JavaScript code. Here are some tips for improving the performance of your JavaScript code:
- Minimize DOM manipulation: DOM manipulation can be slow and resource-intensive, so minimize the amount of DOM manipulation you do. Use JavaScript libraries like jQuery or React to perform complex DOM manipulations if necessary.
- Minimize the number of function calls: Every time you call a function, JavaScript must create a new execution context, which can be slow and consume a lot of memory. Minimize the number of function calls you make, and consider using inline functions or other techniques to reduce the number of function calls you make.
- Use lazy loading: Lazy loading is a technique for loading resources only when they are needed, rather than loading all resources upfront. This can help improve the performance of your code by reducing the amount of data that needs to be loaded and processed.
- Optimize memory usage: JavaScript is a garbage-collected language, but that doesn’t mean you should ignore memory usage. Make sure to deallocate memory when you no longer need it, and avoid memory leaks that can slow down your code.
- Use modern JavaScript features: Take advantage of modern JavaScript features like arrow functions, template literals, and destructuring. These features can make your code more concise and efficient.
- Use a build system: Use a build system like Webpack or Babel to optimize your code for production. This can help reduce the size of your code, minify it, and perform other optimizations that can improve the performance of your code.
- Test and profile regularly: Test your code thoroughly, and use tools like the browser’s developer tools or other profiling tools to identify and optimize performance bottlenecks. Regularly profiling your code can help you identify and fix performance issues early on, and ensure that your code stays fast and responsive.
By following these tips and focusing on performance, you can write JavaScript code that is fast, efficient, and responsive, and that provides a great user experience.
JS Reserved Words
JavaScript has a set of reserved words, which are words that have a specific meaning in the language and cannot be used as variable names, function names, or other identifiers. Here is a list of the reserved words in JavaScript:
abstract
await
boolean
break
byte
case
catch
char
class
const
continue
debugger
default
delete
do
double
else
enum
export
extends
false
final
finally
float
for
function
goto
if
implements
import
in
instanceof
int
interface
let
long
native
new
null
package
private
protected
public
return
short
static
super
switch
synchronized
this
throw
throws
transient
true
try
typeof
var
void
volatile
while
with
yield
These reserved words are a part of the syntax of the language, and cannot be used as identifiers. If you try to use a reserved word as an identifier, you will get a syntax error. To avoid this, make sure to use a different name that is not a reserved word.
JavaScript Versions
JavaScript is a high-level, interpreted programming language widely used for web development. It has undergone several changes and updates since its inception in 1995. Here’s a list of the major versions of JavaScript:
- JavaScript 1.0 (Netscape) – This was the first version of JavaScript, released in 1995.
- JavaScript 1.1 (Netscape) – This version was released in 1996 and had minor updates from JavaScript 1.0.
- JavaScript 1.2 (Netscape) – This version was released in 1996 and had some new features such as the ‘with’ statement.
- JavaScript 1.3 (Netscape) – This version was released in 1997 and had improvements in the core language and its performance.
- JavaScript 1.4 (Netscape) – This version was never released to the public and was intended for Netscape’s server-side JavaScript.
- JavaScript 1.5 (Mozilla) – This version was released in 1998 and had many new features such as regular expressions and improved error handling.
- JavaScript 1.6 (Mozilla) – This version was released in 2005 and had new array and string methods, as well as improvements in performance.
- JavaScript 1.7 (Mozilla) – This version was released in 2006 and had new features such as destructuring and let expressions.
- JavaScript 1.8 (Mozilla) – This version was released in 2008 and had new features such as generator functions and expression closures.
- JavaScript 1.8.5 (Mozilla) – This version was released in 2009 and had bug fixes and security improvements.
- JavaScript 1.9 (Mozilla) – This version was released in 2011 and had new features such as array comprehensions and destructuring parameters.
- JavaScript 2.0 (Mozilla) – This version was never released and was intended to be a major revision of the language.
- ECMAScript (European Computer Manufacturers Association) – This version is an international standard for the language and is not tied to any particular vendor or browser. The first version of ECMAScript (ES1) was released in 1997 and had the same features as JavaScript 1.3. The latest version of ECMAScript (ES2022) was released in 2021 and has many new features such as optional chaining, null coalescing, and BigInt.
Note: The versions of JavaScript are often referred to as ECMAScript, although the two terms are often used interchangeably.
JS Objects
Object Definitions
In JavaScript, an object is a collection of properties and methods that are used to represent a real-world entity or concept. Objects are the fundamental building blocks of the language and are used to model data and behavior.
Each property of an object has a name and a value. The value of a property can be a primitive data type such as a string, number, or Boolean, or it can be another object.
Methods are functions that are associated with an object and can be used to perform actions or manipulate the object’s properties.
There are several ways to create an object in JavaScript:
- Object Literals – Objects can be created using object literals, which are denoted using curly braces {}. For example:
var person = {
name: "John Doe",
age: 30,
greet: function() {
console.log("Hello, my name is " + this.name);
}
};
- The Object Constructor – The
Object
constructor can be used to create an object. For example:
var person = new Object();
person.name = "John Doe";
person.age = 30;
person.greet = function() {
console.log("Hello, my name is " + this.name);
};
- Object.create() – The
Object.create()
method can be used to create an object and specify its prototype. For example:
var person = Object.create(null);
person.name = "John Doe";
person.age = 30;
person.greet = function() {
console.log("Hello, my name is " + this.name);
};
- Factory Functions – A factory function is a function that returns an object and can be used to create objects. For example:
function createPerson(name, age) {
return {
name: name,
age: age,
greet: function() {
console.log("Hello, my name is " + this.name);
}
};
}
var person = createPerson(“John Doe”, 30);
- Constructor Functions – A constructor function is a function that is used to create objects and is invoked using the
new
operator. For example:
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log("Hello, my name is " + this.name);
};
}
var person = new Person(“John Doe”, 30);
Object Properties
In JavaScript, an object property is a value that is associated with a specific object and has a unique name. Properties are used to represent the characteristics or attributes of an object.
There are two types of properties in JavaScript:
- Data Properties – Data properties are properties that hold a value. For example:
var person = {
name: "John Doe",
age: 30
};
In this example, name
and age
are data properties of the person
object.
- Accessor Properties – Accessor properties are properties that have a getter function and/or a setter function. Accessor properties are used to control access to an object’s properties. For example:
var person = {
_name: "John Doe",
_age: 30,
get name() {
return this._name;
},
set name(value) {
this._name = value;
}
};
In this example, name
is an accessor property of the person
object. The get
function returns the value of the _name
property and the set
function sets the value of the _name
property.
Properties can be added, updated, or deleted from an object using the dot notation (.
) or square bracket notation ([]
). For example:
person.age = 31; // updates the age property
person.address = "123 Main St"; // adds a new property
delete person.age; // deletes the age property
Object Methods
In JavaScript, objects can have methods, which are functions that are associated with an object. Here is an example of how you can add methods to an object in JavaScript:
let person = {
firstName: "John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
console.log(person.fullName());// Output: “John Doe”
In the example above, the fullName
method is associated with the person
object and can be invoked using the dot notation. The this
keyword refers to the object on which the method is being called, which in this case is person
.
You can also add methods to objects using the object literal syntax:
let car = {
brand: "Toyota",
model: "Camry",
getDescription: function() {
return this.brand + " " + this.model;
}
};
console.log(car.getDescription());// Output: “Toyota Camry”
You can also add methods to objects using the constructor function and the prototype
property:
function Person(first, last) {
this.firstName = first;
this.lastName = last;
}
Person.prototype.fullName = function() {return this.firstName + ” “ + this.lastName;
};
let person = new Person(“John”, “Doe”);
console.log(person.fullName());
// Output: “John Doe”
In this example, the Person
constructor function creates new Person
objects, and the fullName
method is added to the prototype of the Person
object, so it can be used by all instances of the Person
object.
Object Display
In JavaScript, you can display the contents of an object in various ways, including the following:
- Using
console.log
:
let person = {
firstName: "John",
lastName: "Doe"
};
console.log(person);// Output: {firstName: “John”, lastName: “Doe”}
- Using a
for...in
loop:
let person = {
firstName: "John",
lastName: "Doe"
};
for (let key in person) {console.log(key + “: “ + person[key]);
}
// Output:
// firstName: John
// lastName: Doe
- Using
JSON.stringify
:
let person = {
firstName: "John",
lastName: "Doe"
};
console.log(JSON.stringify(person));// Output: {“firstName”:“John”,“lastName”:“Doe”}
JSON.stringify
is a global function in JavaScript that converts a JavaScript object or value to a JSON string. The resulting string can be used to transmit data between a client and a server, or to save data to a file.
- Using the
Object.entries
method:
let person = {
firstName: "John",
lastName: "Doe"
};
console.log(Object.entries(person));// Output: [[“firstName”, “John”], [“lastName”, “Doe”]]
Object.entries
is a method in JavaScript that returns an array of arrays, where each inner array contains a key/value pair of an object.
Object Accessors
In JavaScript, object accessors (also known as getters and setters) are special methods that provide access to an object’s properties. Getter methods allow you to retrieve the value of an object’s property, while setter methods allow you to set the value of an object’s property.
Here is an example of how you can use getters and setters in JavaScript:
let person = {
firstName: "John",
lastName: "Doe",
get fullName() {
return this.firstName + " " + this.lastName;
},
set fullName(name) {
let parts = name.split(" ");
this.firstName = parts[0];
this.lastName = parts[1];
}
};
console.log(person.fullName);// Output: “John Doe”
person.fullName = “Jane Doe”;
console.log(person.fullName);
// Output: “Jane Doe”
In the example above, the fullName
getter method returns the full name of the person, while the fullName
setter method sets the first name and last name of the person based on the provided full name.
Getter and setter methods are defined using the get
and set
keywords, respectively. To access a getter method, you use the property name like a normal property, without invoking it like a regular function. To access a setter method, you use the property name followed by an assignment, like a normal property.
Note that getters and setters are supported in modern browsers, but may not be supported in older browsers. If you need to support older browsers, you can use a regular function for getting and setting object properties.
Object Constructors
In JavaScript, an object constructor is a special function that is used to create objects. The constructor function sets the initial properties of the object and sets up the methods that the object will have.
Here’s an example of a simple object constructor in JavaScript:
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
let person = new Person(“John”, “Doe”);console.log(person.firstName);
// Output: “John”
console.log(person.lastName);
// Output: “Doe”
In the example above, the Person
function acts as a constructor for the Person
object. When you use the new
keyword to create a new instance of the Person
object, the constructor function is executed, and a new Person
object is created. The Person
object has two properties, firstName
and lastName
, which are set to the values passed to the constructor.
You can also add methods to an object constructor:
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.fullName = function() {
return this.firstName + " " + this.lastName;
};
}
let person = new Person(“John”, “Doe”);console.log(person.fullName());
// Output: “John Doe”
In the example above, the Person
constructor function includes a method fullName
that returns the full name of the person. The method is assigned to the fullName
property of the Person
object. When you create a new Person
object, you can use the fullName
method to retrieve the full name of the person.
Note that when you create an object using a constructor, each instance of the object has its own copy of the methods, so changes to the methods in one instance of the object do not affect other instances of the object.
Object Prototypes
In JavaScript, prototypes are a way to create a relationship between objects. An object’s prototype is another object that it inherits properties and methods from. When an object doesn’t have a property or method that’s being accessed, the JavaScript engine will look in the object’s prototype to see if it has the property or method.
Here’s an example of using prototypes in JavaScript:
let person = {
firstName: "John",
lastName: "Doe"
};
let employee = Object.create(person);employee.jobTitle = “Developer”;
console.log(employee.firstName);
// Output: “John”
console.log(employee.jobTitle);
// Output: “Developer”
In the example above, the person
object acts as the prototype for the employee
object. The employee
object inherits the properties and methods from the person
object, but it can also have its own properties and methods.
You can also use prototypes with constructors:
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Person.prototype.fullName = function() {return this.firstName + ” “ + this.lastName;
};
let person = new Person(“John”, “Doe”);
console.log(person.fullName());
// Output: “John Doe”
In the example above, the Person
constructor function includes a method fullName
that is added to the Person.prototype
object. The Person.prototype
object acts as the prototype for all instances of the Person
object. When you create a new Person
object, you can use the fullName
method to retrieve the full name of the person, even though the method is not directly defined on the object.
Note that prototypes allow you to share properties and methods between objects, which can help you to write more efficient and organized code. However, it’s important to use prototypes carefully, as they can also make your code more complex and harder to understand if used improperly.
Object Iterables
In JavaScript, iterables are objects that can be iterated over, meaning that you can loop through the elements of the object one by one. An iterable must have a Symbol.iterator
property that specifies how to access the elements of the object.
Here’s an example of using an iterable in JavaScript:
let array = [1, 2, 3];
for (let value of array) {
console.log(value);
}
// Output:
// 1
// 2
// 3
In the example above, the array
is an iterable, and the for...of
loop can be used to loop through the elements of the array.
You can also create your own iterables in JavaScript:
let iterable = {
[Symbol.iterator]() {
let i = 0;
return {
next() {
return {
value: i++,
done: i > 10
};
}
};
}
};
for (let value of iterable) {console.log(value);
}
// Output:
// 0
// 1
// 2
// …
// 9
In the example above, the iterable
object has a Symbol.iterator
property that returns an iterator object. The iterator object has a next
method that is used to access the next element of the iterable. When the next
method returns an object with a done
property set to true
, the iteration stops.
Iterables are widely used in JavaScript, and you can find them in many built-in objects, such as arrays, maps, and sets. They allow you to write more concise and readable code, and they are a key part of the language.
Object Sets
In JavaScript, a Set is a collection of unique values, with no duplicates. It’s similar to an array, but it doesn’t allow duplicate values. You can use a Set to store any type of values, including primitive values (such as numbers and strings) and objects.
Here’s an example of using a Set in JavaScript:
let set = new Set();
set.add(1);
set.add(2);
set.add(3);
set.add(1);
console.log(set.size);
// Output: 3
for (let value of set) {
console.log(value);
}
// Output:
// 1
// 2
// 3
In the example above, we create a new Set using the Set
constructor, and we add some values to the Set using the add
method. The size
property returns the number of elements in the Set, which is 3 in this case (even though we added the value 1 twice, it only appears once in the Set). We can use a for...of
loop to loop through the elements of the Set, just like we would with an array.
You can also create a Set from an array:
let array = [1, 2, 3, 1];
let set = new Set(array);
console.log(set.size);// Output: 3
for (let value of set) {
console.log(value);
}
// Output:
// 1
// 2
// 3
In the example above, we create a Set from an array using the Set
constructor. The duplicates from the array are automatically removed when the Set is created, so the size
property returns 3, just like in the previous example.
Sets provide an easy way to store and manipulate collections of unique values in JavaScript. They are very useful in many situations, such as when you need to remove duplicates from an array, or when you need to store a collection of values without allowing duplicates.
Object Maps
In JavaScript, a Map is a collection of key-value pairs, similar to an object. However, unlike objects, Maps can have keys of any type, including primitive values (such as numbers and strings) and objects, not just strings.
Here’s an example of using a Map in JavaScript:
let map = new Map();
map.set(‘name’, ‘John’);
map.set(‘age’, 30);
map.set(‘city’, ‘New York’);
console.log(map.size);
// Output: 3
console.log(map.get(‘name’));
// Output: John
for (let [key, value] of map) {
console.log(`${key}: ${value}`);
}
// Output:
// name: John
// age: 30
// city: New York
In the example above, we create a new Map using the Map
constructor, and we add some key-value pairs to the Map using the set
method. The size
property returns the number of key-value pairs in the Map, which is 3 in this case. We can use the get
method to retrieve the value associated with a given key, and we can use a for...of
loop to loop through the key-value pairs of the Map.
You can also create a Map from an array of key-value pairs:
let array = [['name', 'John'], ['age', 30], ['city', 'New York']];
let map = new Map(array);
console.log(map.size);// Output: 3
console.log(map.get(‘name’));
// Output: John
for (let [key, value] of map) {
console.log(`${key}: ${value}`);
}
// Output:
// name: John
// age: 30
// city: New York
In the example above, we create a Map from an array of key-value pairs using the Map
constructor. The key-value pairs are automatically added to the Map, so the size
property returns 3, just like in the previous example.
Maps provide an easy way to store and manipulate collections of key-value pairs in JavaScript. They are very useful in many situations, such as when you need to store values associated with keys of different types, or when you need to store a collection of key-value pairs without having to use objects.
Object Reference
In JavaScript, objects are reference types, which means that when you assign an object to a variable, you are not creating a new instance of the object, but instead you are creating a reference to the original object.
Here’s an example that illustrates the concept of object reference in JavaScript:
let person = { name: 'John', age: 30 };
let anotherPerson = person;
console.log(person === anotherPerson);// Output: true
anotherPerson.name = ‘Jane’;
console.log(person.name);
// Output: Jane
In the example above, we create an object person
with a name and an age. Then, we create another variable anotherPerson
and assign person
to it. The ===
operator checks if person
and anotherPerson
are the same object, and it returns true
because they are both references to the same object.
When we change the name
property of anotherPerson
, it also changes the name
property of person
, because both variables are references to the same object.
If we want to create a new object that is a copy of the original object, we need to use a method that creates a new object and not just a reference to the original object. Here’s an example:
let person = { name: 'John', age: 30 };
let anotherPerson = Object.assign({}, person);
console.log(person === anotherPerson);// Output: false
anotherPerson.name = ‘Jane’;
console.log(person.name);
// Output: John
In the example above, we use the Object.assign
method to create a new object anotherPerson
that is a copy of the original object person
. Now, person
and anotherPerson
are not the same object, and changing the name
property of anotherPerson
does not change the name
property of person
.
It’s important to understand the concept of object reference in JavaScript, especially when working with objects and manipulating them. In many situations, you may need to create a new object that is a copy of an existing object, rather than just creating a reference to the original object.