BigBinary JavaScript 3.
10
const is short for "constant". It is used to create a variable whose value is not
intended to be changed at all, once it is created.
if we know that the value of the variable needs to be changed later, we need to
declare the variable using the let keyword.
* until a value is assigned to the variable declared using let, it will contain the
value undefined.
In JavaScript, const is used to declare variables. In JavaScript, not only can
const be used to declare variables, but it's also the most recommended way to
create variables.
First, let's see an example.
const fruit= {name: "Apple"}
fruit.name = "Banana"
Code output
{name: "Banana"}
In the above case, we can change fruit even though it's declared as a const.
However, if we try to achieve the same result by assigning a new object, then const
will not allow us to do so.
javascript
const fruit = { name: "Apple" }
Uncaught TypeError: Assignment to constant variable.
Code output
Assignment vs Mutation
To better understand what's going on here, we need to understand the difference
between Assignment and Mutation.
let's take an example of an array.
["Apple", "Banana", "Mango"]
This is a valid JavaScript code. When JavaScript sees this statement, it creates an
array in the memory. Before this statement, the memory would be empty and look like
this.
After that statement, the memory will look like this.
let fruits = ["Apple", "Banana", "Mango"]
Now, we are assigning that array to a variable. The equal sign here acts like an
assignment.
Now, in memory, we have a variable called "fruits," which points to the array.
fruits-variable-assignment.png
Now, let's create one more variable.
let cities = ["Paris", "London", "Chicago"]
Now we have two variables, "cities" and "fruits" and the memory would look like
this.
Now, let's assign a different value to the "fruits" variable.
fruits = ["Strawberry", "Blueberry"]
Now, the memory looks like this.
As we can see, fruits point to a different array because of this assignment. We
have not changed the original array. We have created a new array, which is what
Fruits is now pointing to. This is because the variable fruits is assigned a new
value.
Now let's change the first item in "cities" to "Tokyo".
cities[0] = "Tokyo"
In this case, the existing item was changed. This is called mutation. In this case,
there was no "assignment" using = sign. Notice that in the case of mutation, the
variable didn't change what it's pointing to. All variables continue to point to
the same item. It's the item that itself changed. This is mutation.
Differences between let and const
Once a variable is pointing to something, then let allows us to assign a different
item to the variable so that the variable can point to something else.
const doesn't allow that. In the case of const, once a variable points to an item,
JavaScript will not allow us to change the variable to something else. However,
JavaScript allows us to change the item to which let and const are pointing. In
other words, both let and const allow mutation, but only let allows assigning new
values.
Declaration without const or let
- we can create variables without using const or let keyword but it is a bad
practice and it should be avoided.
Data Types
- String
- Number
- Boolean
- Undefined
- object
Strictly Equality
- It requires both the value and the type of the operands to be the same to return
true
const objOne = { name: "Smith" };
const objTwo = { name: "Smith" };
console.log(objOne === objTwo);
In the above code, objOne and objTwo have the same structure but are stored in
different memory locations, so they are not strictly equal.
Rules for Type Coercion
- When one operand is a string, the other will be coerced into a string as well.
Similarly, if one operand is a number, the other will be converted into a number.
- Boolean operands are converted into numbers, where true becomes 1 and false
becomes 0.
- When comparing an object to a primitive value (string, number or boolean), the
object is first converted into a primitive value before the comparison is
performed.
- For null or undefined, the comparison returns true only if both operands are
either null or undefined.
Template Strings- enclosed within backticks i.e.. string interpolation
console.log(`Adding ${firstNum} and ${secondNum} gives ${result}`);
We can insert the values of variables into a template string using the ${}
notation. This is known as string interpolation.
console.log(`Your balance is ${totalIncome - totalExpense}`);
NaN
- Not a number
- type of NaN
- used in mathematical operations.
A variable declared using let, whose value hasn't been assigned yet, has undefined
as it's default value.
Null Data type
- When a variable is undefined, it means it has been given no value to hold.
Whereas, when a variable is null, it means the variable has a value, the value
null.
OBJECT
- An object can have multiple properties, where each property consists of a key and
a value, separated by commas.
If the key and the value of a property are the same, you can use the shorthand
syntax by simply writing the variable name.
const seatingCapacity = 5;
const fuelType = "petrol";
const car = {
model: 2011,
seatingCapacity,
fuelType
};
const result = `It is a ${car.model} model car that runs on ${car.fuelType} and has
${car.seatingCapacity} seats.`
console.log(result);
- we can read the values of object using dot notation.
Add Object Property using Dot Notation
- const person = {
fullName: "Adam Smith",
age: 37,
isAdmin: true
};
person.profession = "Engineer";// This property is added to the person Object
console.log(person);
const person = {
12: "Adam",
13: "Samantha"
};
console.log(person.12);
Using the dot operator in the above code will give the error
- This is because the dot operator needs the key name to be a proper variable name.
And in JS u cannot have a variable name starts with number.
- To access this we use bracket notation.
const person = {
12: "Adam",
13: "Samantha"
};
console.log(person[12]);
const project = {
"project-lead": "Adam",
developer: "Samantha"
};
console.log(project["project-lead"]);
const subjects = {
101: "Physics",
102: "Biology",
103: "Chemistry"
};
subjects.104 = "Mathematics";
console.log(subjects);
- This is because, the name of the key is not a proper variable name. Now, to add
the value of this property, we must use the bracket notation.
const subjects = {
101: "Physics",
102: "Biology",
103: "Chemistry"
};
subjects[104] = "Computer";
subjects[21 * 5] = "Mathematics"; // Same as subjects[105] = "Mathematics"
console.log(subjects);
- The dot notation should only be used if the key that we are intending to add or
update in the object, has a valid variable name.
Get Object Keys- Object.keys()
- returns an array of strings
const person = {
fullName: "Adam Smith",
age: 37,
isAdmin: true
};
const result = Object.keys(person);
console.log(result);
Get Object Values - Object.values()
- returns the values as an array of different types.
const person = {
fullName: "Adam Smith",
age: 37,
isAdmin: true
};
const result = Object.values(person);
console.log(result);
Get Object Keys and Values- Object.entries()
- we can get all key-value pairs of an object using Object.entries().
- returns key-value pairs as an array of arrays.
const person = {
fullName: "Adam Smith",
age: 37,
isAdmin: true
};
const result = Object.entries(person);
console.log(result);
Output:
(3) [Array(2), Array(2), Array(2)]
0: (2) ["fullName", "Adam Smith"]
1: (2) ["age", 37]
2: (2) ["isAdmin", true]
- Object.entries(person) returns an array in which all the elements are also
arrays. In other words, Object.entries(person) returns an array with many arrays
nested in it.
- Each nested array contains the key and the value of a property of person, in that
same order. The keys will be strings.
Since the first property of person is fullName: "Adam Smith", the first nested
array contains the elements - "fullName" and "Adam Smith".
Remove Property from object
- use delete to remove a property from an object.
const person = {
fullName: "Sam Smith",
age: 37,
isAdmin: true
};
delete person.age;
delete person[`isAdmin`];
console.log(person);
ARRAYS
- used to store multiple values together
const fruits = ["Apple", "Orange", "Banana"];
console.log(fruits);
- If the elements are not stored in increasing indexes then the between indexes are
all undefined.
Arrays-
- push method is used to add a new element to the end of array.
const vegetables = ["corn", "carrot", "potato"];
vegetables.push("beetroot");
console.log(vegetables);
- unshift operator used to add a new element at the beginning of an array.
const vegetables = ["corn", "carrot", "potato"];
vegetables.unshift("beetroot");
console.log(vegetables);
- pop method removes last element of an array
const sports = ["Football", "Cricket", "Basketball"];
sports.pop();
console.log(sports);
The pop() method also returns the element that was removed
const sports = ["Football", "Cricket", "Basketball"];
const lastElement = sports.pop();
console.log(lastElement);
- shift method removes first element of an array.
const sports = ["Football", "Cricket", "Basketball"];
sports.shift();
console.log(sports);
- .length is used to get the number of elements in an array.
TRUTHY AND FALSY VALUES
- Values such as the number 0, false, null, undefined, NaN, and the empty string
"", will get converted to false. These values are called falsy values.
- All the values we have mentioned above, except the falsy values, are truthy
values.
NULLISH COALESCING OPERATOR
- denoted as ??, returns the left-hand operand provided that the left-hand operand
is not null or undefined. Otherwise, it returns the right-hand operand.
TYPE CONVERSIONS:
1. Converting to String
- String() or toString() to convert a non-string value to a string.
console.log(2);
console.log(String(2));
console.log((2).toString());
- Boolean to String
console.log(true);
console.log(String(true));
console.log(true.toString());
* When we need to convert null or undefined into a string, we can only use
String(). Using toString() in such cases can give us an error.
2. Converting to Number
- String which contains a valid number will get converted into Number
const string = "2";
console.log(string);
const number = Number(string);
console.log(number);
* null gets converted to 0, while undefined gets converted to NaN.
* Calling Number() on NaN returns NaN itself.
3. isNaN method
- checks whether a value is NaN when converted into a number
const greeting = "Good Morning!";
console.log(greeting, isNaN(greeting));
const string = "Hello!";
console.log(string, isNaN(string));
console.log(`"2"`, isNaN("2"));
console.log(`false`, isNaN(false));
console.log(`0`, isNaN(0));
console.log(`""`, isNaN(""));
Function Expression
- a function can be assigned to a variable in an expression.
- here the function has no name, the variable name serves as the function name.
- function without name is called anonymous function.
const displayValidationError = function () {
console.log("The user details are not valid.");
}
displayValidationError();
Arrow Function
- Arrow function is basically an expression assigned to a variable. In the example
above, the arrow function is assigned to the variable displayValidationError. The
Arrow function expression starts with the parentheses (), followed by the arrow
operator =>, and the function body.
const displayValidationError = () => {
console.log("The user details are not valid.");
}
displayValidationError();
const greeting = (greetingType) => {
console.log(greetingType);
}
greeting("Hi");
greeting("Hello");
greeting("Welcome");
Parameters
- While defining a function, if we include a list of variables in between the ()
parentheses, they are called parameters
Arguments
- To call a function that has parameters, we need to provide the values in the
function call. These are called arguments.
For arrow functions with only one parameter, we don't need the parentheses ()
around the parameters.
const displayAge = (age) => {
console.log(`The user is ${age} years old.`);
}
displayAge(24);
can also be written as
const displayAge = age => {
console.log(`The user is ${age} years old.`);
}
displayAge(24);
Default Parameters
- Default parameters are function parameters that use a specified value as the
default value if a function call passes undefined to that parameter.
const displayValidationError = (invalidFieldName, additionalMessage = "") => {
const result = `The user ${invalidFieldName} is not valid. ${additionalMessage}`;
console.log(result);
}
displayValidationError("name");
const displayValidationError = (invalidFieldName, additionalMessage = "") => {
console.log(`The user ${invalidFieldName} is not valid. ${additionalMessage}`);
}
displayValidationError("name", undefined);
displayValidationError("name");
displayValidationError();
displayValidationError("name", null);
displayValidationError("name", undefined) - This passes undefined to the
additionalMessage parameter and hence additionalMessage will be set as "", the
default value.
displayValidationError("name") - Since the second argument is omitted,
additionalMessage will receive undefined. Hence, additionalMessage will be set as
"", the default value.
displayValidationError() - Since both the arguments are omitted, both
invalidFieldName and additionalMessage will receive undefined. Since
invalidFieldName does not have a default value, its value will remain as undefined.
However, additionalMessage will be assigned the default value "".
displayValidationError("name", null) - invalidFieldName gets the value "name" and
additionalMessage gets the value null.
Function as a Property of an Object
- we can store function as property of an object. Such properties are called
methods.
const admin = {
name: "Adam Smith",
age: 45,
}
admin.displayGreeting = () => console.log("Hello World");
admin.displayGreeting();
Callback Function
- you can define a function and pass it as an argument to another function. Such a
function, is called a callback function.
const validateSolution = (solution, statusMessage) => {
if (solution === 11) {
statusMessage(true);
} else {
statusMessage(false);
}
};
const statusMessage = (status) => {
if (status) {
console.log("Great! Your answer is correct!");
} else {
console.log("Oops! Your answer is incorrect. Please try again.");
}
};
const solution = 11;
validateSolution(solution, statusMessage);
Anoymous function
- function with no name.
- use this in situations where we don't want to reuse the functionality.
- // Run the function defined with the function keyword without saving it in a
variable
(function () {
console.log("Function Keyword");
})();
// Run the arrow function without saving it in a variable
(() => {
console.log("Arrow Function");
})();